patternpythonMinor
Searching the Foursquare API with Python
Viewed 0 times
foursquarethesearchingwithpythonapi
Problem
I'd like some feedback on the readability, style, and potential problems or issues.
foursquare.py
business.py
foursquare.py
import time
from api_keys import CLIENT_ID
from api_keys import CLIENT_SECRET
from api_keys import CATEGORY_ID
from business import Business
from business import make_request
def search(lat, lng, distance):
"""
Searches the Foursquare API (Max Limit = 50)
:param lat: Latitude of the request
:param long: Longitude of the request
:param distance: Distance to search (meters)
:returns: List of retrieved venues
"""
url = 'https://api.foursquare.com/v2/venues/explore?ll=%s,%s&intent=browse&radius=%s&limit=50&categoryId=%s&client_id=%s&client_secret=%s&v=%s' % (lat, lng, distance, CATEGORY_ID, CLIENT_ID, CLIENT_SECRET, time.strftime("%Y%m%d"))
venue_list = []
try:
data = make_request(url)
for item in data['response']['groups'][0]['items']:
venue = item['venue']
venue_list.append(Business(venue['name'],
venue['location']['address'],
venue['rating'],
venue['ratingSignals'],
venue['stats']['checkinsCount']))
except Exception, e:
print e
return venue_listbusiness.py
import urllib2
import json
class Business:
def __init__(self, name, address, rating, rating_count, checkin_count):
self.name = name
self.address = address
self.rating = rating
self.rating_count = rating_count
self.checkin_count = checkin_count
def make_request(url):
"""
Makes a new HTTP request to the given URL
:param url: The URL to request
:returns: JSON response
"""
req = urllib2.Request(url)
response = urllib2.urlopen(req)
data = json.loads(response.read())
response.close()
return dataSolution
Named tuples
Managing resources
For
Do you need to wrap it in
String formatting
Prefer the
is better than:
Business is nothing short of a tuple where each attribute is named. Rather than going through the verbosity of writing everything out, you can just make it a namedtuple:Business = namedtuple('Business', 'name address rating rating_count checkin_count')Managing resources
For
make_request, the preferred way to handle resources in Python is to use a context manager. For urlopen, we have contextlib.closing:def make_request(url):
with closing(urlopen(url)) as response:
return json.loads(response.read())Do you need to wrap it in
Request? Not sure that gives you anything.String formatting
Prefer the
format() syntax to the % syntax. That is:'Hello, {}'.format(name)is better than:
'Hello, %s' % nameCode Snippets
Business = namedtuple('Business', 'name address rating rating_count checkin_count')def make_request(url):
with closing(urlopen(url)) as response:
return json.loads(response.read())'Hello, {}'.format(name)'Hello, %s' % nameContext
StackExchange Code Review Q#113510, answer score: 8
Revisions (0)
No revisions yet.