0

I'm trying to upload a file along with some data to a Flask server using Python Requests.

Here's my code:

@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        temp_image = request.files['file']
        filename = secure_filename(temp_image.filename)
        temp_image.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        return 'Success'
 url = "https://some-random-url.com/"
 files = {'file': open("shared/assets/12332.png", 'rb')}
 data = {"lobby_id": "lobby_id"}
 r = requests.post(url=url, files=files)

So this part works absolutely fine and I get <Response [200]>.

But when I include the data part, and modify my Flask part of the code to,

@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        temp_image = request.files['file']
        data = request.get_json(force=True)
        filename = secure_filename(temp_image.filename)
        temp_image.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        return 'Success'

I get <Response [400]>. I'm assuming there's a mistake in the Flask section of the code but I'm unable to figure it out.

  • 1. What is server side error logs? 2. Please provide code how did you include the `data` part – rzlvmp Nov 05 '21 at 07:57
  • I attached the code snippet with the data part. That's the basic set of code I'm trying right now. Once I get the data json, I can proceed with the code. As for the errors, I'm running it in a remote server and the logs do not exactly work, or maybe I'm not sure on how to use it. But I get the response code and it's ````. I did get this when I printed the response text. ``` 400 Bad Request

    Bad Request

    The browser (or proxy) sent a request that this server could not understand.

    ```
    – Merlin DarkWiz Nov 05 '21 at 09:25
  • I mean your client side `data` is not used. You should add it to request: `requests.post(url=url, files=files, json=data)`. Did you do that? – rzlvmp Nov 05 '21 at 11:34
  • @rzlvmp I found `requests.post` plays up with both the `files` and `json` args provided. My solution was to send the JSON data as another file within the `multipart/form-data` request. [Here's my tested solution for Flask](https://stackoverflow.com/a/63439756/2052575). Guessing this solves Merlin's problem. – v25 Nov 05 '21 at 11:50
  • This works, thanks a lot. – Merlin DarkWiz Nov 08 '21 at 07:36

0 Answers0