python-3.x - Python Poloniex API 调用

标签 python-3.x api urllib poloniex

我有以下代码,我试图根据 their instructions 对 Poloniex 进行 API 调用

import urllib
import urllib.request
import json
import time
import hashlib
import codecs
import hmac 
import time


Key = "whatever your key is"
Sign = "whatever your secret is"

def returnBalances(balances):
    nonce = int(round(time.time()-599900000)*10)
    parms = {"returnBalances":balances,
             "nonce":nonce}

    parms = urllib.parse.urlencode(parms)
    hashed = hmac.new(b'Sign',digestmod=hashlib.sha512)
    signature = hashed.hexdigest()

    headers = {"Content-type":"application/x-www-form-urlencoded",
               "Key":Key,
               "Sign":signature}

    conn = urllib.request.urlopen("https://poloniex.com")
    conn.request("POST","/tradingApi",parms,headers)

    response = conn.getresponse()
    print(response.status,response.reason)

returnBalances('balances')

当我运行这个时,我收到此错误消息

HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 403: Forbidden

有人可以帮忙吗?

最佳答案

  • 您可以使用 urllib.error.HTTPError 捕获 HTTP 错误
  • POST 数据应该是字节,因此您必须编码 parms
  • urllib.request.urlopen返回 HTTPResponse对象,没有 request方法。
    如果你想设置标题和其他参数,你应该使用 urllib.request.Request
  • 根据api docs post 参数应该是“nonce”和“command”,所以我修改了您的函数以接受“returnBalances”作为参数并在 parms["command"] 中使用它

def api_call(command):
    nonce = int(round(time.time()-599900000)*10)
    parms = {"command":command, "nonce":nonce}
    parms = urllib.parse.urlencode(parms).encode()

    hashed = hmac.new(Sign.encode(), parms, digestmod=hashlib.sha512)
    signature = hashed.hexdigest()
    headers = {"Key":Key, "Sign":signature}

    req = urllib.request.Request("https://poloniex.com/tradingApi", headers=headers)
    try:
        conn = urllib.request.urlopen(req, data=parms)
    except urllib.error.HTTPError as e:
        conn = e
    print(conn.status,conn.reason)
    return json.loads(conn.read().decode())

balances = api_call("returnBalances")

关于python-3.x - Python Poloniex API 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47958768/

相关文章:

python - 从具有子父关系的列表开始,创建一个包含子项的父项作为列表

python - 使用 Chardet 查找超大文件的编码

Python - 如何将 IF 语句转换为函数以使用其他字符串多次调用?

python - 了解 Python map 函数 + 范围

php - 在 POSTMAN 上使用 PUT 方法上传文件

android - 使用 FFmpeg C API 调整视频大小

php - 使用 PayPal API 支付第三方

python - 为什么 find_all BeautifulSoup4 函数没有返回任何内容?

python - 如何将 URL 中的图像下载到特定文件夹中

python - 我有一个包含 urls-pdf 的列表,我想将它们本地保存到我的电脑上