· 4 years ago · Jul 18, 2021, 05:18 PM
1class Place:
2
3 def __init__(self, place):
4 self.id = place["_id"]
5 self.photos = place["result"].get("photos", [])
6 self.photos = self.make_photos()
7
8 def make_photos(self):
9 photo_objects = []
10 photos = self.photos
11 if not photos:
12 return []
13 for photo in photos:
14 photo = Photo(photo)
15 photo.place_id_db = self.id
16 photo_objects.append(photo)
17 return photo_objects
18
19
20class Photo:
21
22 def __init__(self, photo):
23 self.photo = photo
24 self.photo_reference = photo["photo_reference"]
25 self.max_width = photo["width"]
26 self.max_height = photo["height"]
27 self.url_exists_in_db = False
28 self.url = self.photo.get("url")
29 self.place_id_db = None # set by Place
30
31 def get_url(self):
32 if self.url:
33 self.url_exists_in_db = True
34 p("Url is already retrieved")
35 return self.url
36 p("Retrieving url from API")
37 base = "https://maps.googleapis.com/maps/api/place/photo"
38 params = {
39 "photoreference": self.photo_reference,
40 "maxheight": self.max_height,
41 "maxwidth": self.max_width,
42 "key": API_key
43 }
44 response = requests.get(base, params=params)
45 self.url = response.url
46 return self.url
47
48 def download(self):
49 url = self.get_url()
50 photo = requests.get(url)
51 photo_content = photo.content
52 with open(f"photos/{self.photo_reference}.jpg", "wb") as photo:
53 photo.write(photo_content)
54
55 def save_url_to_db(self):
56 if self.url_exists_in_db:
57 p("Url exists in db")
58 return
59 p("Saving url to db")
60 detailed_google_places_afula_db.update_one(
61 {"_id": self.place_id_db},
62 {
63 "$set": {
64 "result.photos.$[p].url": self.url
65 }
66 },
67 array_filters=[ {"p.photo_reference": self.photo_reference} ],
68 )