ewizard
ewizard

Reputation: 2862

Python - urllib.request and flask

I have this P2P python code, and I am trying to send a POST request from it to flask:

On my P2P side I have:

...

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")

For my flask code I have:

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

    print(request.args)

request args is always output as:

ImmutableMultiDict([])

The output for the P2P side is:

{'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

As you can see, the data for urllib.request.urlopen looks correct. Why isn't it getting through to the flask side?

Upvotes: 2

Views: 3130

Answers (1)

Raja Simon
Raja Simon

Reputation: 10315

You are making the POST request to validate endpoint. And request.args is only return the url querystring. So the real data will be available in request.form.

Answer

Please make the GET request... so data will be available in request.args

data = urllib.parse.urlencode(json_data)

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

Upvotes: 2

Related Questions