Flask: how to handle application / octet stream

I want to make some files to upload files. I am using jQuery File Uploader . My server code:

@app.route("/new/photogallery",methods=["POST"]) def newPhotoGallery(): print request.files 

I tried two things:

  • Submit a form usually:

    When I submit my form normally, it prints:

    ImmutableMultiDict([('post_photo_gallery', FileStorage: u'' ('application/octet-stream'))])

  • Submit a form using AJAX:

    When I submit my form using AJAX, it prints:

    ImmutableMultiDict([])

My first question is: why is there a difference between an AJAX request and a regular request.
My second question: how can I handle this application/octet-stream request in Flask/Python My third question: is this a good way to use application/octet-stream ?

By the way, I don't know much about application/octet-stream . Many thanks.

+8
python flask
source share
2 answers

I was unable to get the request using messages like application/octet-stream , but in the past they used forms like multipart/form-data to load images using a flask.

I expanded on what I did in the past to support multiple downloads, and this helped to use the werkzeug FileStorage objects.

The key point here is to create a mail route that looks for the request element from the form. This should allow you to send POST to the route either in standard form or by an AJAX call.

The following is a simplified example that uses a form:

Presentation template:

 <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>jQuery File Upload Example</title> </head> <body> {% if err %} <h4>{{ err }}</h4> {% endif %} <form action="/" method=POST enctype=multipart/form-data id="fileupload"> <input type="file" name="files" data-url="/" multiple> <input type=submit value=Post> </form> {% if files %} {% for file in files %} <p>Uploaded: <b>{{ file }}</b> </p> {% endfor %} {% endif %} </body> </html> 

Flagged application

 from flask import Flask, request, render_template from werkzeug import secure_filename, FileStorage import os # Flask functions app = Flask(__name__) app.config.from_object(__name__) DEBUG = True # add this so that flask doesn't swallow error messages app.config['PROPAGATE_EXCEPTIONS'] = True @app.route('/', methods=['GET', 'POST']) def uploader(): if request.method =='POST' and request.files.getlist('files'): up_file_list = [] # Iterate the through a list of files from the form input field for a_file in request.files.getlist('files'): if a_file.filename: # Validate that what we have been supplied with is infact a file if not isinstance(a_file, FileStorage): raise TypeError("storage must be a werkzeug.FileStorage") # Sanitise the filename a_file_name = secure_filename(a_file.filename) # Build target a_file_target = os.path.join('/tmp/', a_file_name) # Save file a_file.save(a_file_target) up_file_list.append(a_file_name) # Return template if up_file_list: return render_template('uploader.html', err=None, files=up_file_list) else: return render_template('uploader.html', err='No Files Uploaded', files=None) else: return render_template('uploader.html', err=None, files=None) # application execution if __name__ == '__main__': app.run() 
+2
source share

Regardless of the data encoding, you should be able to receive raw data using request.data . In the case of application/octet-stream you can simply write request.data in a binary file.

An example of a handler for different data types :

 from flask import json @app.route('/messages', methods = ['POST']) def api_message(): if request.headers['Content-Type'] == 'text/plain': return "Text Message: " + request.data elif request.headers['Content-Type'] == 'application/json': return "JSON Message: " + json.dumps(request.json) elif request.headers['Content-Type'] == 'application/octet-stream': with open('/tmp/binary', 'wb') as f: f.write(request.data) f.close() return "Binary message written!" else: return "415 Unsupported Media Type ;)" 

A typical form data processing scenario is already documented here .

0
source share

All Articles