0

I have the following code

client.py

import requests
import pickle

class Test():
    def __init__(self, val):
        self.val = val

testList = []
for i in range(0,10):
    testList.append(Test(i))



data = {"foo": 1000, "bar": "value", "list": testList}
endpoint = "%s/%s" % (address, "testendpoint")
r = requests.post(endpoint, data={"req": pickle.dumps(data) })

server.py

import flask
import pickle
from flask import request

app = flask.Flask(__name__)
app.config["DEBUG"] = False

class Test():
    def __init__(self, val):
        self.val = val

@app.route('/testendpoint', methods=['POST'])
def testendpoint():
    data = pickle.loads(request.form['req'])
    print(data)

    response = {
        "response": "Success"
    }

    return json.dumps(response)

app.run(host="0.0.0.0", port=24979)

When I run client.py with server.py running, I get the following error:

[2020-07-17 14:06:05,054] ERROR in app: Exception on /testendpoint [POST]
Traceback (most recent call last):
  File "/usr/local/lib64/python3.6/site-packages/flask/app.py", line 2446, in wsgi_app
    response = self.full_dispatch_request()
  File "/usr/local/lib64/python3.6/site-packages/flask/app.py", line 1951, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/usr/local/lib64/python3.6/site-packages/flask/app.py", line 1820, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/usr/local/lib64/python3.6/site-packages/flask/_compat.py", line 39, in reraise
    raise value
  File "/usr/local/lib64/python3.6/site-packages/flask/app.py", line 1949, in full_dispatch_request
    rv = self.dispatch_request()
  File "/usr/local/lib64/python3.6/site-packages/flask/app.py", line 1935, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "server.py", line 11, in testendpoint
    data = pickle.loads(request.form['req'])
TypeError: a bytes-like object is required, not 'str'

I assume my bytes object gets converted to a string when sent via the http request. How do I send my data on the client via the request and then decode it on the server end?

TreeWater
  • 761
  • 6
  • 13
  • Sending pickled objects like this should probably be avoided. See [here](https://stackoverflow.com/questions/54009432/how-do-i-safely-send-a-python-object-to-my-flask-api) and [here](https://stackoverflow.com/questions/40551215/how-can-i-marshal-a-pickled-object-through-an-api-preferably-using-flask-restp) for various solutions/explanations. – v25 Jul 17 '20 at 22:26

1 Answers1

0

It should be dumps, but not loads

Edit like this

data = pickle.dumps(request.form['req'])