sync_with_server.py
74 lines
| 2.5 KiB
| text/x-python
|
PythonLexer
|
r841 | import re | ||
|
r1144 | import xml.etree.ElementTree as ET | ||
|
r1321 | import httplib2 | ||
|
r841 | from django.core.management import BaseCommand | ||
|
r1321 | |||
|
r841 | from boards.models import GlobalId | ||
|
r1177 | from boards.models.post.sync import SyncManager | ||
|
r841 | |||
__author__ = 'neko259' | ||||
|
r1138 | REGEX_GLOBAL_ID = re.compile(r'(\w+)::([\w\+/]+)::(\d+)') | ||
|
r841 | |||
class Command(BaseCommand): | ||||
|
r1321 | help = 'Send a sync or get request to the server.' | ||
|
r841 | |||
|
r1138 | def add_arguments(self, parser): | ||
parser.add_argument('url', type=str) | ||||
|
r1321 | parser.add_argument('--global_id', type=str, default='', | ||
help='Post global ID') | ||||
|
r1138 | |||
|
r841 | def handle(self, *args, **options): | ||
|
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) | ||||
|
r841 | |||
|
r1138 | global_id = GlobalId(key_type=key_type, key=key, | ||
|
r841 | local_id=local_id) | ||
|
r1138 | xml = GlobalId.objects.generate_request_get([global_id]) | ||
|
r1177 | # body = urllib.parse.urlencode(data) | ||
|
r1138 | h = httplib2.Http() | ||
|
r1177 | response, content = h.request(url, method="POST", body=xml) | ||
|
r841 | |||
|
r1236 | SyncManager.parse_response_get(content) | ||
|
r1138 | else: | ||
raise Exception('Invalid global ID') | ||||
|
r841 | else: | ||
|
r1144 | h = httplib2.Http() | ||
|
r1321 | xml = GlobalId.objects.generate_request_pull() | ||
response, content = h.request(url, method="POST", body=xml) | ||||
|
r1144 | |||
print(content) | ||||
root = ET.fromstring(content) | ||||
status = root.findall('status')[0].text | ||||
if status == 'success': | ||||
|
r1322 | ids_to_sync = list() | ||
|
r1144 | models = root.findall('models')[0] | ||
for model in models: | ||||
|
r1322 | global_id, exists = GlobalId.from_xml_element(model) | ||
print(global_id) | ||||
if not exists: | ||||
ids_to_sync.append(global_id) | ||||
if len(ids_to_sync) > 0: | ||||
xml = GlobalId.objects.generate_request_get(ids_to_sync) | ||||
# body = urllib.parse.urlencode(data) | ||||
h = httplib2.Http() | ||||
response, content = h.request(url, method="POST", body=xml) | ||||
SyncManager.parse_response_get(content) | ||||
else: | ||||
print('Nothing to get, everything synced') | ||||
|
r1144 | else: | ||
raise Exception('Invalid response status') | ||||