我刚刚开始学习 python/django。我一直在自学 PHP,现在我想学习 python。我在集成 yelp 的 API 时遇到问题。我收到错误:
Values instance has no attribute 'q'
我有这个代码:
def search(request):
parser = optparse.OptionParser()
parser.add_option('-c', '--consumer_key', dest='my_consumer_key_goes_here', help='OAuth consumer key (REQUIRED)')
parser.add_option('-s', '--consumer_secret', dest='my_consumer_secret_goes_here', help='OAuth consumer secret (REQUIRED)')
parser.add_option('-t', '--token', dest='my_token_goes_here', help='OAuth token (REQUIRED)')
parser.add_option('-e', '--token_secret', dest='my_token_secret_goes_here', help='OAuth token secret (REQUIRED)')
parser.add_option('-a', '--host', dest='host', help='Host', default='api.yelp.com')
options, args = parser.parse_args()
# search stuff?
if 'q' in request.GET and request.GET['q']:
q = request.GET['q']
parser.add_option('-q', '--term', dest=q, help='Search term')
url_params = {}
if options.q:
url_params['term'] = options.q
# Sign the URL
consumer = oauth2.Consumer(consumer_key, consumer_secret)
oauth_request = oauth2.Request('GET', url, {})
oauth_request.update({'oauth_nonce': oauth2.generate_nonce(),
'oauth_timestamp': oauth2.generate_timestamp(),
'oauth_token': token,
'oauth_consumer_key': consumer_key})
token = oauth2.Token(token, token_secret)
oauth_request.sign_request(oauth2.SignatureMethod_HMAC_SHA1(), consumer, token)
signed_url = oauth_request.to_url()
else:
message = 'You submitted an empty form.'
#return HttpResponse(message)
print 'Signed URL: %s\n' % (signed_url,)
# Connect
try:
conn = urllib2.urlopen(signed_url, None)
try:
response = json.loads(conn.read())
finally:
conn.close()
except urllib2.HTTPError, error:
response = json.loads(error.read())
return response
response = request(options.host, '/v2/search', url_params, options.consumer_key, options.consumer_secret, options.token, options.token_secret)
print json.dumps(response, sort_keys=True, indent=2)
现在,由于我对这整个 python 语言还是新手,我想知道我是否还在正确的地方添加了 API consumer_key、secret 等……?我是否正确设置了此代码?其中大部分来自原始的 yelp api 脚本。我想问题出在该if options.q:
地区...不确定我是否正确执行此操作?
谢谢