Skip to content

Instantly share code, notes, and snippets.

@boffbowsh
Created December 2, 2019 11:50
Show Gist options
  • Save boffbowsh/131b836a62b70e0d13c7c490c00a460c to your computer and use it in GitHub Desktop.
Save boffbowsh/131b836a62b70e0d13c7c490c00a460c to your computer and use it in GitHub Desktop.
import requests
from django.core.management.base import BaseCommand
from uk_political_parties.models import Party, PartyEmblem
class Command(BaseCommand):
def clean_party(self, party_id, party):
"""
Takes the raw dict from OpenElectoralCommission and returns a dict
that's able to be used by the django model. This is needed because
this app doesn't support the full JSON provided yet.
"""
cleaned_party = {
'party_id': party_id,
'party_name': party['name'],
'registered_date': party['date_registered'],
'register': party['register'],
}
return cleaned_party
def handle(self, **options):
base_url = "https://candidates.democracyclub.org.uk"
url = "{}/api/next/parties/".format(base_url)
while url:
req = requests.get(url)
results = req.json()
organizations = results['results']
for org in organizations:
party_id = org['ec_id']
print(party_id, org['name'])
(party_obj, created) = Party.objects.update_or_create(
party_id=party_id,
defaults=self.clean_party(party_id, org))
if org['emblems']:
for emblem in org['emblems']:
PartyEmblem.objects.update_or_create(
party_id=party_id,
emblem_url=emblem['image'],
)
url = results.get('next', None)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment