Skip to content

Instantly share code, notes, and snippets.

@kgriffs
Created December 16, 2014 00:34
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kgriffs/fe371bfbb2d63211889b to your computer and use it in GitHub Desktop.
Save kgriffs/fe371bfbb2d63211889b to your computer and use it in GitHub Desktop.
Falcon hook for multipart/form-data (POC)
import cgi
def get_file(name):
def process_post_form(req, resp, resource, params):
# TODO: Either validate that content type is multipart/form-data
# here, or in another hook before allowing execution to proceed.
# This must be done to avoid a bug in cgi.FieldStorage
env = req.env
env.setdefault('QUERY_STRING', '')
# TODO: Add error handling, when the request is not formatted
# correctly or does not contain the desired field...
# TODO: Consider overriding make_file, so that you can
# stream directly to the destination rather than
# buffering using TemporaryFile (see http://goo.gl/Yo8h3P)
form = cgi.FieldStorage(fp=req.stream, environ=env)
file_item = form[name]
if file_item.file:
# It's an uploaded file
params['file'] = file_item.file
else:
# TODO: Raise an error
pass
return process_post_form
# Elsewhere...
import falcon
class MyResource(object):
@falcon.before(get_file('userfile'))
def on_post(self, req, resp, file):
pass
@kgriffs
Copy link
Author

kgriffs commented Mar 24, 2015

Warning: Untested

@kgriffs
Copy link
Author

kgriffs commented Sep 18, 2017

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment