falconry/falcon

Simulate multipart/form-data file upload with Falcon's Testing module

Open

#1,010 opened on Apr 4, 2017

View on GitHub
 (11 comments) (0 reactions) (0 assignees)Python (9,293 stars) (925 forks)batch import
enhancementgood first issueneeds contributorproposal

Description

This simple Falcon API will take a HTTP POST with enctype=multipart/form-data and a file upload in the file parameter, returning the file's content to the caller:

# simple_api.py
import cgi
import falcon
import json

class MultipartFileUpload(object):
    def on_post(self, req, resp):
        upload = cgi.FieldStorage(fp=req.stream, environ=req.env)
        data = upload['file'].file.read().decode('utf-8')
        resp.body = json.dumps(dict(data=data))

app = falcon.API()
app.add_route('/', MultipartFileUpload())

To try this out, create a textfile with some content and send to the API via curl -F "file=@sample.txt" localhost:8000.

I would like to test this API now with Falcon's testing utilities, simulating such a file upload. The simulate_request method has a file_wrapper parameter which might be useful but from the documentation I do not understand how it is supposed to be used or whether this is possible at all.

As a workaround, I currently use webtest where this is supported, another possibility would be werkzeug. Anyway, I'm happy to drop dependencies if this should be possible with Falcon itself.

Contributor guide