Files
web2.0-backend/infoscreen/management/commands/importabb.py
T
2016-09-01 18:40:45 +03:00

47 lines
1.8 KiB
Python

from django.core.management.base import BaseCommand, CommandError
from django.db.models import Max
from django.conf import settings
from datetime import datetime, timedelta
from pytz import utc
from paramiko.client import SSHClient, AutoAddPolicy, RSAKey
from infoscreen.models import ABBJob
import qrcode
class Command(BaseCommand):
help = 'import new abbjobs from oldish sikweb'
def add_arguments(self, parser):
parser.add_argument('keypath')
def handle(self, *args, **options):
last_id = ABBJob.objects.aggregate(Max('sw_id'))['sw_id__max'] or 0
client = SSHClient()
client.set_missing_host_key_policy(AutoAddPolicy())
key = RSAKey.from_private_key_file(options.get("keypath"))
client.connect("otax.ayy.fi", username="sik", pkey=key)
stdin, stdout, stderr = client.exec_command("./abbjobexport.sh {}".format(last_id))
errors = stderr.read()
if len(errors) > 0:
print(errors)
client.close()
return
data = stdout.read().decode("latin1").strip().split("\n") # shame on latin1 otax!!!
for row in data:
if not row:
continue
cols = row.split('\t',maxsplit=2)
qr_url = gen_qr(cols[0])
created = datetime.strptime(cols[1], "%Y-%m-%d %H:%M:%S").replace(tzinfo=utc) # todo parse to right timezone
ABBJob.objects.create(
sw_id=int(cols[0]),
created=created,
title=cols[2],
QR=qr_url)
def gen_qr(sw_id):
img = qrcode.make("http://sahkoinsinoorikilta.fi/news/{}".format(sw_id))
imgname = "abbjobs_{}.png".format(sw_id)
imgurl = "{}qr/{}".format(settings.MEDIA_URL,imgname)
img.save("{}/qr/{}".format(settings.MEDIA_ROOT,imgname))
return imgurl