sync_with_server.py
61 lines
| 2.0 KiB
| text/x-python
|
PythonLexer
neko259
|
r841 | import re | ||
neko259
|
r1138 | import urllib.parse | ||
neko259
|
r841 | import httplib2 | ||
neko259
|
r1144 | import xml.etree.ElementTree as ET | ||
neko259
|
r841 | from django.core.management import BaseCommand | ||
from boards.models import GlobalId | ||||
__author__ = 'neko259' | ||||
neko259
|
r1138 | REGEX_GLOBAL_ID = re.compile(r'(\w+)::([\w\+/]+)::(\d+)') | ||
neko259
|
r841 | |||
class Command(BaseCommand): | ||||
help = 'Send a sync or get request to the server.' + \ | ||||
'sync_with_server <server_url> [post_global_id]' | ||||
neko259
|
r1138 | def add_arguments(self, parser): | ||
parser.add_argument('url', type=str) | ||||
neko259
|
r1144 | #parser.add_argument('global_id', type=str) # TODO Implement this | ||
neko259
|
r1138 | |||
neko259
|
r841 | def handle(self, *args, **options): | ||
neko259
|
r1138 | url = options.get('url') | ||
global_id_str = options.get('global_id') | ||||
if global_id_str: | ||||
match = REGEX_GLOBAL_ID.match(global_id_str) | ||||
if match: | ||||
key_type = match.group(1) | ||||
key = match.group(2) | ||||
local_id = match.group(3) | ||||
neko259
|
r841 | |||
neko259
|
r1138 | global_id = GlobalId(key_type=key_type, key=key, | ||
neko259
|
r841 | local_id=local_id) | ||
neko259
|
r1138 | xml = GlobalId.objects.generate_request_get([global_id]) | ||
data = {'xml': xml} | ||||
body = urllib.parse.urlencode(data) | ||||
h = httplib2.Http() | ||||
response, content = h.request(url, method="POST", body=body) | ||||
neko259
|
r841 | |||
neko259
|
r1138 | # TODO Parse content and get the model list | ||
print(content) | ||||
else: | ||||
raise Exception('Invalid global ID') | ||||
neko259
|
r841 | else: | ||
neko259
|
r1144 | h = httplib2.Http() | ||
response, content = h.request(url, method="POST") | ||||
print(content) | ||||
root = ET.fromstring(content) | ||||
status = root.findall('status')[0].text | ||||
if status == 'success': | ||||
models = root.findall('models')[0] | ||||
for model in models: | ||||
model_content = model[0] | ||||
print(model_content.findall('text')[0].text) | ||||
else: | ||||
raise Exception('Invalid response status') | ||||