Skip to content

Commit e6eb7f5

Browse files
committed
Add migration to populate locations from Yelp
1 parent fa8b61d commit e6eb7f5

2 files changed

Lines changed: 62 additions & 1 deletion

File tree

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
# Generated by Django 4.2 on 2023-05-09 20:17
2+
3+
import requests
4+
from os import environ
5+
6+
from django.contrib.gis.geos import Point
7+
from django.db import migrations
8+
from django.utils import timezone
9+
10+
11+
def populate_locations(apps, schema_editor):
12+
Location = apps.get_model('api', 'Location')
13+
LocationType = apps.get_model('api', 'LocationType')
14+
15+
YELP_URL = 'https://api.yelp.com/v3/businesses/search' \
16+
+ '?location=Philadelphia' \
17+
+ '&latitude=39.952584' \
18+
+ '&longitude=-75.165222' \
19+
+ '&categories=cafes' \
20+
+ '&limit=50'
21+
22+
yelp_result = requests.get(
23+
YELP_URL,
24+
headers={'Authorization': f'Bearer {environ.get("YELP_API_KEY")}'},
25+
timeout=5
26+
)
27+
28+
businesses = yelp_result.json()['businesses']
29+
30+
default_location_type = LocationType(
31+
code='default',
32+
name='Default Location'
33+
)
34+
default_location_type.save()
35+
36+
for b in businesses:
37+
location = Location(
38+
name=b['name'],
39+
address=' '.join(b['location']['display_address']),
40+
location=Point(
41+
b['coordinates']['longitude'],
42+
b['coordinates']['latitude']
43+
),
44+
location_type=default_location_type,
45+
price_category=b.get('price', ''),
46+
created_datetime=timezone.now(),
47+
modified_datetime=timezone.now()
48+
)
49+
location.save()
50+
51+
52+
class Migration(migrations.Migration):
53+
54+
dependencies = [
55+
('api', '0002_adjust_biz_hours_and_location_relation'),
56+
]
57+
58+
operations = [
59+
migrations.RunPython(populate_locations, migrations.RunPython.noop)
60+
]

src/django/requirements.txt

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
django==4.2
22
djangorestframework==3.14.0
33
djangorestframework-gis==1.0
4-
psycopg2==2.9.6
4+
psycopg2==2.9.6
5+
requests==2.30.0

0 commit comments

Comments
 (0)