【问题标题】:Python - urllib.request and flaskPython - urllib.request 和烧瓶
【发布时间】:2018-05-24 13:15:28
【问题描述】:

我有这个P2P python 代码,我正在尝试从它发送一个POST 请求到flask:

在我的P2P 这边我有:

...

for reply in con:
    jsonData = json.loads(reply)
    print(jsonData)
    print(type(jsonData) is dict, tuple)
    data = urlencode(jsonData)
    print(data + " : urlencode")
    data = data.encode()
    print(data.__class__)
    req = urllib.request.Request("http://0.0.0.0:5000/validate", data)
    response = urllib.request.urlopen(req)
    #res = response.read()
    print(response.read().decode('utf8') + " : response in alice")

对于我的flask 代码,我有:

@app.route('/validate', methods=['POST'])
def validate():

    print(request.args)

请求参数总是输出为:

ImmutableMultiDict([])

P2P 端的输出是:

{'index': 2043, 'message': 'New Block Forged', 'previous_hash': 'fa4a49cd092869db788490e79a933e7a45107ce513523500e5cd9c85e25426de', 'proof': 168158, 'transactions': [{'amount': 1, 'recipient': '6760d061731c493e94897164c2362476', 'sender': '0'}]}
True <class 'tuple'>
index=2043&message=New+Block+Forged&previous_hash=fa4a49cd092869db788490e79a933e7a45107ce513523500e5cd9c85e25426de&proof=168158&transactions=%5B%7B%27amount%27%3A+1%2C+%27recipient%27%3A+%276760d061731c493e94897164c2362476%27%2C+%27sender%27%3A+%270%27%7D%5D : urlencode
<class 'bytes'>
{
  "add": true
}
 : response in alice

如您所见,urllib.request.urlopen 的 data 看起来是正确的。为什么它没有通过烧瓶一侧?

【问题讨论】:

  • 你为什么不试试 requests 模块?更容易理解。
  • 我最终使用了我更喜欢的 json...不是这个问题的真正答案,所以我让它保持打开状态
  • 朋友我说的是urllib模块。尝试使用 requests 模块发送 HTTP 请求。它更容易理解。 Here

标签: python url post flask request


【解决方案1】:

您正在向validate 端点发出POST 请求。而 request.args 只返回 url 查询字符串。因此,真实数据将在request.form 中提供。

回答

请提出GET 请求...以便data 在request.args 中可用

data = urllib.parse.urlencode(json_data)

url = 'http://localhost:5000?{}'.format(data)
with urllib.request.urlopen(url) as response:
    pass

【讨论】:

  • 啊是的...这应该是一个获取请求...请求模块看起来也很酷,肯定看起来更容易谢谢
猜你喜欢
  • 1970-01-01
  • 2018-09-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多