POST method to upload file with json object in python flask app

2024/9/8 8:35:29

I am stuck in a problem where I am trying to build single API which will upload file along with json object. I need this API to create webhook.

Using multi part, I am able to upload file and in option filed I am able to send json object.

In flask app when I am trying to retrieve json object its converting as blob type. I tried to convert it base64 then again converting into string but whole process is not working.

Let me know if anyone has good solution I can combine file and json object together and fetch it by flask python app.

zz is the variable in my code where I am trying to store my json object. name is the field where I am passing my json object with file.

Thanks in advance.

My current code

app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER@app.route('/upload/',methods = ['POST'])
def upload():customer_name='abc'if request.method == 'POST':zz=base64.b64encode(request.files['name'].read())try:file = request.files['file']if file:file.filename=customer_name+'_'+str(datetime.now())+'.'+file.filename.split('.')[-1]filename = secure_filename(file.filename)path=os.path.join(app.config['UPLOAD_FOLDER'], filename)file.save(path)return jsonify({'status':success,'junk_data':[],'message':error})except Exception as err:logger.error(str(datetime.now())+' '+str(err))return jsonify({'status':False,'junk_data':[],'message':str(err)})
if __name__ == '__main__':app.run(host='localhost',debug=True, use_reloader=True,port=5000)
Answer

I have got the answer after lot R&D.

request format

//user any client-sidecontent-type:multipart/form-datafile: file need to upload data: {"name":"abc","new_val":1}

python code to fetch from request object

data=json.loads(request.form.get('data'))
file = request.files['file']
https://en.xdnf.cn/q/72966.html

Related Q&A

Django Logging with FileHandler not Working

I am using the logging setup below with a django project (also using sentry/raven). The sentry/raven bit is working fine, but the file logging isnt. An empty logfile is created, but whenever I use logg…

How to directly access a resource in a Py2app (or Py2exe) program?

This is mostly for Py2app, but I plan to also port to Windows so Py2exe is also applicable.For Mac: How can I access the Resources folder of my app bundle from Python code? The ideal way for me would …

Workflow for Python with Docker + IDE for non-web applications

I am currently trying to insert Docker in my Python development workflow of non-web applications.What are the current best practices in Python development using Docker and an IDE? I need the possibili…

Django Deserialization Error Problem installing Fixture

Traceback (most recent call last):File "/Users/sparshkedia/Desktop/task/venv/lib/python3.6/site-packages/django/core/serializers/json.py", line 69, in Deserializeryield from PythonDeserialize…

Python HTTP Exception Handling

Im running a program that downloads files from a web sit. Ive introduced one exception handling urllib.error.HTTPError, but now Im getting from time to time additional errors that Im not sure how to ca…

Weird lambda behaviour in loops [duplicate]

This question already has answers here:What do lambda function closures capture?(8 answers)Closed 10 years ago.I stumbled upon a behaviour in python that I have a hard time understanding. This is the…

Why does inspect return different line for class inheriting from superclass?

While trying to figure out if a function is called with the @decorator syntax, we realized that inspect has a different behaviour when looking at a decorated class that inherits from a superclass.The f…

Sorting a list of tuples with multiple conditions

I am currently trying to sort the following list:list_ = [(1, 0101), (1, 1010), (1, 101), (2, 01), (2, 010), (2, 10)]These are the steps I want to take in order to sort it:Sort the list by the value of…

Tensorboard error: Tensor object has no attribute value

My goal: Add arbitrary text to tensorboard.My code:text = "muh teeeext" summary = tf.summary.text("Muh taaaag", tf.convert_to_tensor(text)) writer.add_summary(summary)My error:File …

How to embed Google Speech to Text API in Python program? [closed]

Closed. This question is seeking recommendations for books, tools, software libraries, and more. It does not meet Stack Overflow guidelines. It is not currently accepting answers.We don’t allow questi…