我正在尝试实现简单的api客户端并面临非常具体的问题。试图在平面python代码中做一些简单的请求就可以了。但是,当我尝试将其全部包装到一个小类中时,它会返回一个带有403
状态代码的响应。我尝试了不同的方法来解决这个问题,但到目前为止还没有。
Snippet#1
import requests
import hashlib
import time
api_key = "my_api_key"
secret = "my_secret"
endpoint = "https://somecompany.com/some-api/1.0/status"
s = requests.Session()
s.headers['Accept'] = "application/json"
s.headers['Api-Key'] = api_key
def encode_signature(api_key, secret, time_secs):
return hashlib.sha256(
"{}{}{}".format(api_key, secret, time_secs)
).hexdigest()
def test_req(method, url, api_key, signature, **kwargs):
r = requests.Request(method=method, url=url, **kwargs)
prepped = s.prepare_request(r)
prepped.headers['X-Signature'] = signature
resp = s.send(prepped)
return resp, prepped
if __name__ == '__main__':
resp, req = test_req('GET', endpoint, api_key,
encode_signature(api_key, secret, int(time.time())))
print resp.status_code
Snippet#2(这个不起作用,但看起来和我类似)
import requests
import hashlib
import time
api_key = "my_api_key"
secret = "my_secret"
endpoint = "https://somecompany.com/some-api/1.0/status"
class Transport(object):
"""docstring for Transport"""
def __init__(self, api_key, secret):
self.api_key = api_key
self.secret = secret
self.conn = requests.Session()
self.conn.headers['Api_Key'] = api_key
self.conn.headers['Accept'] = 'application/json'
@property
def signature(self):
return hashlib.sha256(
"{}{}{}".format(self.api_key, self.secret, int(time.time()))
).hexdigest()
def request(self, method, endpoint, **kwargs):
r = requests.Request(method=method, url=endpoint, **kwargs)
prepped = self.conn.prepare_request(r)
prepped.headers['X-Signature'] = self.signature
resp = self.conn.send(prepped)
return resp, prepped
if __name__ == '__main__':
tr = Transport(api_key, secret)
resp, req = tr.request('GET', endpoint)
print resp.status_code
正如我所想,我用这两个片段做了完全相同的事情只有区别:在session属性中存储会话而不是全局变量。有没有办法处理会话对象错误?我迫切需要帮助!