Python: cannot access class attribute from different modules/functions - python

I have a class called Org, and I'm trying to access its method from multiple functions (that are defined outside of the class). I'm calling main() first, followed by discover_buildings(). The main() executes without error, however, I get AttributeError: 'Org' has no attribute 'headers' error after I call discover_buildings(). What is it that I'm doing wrong? (I was expecting the headers attribute to be shared across the different methods)
class Org(object):
def __init__(self, client_id, client_secret, grant_type='client_credentials'):
self.grant_type = grant_type
self.client_id = client_id
self.client_secret = client_secret
self.url = CI_A_URL
def auth(self):
""" authenticate with bos """
params = {
'client_id': self.client_id,
'client_secret': self.client_secret,
'grant_type': self.grant_type
}
r = requests.post(self.url + 'o/token/', data=params)
if r.status_code == 200:
self.access_token = r.json()['access_token']
self.headers = {
'Authorization': 'Bearer %s' %self.access_token,
'Content-Type': 'application/json',
}
else:
logging.error(r.content)
r.raise_for_status()
def get_buildings(self, perPage=1000):
params = {
'perPage': perPage
}
r = requests.get(self.url + 'buildings/', params=params, headers=self.headers)
result = r.json().get('data')
if r.status_code == 200:
buildings_dict = {i['name']: i['id'] for i in result}
sheet_buildings['A1'].value = buildings_dict
else:
logging.error(r.content)
r.raise_for_status()
client_id = 'xxx'
client_secret = 'yyy'
gateway_id = 123
o = Org(client_id, client_secret)
def discover_buildings():
return o.get_buildings()
def main():
return o.auth()
Thanks, in advance, for your help!

Try using a property to calculate headers whenever you need it and then cache it.
def auth(self):
""" authenticate with bos """
# 👇you might want to isolate `token` into a nested #property token
params = {
'client_id': self.client_id,
'client_secret': self.client_secret,
'grant_type': self.grant_type
}
# note assignment to `_headers`, not `headers`
r = requests.post(self.url + 'o/token/', data=params)
if r.status_code == 200:
self._access_token = r.json()['access_token']
# 👆
self._headers = { # 👈
'Authorization': 'Bearer %s' %self._access_token,
'Content-Type': 'application/json',
}
else:
logging.error(r.content)
r.raise_for_status()
#cache after the first time.
_headers = None
#property
def headers(self):
""" call auth when needed
you might want to isolate `token`
into its own property, allowing different
headers to use the same token lookup
"""
if self._headers is None:
self.auth()
return self._headers

the problem is the way you define "discover_buildings"
you define it first with "o" just initialised not after the authentication.
to handle this:
rewrite discover to take 'o' as a parameter
or
check first to see 'o' has 'headers' if not authenticate 'o' and do the rest
def discover_buildings():
if not getattr(o, 'headers'):
o.auth()
return o.get_buildings()

You didn't define self.headers. You need to run o.auth() (or define self.headers) before you run o.get_buildings().

Related

local variable 'verify_payment' referenced before assignment

I'm having the local variable referenced before assignment error and I have tried a lot of ways that I can use to fix this. Any help would be greatly appreciated
This is my Views.py (the error after the top of the second if statement)
def call_back_url(request):
reference = request.GET.get('reference')
# We need to fetch the reference from PAYMENT
check_pay = PayHistory.objects.filter(paystack_charge_id=reference).exists()
if check_pay == False:
# This means payment was not made error should be thrown here...
print("Error")
else:
payment = PayHistory.objects.get(paystack_charge_id=reference)
# We need to fetch this to verify if the payment was successful.
def verify_payment(request):
url = 'https://api.paystack.co/transaction/verify/'+reference
headers = {
'Authorization': 'Bearer '+settings.PAYSTACK_SECRET_KEY,
'Content-Type' : 'application/json',
'Accept': 'application/json',
}
datum = {
"reference": payment.paystack_charge_id
}
x = requests.get(url, data=json.dumps(datum), headers=headers)
if x.status_code != 200:
return str(x.status_code)
results = x.json()
return results
initialized = verify_payment(request)
if initialized['data']['status'] == 'success':
PayHistory.objects.filter(paystack_charge_id=initialized['data']['reference']).update(paid=True)
new_payment = PayHistory.objects.get(paystack_charge_id=initialized['data']['reference'])
instance = Membership.objects.get(id=new_payment.payment_for.id)
sub = UserMembership.objects.filter(reference_code=initialized['data']['reference']).update(membership=instance)
user_membership = UserMembership.objects.get(reference_code=initialized['data']['reference'])
Subscription.objects.create(user_membership=user_membership, expires_in=dt.now().date() + timedelta(days=user_membership.membership.duration))
return redirect('subscribed')
return render(request, 'payment.html')
def subscribed(request):
return render(request, 'subscribed.html')
try:
def verify_payment(request):
url = 'https://api.paystack.co/transaction/verify/'+reference
headers = {
'Authorization': 'Bearer '+settings.PAYSTACK_SECRET_KEY,
'Content-Type' : 'application/json',
'Accept': 'application/json',
}
datum = {
"reference": payment.paystack_charge_id
}
x = requests.get(url, data=json.dumps(datum), headers=headers)
if x.status_code != 200:
return str(x.status_code)
results = x.json()
return results
def call_back_url(request):
reference = request.GET.get('reference')
# We need to fetch the reference from PAYMENT
check_pay = PayHistory.objects.filter(paystack_charge_id=reference).exists()
if check_pay == False:
# This means payment was not made error should be thrown here...
print("Error")
else:
payment = PayHistory.objects.get(paystack_charge_id=reference)
# We need to fetch this to verify if the payment was successful.
initialized = verify_payment(request)
if initialized['data']['status'] == 'success':
PayHistory.objects.filter(paystack_charge_id=initialized['data']['reference']).update(paid=True)
new_payment = PayHistory.objects.get(paystack_charge_id=initialized['data']['reference'])
instance = Membership.objects.get(id=new_payment.payment_for.id)
sub = UserMembership.objects.filter(reference_code=initialized['data']['reference']).update(membership=instance)
user_membership = UserMembership.objects.get(reference_code=initialized['data']['reference'])
Subscription.objects.create(user_membership=user_membership, expires_in=dt.now().date() + timedelta(days=user_membership.membership.duration))
return redirect('subscribed')
return render(request, 'payment.html')
def subscribed(request):
return render(request, 'subscribed.html')

building decorator with token authentication and functools.wraps

i am building a kivy app that does APIs requests.
get_token() function runs first when app is launched to get all the necessary info, dicts, vars etc. After 30 min token gets expired, app has a buttons that on_press it will send request calls to the server, if the token is expired it wont work. I am trying to build a decorator #use_token that will check if simple request gets executed and receives response 200 Success code, if success: return(decorated function) else: calling get_token that will refresh token, and returning decorated function. A whole concept works, prints work at every possible block of code in every function, but when after 30 min token is expired, refresh_token() calls for get_token() inside the if statement, prints are still working but returned decorated function doesnt send requests, it prints test strings but doesnt do the main thing. That tells me that function get_token() executes inside if statement but doesn't update token information...
FIRST FUNCTION, RUNS ONES AT START:
def get_token():
url_token = "http://server.com"
payload = "{" \
"\n \"grantType\": \"password\"," \
"\n \"password\": \"string\"," \
"\n \"refreshToken\": \"string\"," \
"\n \"token\": \"string\"," \
"\n \"username\": \"admin\"" \
"\n}"
headers = {
'Content-Type': 'application/json',
'api_key': ''
}
global readyToken
readyToken = requests.request("POST", url_token, headers=headers, data=payload).json()['token']
print("Getting a NEW TOKEN!")
get_token()
DECORATOR FUNCTION:
def use_token(func):
#functools.wraps(func)
def refresh_token(*args):
url_check = "simplerequest.com"
response = requests.request("PUT", url_check, headers=HEADERS)
print("This print from url_check block "+str(response))
str_response = str(response)
if '401' in str_response:
print("401 found, Token is Expired, refreshing with get_token")
get_token()
else:
print("200 Code, success, passing, leaving else statement")
pass
print("emptying str_response and calling for decorated function:")
str_response = ""
return func(*args)
return refresh_token
DECORATED FUNCTION:
global URL_QC, HEADERS
URL_QC = "www.server.com"
HEADERS = {
'Content-Type': 'application/json',
'api_key': readyToken
}
#use_token
def change_channel(self, display_mac, ch_number):
print("Hello from DECORATED function!!!")
payload = "{\"deviceIds\": [" + str(display_mac) + "],\"menu\": \"save_sch_channel\", \"productType\": \"string\", \"value\":" + str(ch_number) + "}"
response = requests.request("PUT", URL_QC, headers=HEADERS, data=payload)
You are not updating the HEADERS variable when the readyToken changes.
HEADERS = {
'Content-Type': 'application/json',
'api_key': readyToken
}
In python, strings are passed by value. So here, you are only setting HEADERS['api_key'] to the current value of readyToken once. If you change readyToken later, the HEADERS is not updated because it only retains the original value of readyToken.
This can be solved by simply updating readyToken in the HEADERS every time it changes:
def get_token():
url_token = "http://server.com"
payload = {
"grantType": "password",
"password": "string",
"refreshToken": "string",
"token": "string",
"username": "admin"
}
headers = {
"Content-Type": 'application/json',
"api_key": ""
}
response = requests.post(url_token, headers=headers, data=payload)
print(f'Got Response: {response.json()}')
global readyToken
readyToken = response.json()['token']
# We also need to update headers!
global HEADERS
HEADERS['api_key'] = readyToken
Even better, if you are only using readyToken in the HEADERS, remove the readyToken variable entirely and simply update the global HEADERS variable:
def get_token():
...
response = requests.post(url_token, headers=headers, data=payload)
print(f'Got Response: {response.json()}')
global HEADERS
HEADERS['api_key'] = response.json()['token']
Alfa Q thank you so much, all your guesses and fixes was right! I do use token only in header, therefore i got read of readyToken and put token expression right into 'api_key' value. I also restructured the code and made a class implementing all your fixes:
token.py:
class Token:
def __init__(self):
self.url_check = "www.check.com"
self.url_token = "www.server.com"
self.payload = "{" \
"\n \"grantType\": \"password\"," \
"\n \"password\": \"password\"," \
"\n \"refreshToken\": \"string\"," \
"\n \"token\": \"string\"," \
"\n \"username\": \"admin\"" \
"\n}"
self.headers_token = {
'Content-Type': 'application/json',
'api_key': self.get_token()
}
def get_token(self):
return requests.post(self.url_token, headers=self.headers, data=self.payload).json()['token']
def use_token(self, func):
#functools.wraps(func)
def refresh_token(*args):
response = requests.put(self.url_check, headers=self.headers_token)
print("This print from url_check block: " + str(response))
if response.status_code == 200:
print('Status 200 | Token OK - No refresh necessary')
return func(*args)
elif response.status_code == 401:
print('Status 401 | Token is Expired - Refreshing')
self.get_token()
return func(*args)
else:
print(f'Status {response.status_code} | Error Occurred')
print("Print from REFRESH_TOKEN")
return refresh_token
main.py:
#token.use_token
def change_channel(self, display_mac, ch_number):
print("Hello from DECORATED function!!!")
payload = "{\"deviceIds\": [" + str(display_mac) + "],\"menu\": \"save_sch_channel\", \"productType\": \"string\", \"value\":" + str(ch_number) + "}"
response = requests.request("PUT", URL_QC, headers=token.headers_token, data=payload)
print(response)

Upload PDF from Python as attachment to Salesforce Object

I am trying to upload a pdf generated in Python as an attachment to a salesforce object using the simple_salesforce Python package. I have tried several different ways to accomplish this, but have had no luck so far. Here is the code
import base64
import json
from simple_salesforce import Salesforce
instance = ''
sessionId = sf.session_id
def pdf_encode(pdf_filename):
body = open(pdf_filename, 'rb') #open binary file in read mode
body = body.read()
body = base64.encodebytes(body)
body = pdf_encode('PDF_Report.pdf')
response = requests.post('https://%s.salesforce.com/services/data/v29.0/sobjects/Attachment/' % instance,
headers = { 'Content-Type': 'application/json', 'Authorization': 'Bearer %s' % sessionId },
data = json.dumps({
'ParentId': parent_id,
'Name': 'test.txt',
'body': body
})
)
I get this error.
TypeError: Object of type bytes is not JSON serializable
I have also tried to use
body = base64.encodebytes(body).decode('ascii')
in my code, but I can't get that to work either. I get the error
UnicodeError: encoding with 'idna' codec failed (UnicodeError: label empty or too long)
Any suggestions on how to upload a PDF in Python 3 into Salesforce as an attachment using simple_salesforce?
I was working on this and found a few resources to upload files. I created one for myself using that.
Below is the code that you can use for Python and have the file uploaded on Salesforce.
import requests
import base64
import json
params = {
"grant_type": "password",
"client_id": "Your_Client_Id",
"client_secret": "Your_Client_Secret",
"username": "YOUR_EMAIL#procureanalytics.com.pcsandbox", # The email you use to login
"password": "YOUR_PASSWORD+YOUR_SECURITY_TOKEN" # Concat your password and your security token
}
r = requests.post("https://test.salesforce.com/services/oauth2/token", params=params)
# if you connect to a Sandbox, use test.salesforce.com instead
access_token = r.json().get("access_token")
instance_url = r.json().get("instance_url")
print("Access Token:", access_token)
print("Instance URL", instance_url)
#######################################################################################
# Helper function
#######################################################################################
def sf_api_call(action, parameters = {}, method = 'get', data = {}):
"""
Helper function to make calls to Salesforce REST API.
Parameters: action (the URL), URL params, method (get, post or patch), data for POST/PATCH.
"""
headers = {
'Content-type': 'application/json',
'Accept-Encoding': 'gzip',
'Authorization': 'Bearer %s' % access_token
}
if method == 'get':
r = requests.request(method, instance_url+action, headers=headers, params=parameters, timeout=30)
elif method in ['post', 'patch']:
r = requests.request(method, instance_url+action, headers=headers, json=data, params=parameters, timeout=10)
else:
# other methods not implemented in this example
raise ValueError('Method should be get or post or patch.')
print('Debug: API %s call: %s' % (method, r.url) )
if r.status_code < 300:
if method=='patch':
return None
else:
return r.json()
else:
raise Exception('API error when calling %s : %s' % (r.url, r.content))
# Test connection
print(json.dumps(sf_api_call('/services/data/v40.0/query/', {
'q': 'SELECT Account.Name, Name, CloseDate from Opportunity where IsClosed = False order by CloseDate ASC LIMIT 1'
}), indent=2))
#######################################################################################
# File Upload from directory
#######################################################################################
# 1) Create a ContentVersion
path = "Folder_name\Sample_pdf.pdf"
with open(path, "rb") as f:
encoded_string = base64.b64encode(f.read()).decode("utf-8")
ContentVersion = sf_api_call('/services/data/v40.0/sobjects/ContentVersion', method="post", data={
'Title': 'Sample_pdf file',
'PathOnClient': path,
'VersionData': encoded_string,
})
ContentVersion_id = ContentVersion.get('id')
# 2) Get the ContentDocument id
ContentVersion = sf_api_call('/services/data/v40.0/sobjects/ContentVersion/%s' % ContentVersion_id)
ContentDocument_id = ContentVersion.get('ContentDocumentId')
# 3) Create a ContentDocumentLink
Id = "Abcd123" # This Id can be anything: Account_Id or Lead_Id or Opportunity_Id
ContentDocumentLink = sf_api_call('/services/data/v40.0/sobjects/ContentDocumentLink', method = 'post', data={
'ContentDocumentId': ContentDocument_id,
'LinkedEntityId': Id,
'ShareType': 'V'
})
How to use
Step 1:
Key in your email address and password here. Please note that the password here is a string of 'your password' and your 'security token'.
# Import libraries
import requests
import base64
import json
params = {
"grant_type": "password",
"client_id": "Your_Client_Id",
"client_secret": "Your_Client_Secret",
"username": "YOUR_EMAIL#procureanalytics.com.pcsandbox", # The email you use to login
"password": "YOUR_PASSWORD+YOUR_SECURITY_TOKEN" # Concat your password and your security token
}
r = requests.post("https://test.salesforce.com/services/oauth2/token", params=params)
# if you connect to a Sandbox, use test.salesforce.com instead
access_token = r.json().get("access_token")
instance_url = r.json().get("instance_url")
print("Access Token:", access_token)
print("Instance URL", instance_url)
You can get your security token on Salesforce through Account >> Settings >> Reset My Security Token.
You will receive an email from salesforce with your security token.
Step 2:
Choose appropriate link for request.post
For Sandbox environment:
r = requests.post("https://test.salesforce.com/services/oauth2/token", params=params)
For Production enviroment:
r = requests.post("https://login.salesforce.com/services/oauth2/token", params=params)
After your initial connection is ready, the output on the second cell should look something like this:
Access Token: !2864b793dbce2ad32c1ba7d71009ec84.b793dbce2ad32c1ba7d71009ec84
Instance URL https://your_company_name--pcsandbox.my.salesforce.com
Step 3:
Under the 'File upload from a directory' cell (Cell #5), specify your file path.
In my case, this is
# 1) Create a ContentVersion
path = "Folder_name\Sample_pdf.pdf"
with open(path, "rb") as f:
encoded_string = base64.b64encode(f.read()).decode("utf-8")
Step 4:
Under the same cell, mention the Id in which you would like to upload your file.
The sample code below is uploading a file on Accounts object for an account with Id: Abcd123
# 3) Create a ContentDocumentLink
Id = "Abcd123" # This Id can be anything: Account_Id or Lead_Id or Opportunity_Id
ContentDocumentLink = sf_api_call('/services/data/v40.0/sobjects/ContentDocumentLink', method = 'post', data={
'ContentDocumentId': ContentDocument_id,
'LinkedEntityId': Id,
'ShareType': 'V'
})

Why raise_for_status() did not catch the error?

Trying to check for none 200 Response in the current_track() function. What could be a problem? It throwing JSONDecodeError error. But if I understood raise_for_ status correctly it should have prevented the function from trying to load a JSON from a faulty web-page? If I run the script without this check and with uncommenting lines check_playback() it successfully catches JSONDecodeError.
The script is fetching data from Spotify and putting it to the status on vk.com.
import config
import webbrowser
import requests
import furl
import secrets
import string
import time
import os
import simplejson as json
URL_CODE_BASE_VK = 'https://oauth.vk.com/authorize'
URL_CODE_BASE_SP = 'https://accounts.spotify.com/authorize'
URL_TOKEN_VK = 'https://oauth.vk.com/access_token'
URL_TOKEN_SP = 'https://accounts.spotify.com/api/token'
URL_TRACK = 'https://api.spotify.com/v1/me/player/currently-playing'
URL_STATUS = 'https://api.vk.com/method/status.set'
EXP_IN_TOKEN_SP = 3400
EXP_IN_TOKEN_VK = 86400
FILE_TOKEN_VK = 'vk_token.json'
FILE_TOKEN_SP = 'sp_token.json'
def get_auth_code_vk():
url_code_params = {
'client_id': config.CLIENT_ID_VK,
'response_type': 'code',
'redirect_uri': 'https://oauth.vk.com/blank.html',
'v': 5.92,
'scope': 'status',
'state': gen_state(),
'display': 'page'
}
code = url_open(URL_CODE_BASE_VK, url_code_params)
return parse_code(code)
def get_auth_code_sp():
url_code_params = {
'client_id': config.CLIENT_ID_SP,
'response_type': 'code',
'redirect_uri': 'https://www.spotify.com/',
'scope': 'user-read-currently-playing',
'state': gen_state()
}
code = url_open(URL_CODE_BASE_SP, url_code_params)
return parse_code(code)
def gen_state():
symbols = string.ascii_lowercase + string.digits
return ''.join(secrets.choice(symbols) for _ in range(12))
def url_open(url_base, url_params):
url_code_full = furl.furl(url_base).add(url_params).url
webbrowser.open_new_tab(url_code_full)
input_url = input('Enter the whole URL, that you have been redirected on: ')
return input_url
def parse_code(url):
return (url.split("code=")[1]).split("&state=")[0]
def get_token_vk():
data = {
'grant_type': 'authorization_code',
'code': get_auth_code_vk(),
'redirect_uri': 'https://oauth.vk.com/blank.html',
'client_id': 6782333,
'client_secret': config.CLIENT_SECRET_VK
}
response = requests.post(url=URL_TOKEN_VK, data=data).json()
write_file(FILE_TOKEN_VK, response)
def get_token_sp():
data = {
'grant_type': 'authorization_code',
'code': get_auth_code_sp(),
'redirect_uri': 'https://www.spotify.com/',
'client_id': config.CLIENT_ID_SP,
'client_secret': config.CLIENT_SECRET_SP
}
response = requests.post(url=URL_TOKEN_SP, data=data).json()
write_file(FILE_TOKEN_SP, response)
def write_file(tkn_file, response):
dict = {}
dict['token'] = response["access_token"]
dict['time'] = time.time()
with open(tkn_file, 'w') as file:
file.write(json.dumps(dict))
def load_file(tkn_file):
with open(tkn_file) as file:
data = json.load(file)
return data
def set_status():
params = {
'v': 5.92,
'access_token': load_file(FILE_TOKEN_VK)['token'],
'text': current_track()
}
set_status = requests.get(url=URL_STATUS, params=params)
def track_data():
tkn_file = load_file(FILE_TOKEN_SP)['token']
headers = {
'Accept': 'application/json',
'Authorization': f'Bearer {tkn_file}'
}
return requests.get(url=URL_TRACK, headers=headers)
def current_track():
response = track_data()
print(response)
try:
response.raise_for_status()
except requests.exceptions.HTTPError as e:
return "Error: " + str(e)
# data = track_data().json()
data = response.json()
artist = data['item']['artists'][0]['name']
track = data['item']['name']
return(f'{artist} - {track}')
def check_playback():
set_status()
print(current_track())
# try:
# set_status()
# print(current_track())
# except json.decoder.JSONDecodeError:
# print('Not playing')
def token_missing(file):
return not os.path.isfile(file)
def token_expired(file, exp_in):
return time.time() - load_file(file)['time'] > exp_in
def token_not_valid(file, exp_in):
return token_missing(file) or token_expired(file, exp_in)
def run_script():
if token_not_valid(FILE_TOKEN_VK, EXP_IN_TOKEN_VK):
get_token_vk()
if token_not_valid(FILE_TOKEN_SP, EXP_IN_TOKEN_SP):
get_token_sp()
check_playback()
if __name__ == "__main__":
run_script()
Error screen
raise_for_status() will only raise an exception if the server reported an error to you (and even then, only if it actually followed the HTTP spec and returned a HTTP error code).
There is no way for the library to know that the response is incorrect. Even if it was correctly formatted JSON, it can't know what schema you expect it to follow (what fields should be present, and what types those fields should have). Even if it knew the schema and had verified it, there is no way for it to know that the data is actually correct and not made up on the spot.

Iterating over lists of input params for use in Yelp API code

this is my first time using stack overflow, and my first time using Python, so please forgive me if I provided more code than was necessary, or I'm asking the wrong questions. I'm still figuring out how the calls to the API work, so I provided all of the code that interacted with it. This code works, but only for a single string input in the params 'CATEGORY_1' and 'LOCATION'. I'm trying to figure out how to enter lists for each of these params so that it iterates through each of them, making many different url requests to the API, and printing out all of the results. I want the output to show each LOCATION input address from the list, then the corresponding API business search results for the categories 'bikes' and 'skateshops'. I'm uncertain where to put the for loops, and also it seems that the .replace attribute that I used does not work for list objects. Any help is appreciated!
Sincerely, Programming n00b
#Oauth credentials
CLIENT_ID = XXX
CLIENT_SECRET = XXX
# Yelp API Constants
API_HOST = 'https://api.yelp.com'
SEARCH_PATH = '/v3/businesses/search'
BUSINESS_PATH = '/v3/businesses/'
TOKEN_PATH = '/oauth2/token'
GRANT_TYPE = 'client_credentials'
# Desired Search parameters
CATEGORY_1 = ['bikes','skateshops']
LOCATION = ['123 Meadow St, Portland, OR', '222 Spring St, Provo, UT', '808
Williams Ave, Walla Walla, Washington']
RADIUS = 8050
SEARCH_LIMIT = 50
def obtain_bearer_token(host, path):
url = '{0}{1}'.format(host, quote(path.encode('utf8')))
assert CLIENT_ID, "Please supply your client_id."
assert CLIENT_SECRET, "Please supply your client_secret."
data = urlencode({
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET,
'grant_type': GRANT_TYPE,
})
headers = {
'content-type': 'application/x-www-form-urlencoded',
}
response = requests.request('POST', url, data=data, headers=headers)
bearer_token = response.json()['access_token']
return bearer_token
def request(host, path, bearer_token, url_params=None):
url_params = url_params or {}
url = '{0}{1}'.format(host, quote(path.encode('utf8')))
headers = {
'Authorization': 'Bearer %s' % bearer_token,
}
print(u'Querying {0} ...'.format(url))
response = requests.request('GET', url, headers=headers,
params=url_params)
return response.json()
def search(bearer_token, term, location):
url_params = {
'categories': term.replace(' ', '+'),
'location': location.replace(' ', '+'),
'radius': RADIUS,
'limit': SEARCH_LIMIT
}
return request(API_HOST, SEARCH_PATH, bearer_token, url_params=url_params)
def get_business(bearer_token, business_id):
business_path = BUSINESS_PATH + business_id
return request(API_HOST, business_path, bearer_token)
def query_api(term, location):
bearer_token = obtain_bearer_token(API_HOST, TOKEN_PATH)
response = search(bearer_token, term, location)
businesses = response.get('businesses')
for x in businesses[:]:
location=x['location']
print('{0},{1},{2},{3},{4},{5},{6},{7}'.format(x['name'],location['addre
ss1'],location['city'],location['state'],location['zip_code'],
x['phone'],x['url'],term))

Categories