【问题标题】:Why does requests return an error when running through a function?为什么请求通过函数运行时会返回错误?
【发布时间】:2017-12-06 17:03:24
【问题描述】:

Bittrex Api 上有一个名为 getbalance 的端点,它将货币作为字符串并返回该货币的当前余额。在函数中执行请求时,

balance = get_balance('BTC')    

请求返回:

{'message': 'INVALID_SIGNATURE',
“结果”:无,
“成功”:假}

功能:

def get_balance(currency):
    endpoint = '/account/getbalance'
    params = {
        'currency' : currency
    }
    return call_endpoint(endpoint, False, params)

call_endpoint:

def call_endpoint(endpoint, isPublic, params = None):
    base_url = 'https://bittrex.com/api/v1.1'
    url = (base_url + endpoint + 
       '?apikey=' + API_KEY + 
       '&nonce=' + str(time.time())).encode('utf-8')
    signature = hmac.new(SECRET_KEY, url, hashlib.sha512).hexdigest()
    headers = {'apisign' : signature}
    r = requests.get(url, headers = headers, params=params)
    return r

但是,如果我要在函数之外请求它:

url = ('https://bittrex.com/api/v1.1/account/getbalance' + 
    '?apikey=' + API_KEY +
    '&nonce=' + str(time.time()) +
    '&currency=BTC').encode('utf-8')
signature = hmac.new(SECRET_KEY, url, hashlib.sha512).hexdigest()
headers = {'apisign' : signature}
r = requests.get(url, headers = headers)

它有效。

{'消息': '',
“结果”:{“可用”:
...,
“成功”:真}

这两种方法具有相同的代码,那么导致此错误的 python 函数或请求库是否存在某些问题?

【问题讨论】:

  • 唯一的区别是发送 params.please remove (params argument) inside function and try it
  • 两种情况下的URL不同;一个包括货币,另一个不包括货币。这将影响计算的签名,尽管我不知道这是否会对这个特定的 API 产生影响。 (我假设您的电话是 get_balance("BTC") 或等效电话。)
  • 我对其进行了编辑以显示初始调用。

标签: python python-3.x python-requests


【解决方案1】:

这两种方法的作用不同。

您的 call_endpoint 函数会在没有 currency 参数的情况下计算 url 输入上的标头的签名,然后将 requests 添加到 currency 参数中。

您的其他 sn-p 计算包含 currency 参数的 url 上的签名。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-22
    • 2019-01-16
    • 2020-05-01
    相关资源
    最近更新 更多