Skip to content

Instantly share code, notes, and snippets.

@vytas7
Last active April 23, 2021 08:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vytas7/657915918327a7b2fe7a1286b7553512 to your computer and use it in GitHub Desktop.
Save vytas7/657915918327a7b2fe7a1286b7553512 to your computer and use it in GitHub Desktop.
ASGI multipart form handling

ASGI multipart/form-data Media Handler Demo

Official documentation: Multipart Forms

  1. Install Falcon (3.0+ required for ASGI) and the uvicorn ASGI app server:

    pip install -U "falcon >= 3.0.0"
    pip install uvicorn
  2. Run as uvicorn test:app, where test:app is coming from the test.py example below.
  3. POST your multipart forms to http://127.0.0.1:8000/submit.

API Extensions

Similarly to ASGI Request/Response classes, the ASGI multipart form interface is kept as close to WSGI as possible, with the following additions (made them for WSGI too):

  • BodyPart.data becomes (primarily) BodyPart.get_data(), but the property exists as a convenience alias.
  • BodyPart.media becomes (primarily) BodyPart.get_media(), but the property exists as a convenience alias.
  • BodyPart.text becomes (primarily) BodyPart.get_text(), but the property exists as a convenience alias.

Pull Request

Feature PR: #1728 -- merged!

import hashlib
import falcon
import falcon.asgi
class Submissions:
async def on_get(self, req, resp):
resp.media = {'status': 'up'}
async def on_post(self, req, resp):
if not req.content_type or not req.content_type.startswith(
falcon.MEDIA_MULTIPART):
raise falcon.HTTPUnsupportedMediaType(title='Gimme multipart')
form = await req.get_media()
parts = []
async for part in form:
sha1 = hashlib.sha1()
async for chunk in part.stream:
sha1.update(chunk)
parts.append({
'content_type': part.content_type,
'filename': part.filename,
'name': part.name,
'secure_filename': part.secure_filename,
'sha1': sha1.hexdigest(),
})
resp.media = parts
app = falcon.asgi.App()
app.add_route('/submit', Submissions())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment