location_utils.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. from django.contrib.auth.models import User
  2. from requests import get
  3. from .auth_utils import refresh_access_token
  4. from .models import UserModel, Location
  5. def get_all_location_ids():
  6. locations = Location.objects.only('location_id')
  7. ids = [loc.location_id for loc in locations]
  8. '''
  9. There is a location which we don't need to add into database.
  10. It is a Medical Billing Service, That's why it is nothing to do with review.
  11. '''
  12. ids.remove('5397588228065547694')
  13. return ids
  14. def populate_locations():
  15. access_token, _ = refresh_access_token()
  16. user = User.objects.get(username='admin@ercare')
  17. gmb_id = UserModel.objects.get(user=user).gmb_account_id
  18. url = 'https://mybusiness.googleapis.com/v4/accounts/' + gmb_id + '/locations'
  19. headers = {
  20. 'authorization': 'Bearer ' + access_token,
  21. 'content-type': 'application/json'
  22. }
  23. res = get(url, headers=headers).json()
  24. locations = res['locations']
  25. for loc in locations:
  26. # loc['name'] = 'accounts/103266181421855655295/locations/8916258876770296726'
  27. loc_id = loc['name'].split('/')[-1]
  28. location_ids = get_all_location_ids()
  29. if loc_id in location_ids:
  30. continue
  31. loc_name = loc['locationName']
  32. loc_website = loc['websiteUrl']
  33. loc_display = loc['primaryCategory']['displayName']
  34. location = Location.objects.create(location_id=loc_id, location_name=loc_name, website_url=loc_website, display_name=loc_display, owner=user)
  35. location.save()