Skip to content

Instantly share code, notes, and snippets.

@mivade
Created July 20, 2021 15:15
Show Gist options
  • Save mivade/c0c31a966a13d7324d61d003ebd1b5ac to your computer and use it in GitHub Desktop.
Save mivade/c0c31a966a13d7324d61d003ebd1b5ac to your computer and use it in GitHub Desktop.
"""Example of how to use webargs with Tornado to read form data which includes file uploads."""
from dataclasses import dataclass, field
from typing import List, Optional
from marshmallow_dataclass import class_schema
from marshmallow.fields import Raw
from tornado.ioloop import IOLoop
from tornado.web import Application, RequestHandler
from webargs.tornadoparser import parser
@dataclass
class UploadedFile:
filename: str
body: bytes = field(metadata={"marshmallow_field": Raw()})
content_type: str
@dataclass
class Files:
files: List[UploadedFile]
@dataclass
class FormData:
bar: Optional[str] = None
class Handler(RequestHandler):
files_schema = class_schema(Files)()
form_schema = class_schema(FormData)()
def parse_files(self) -> Files:
return parser.parse(self.files_schema, self.request, location="files")
def parse_form(self) -> FormData:
return parser.parse(self.form_schema, self.request, location="form")
def post(self) -> None:
files = self.parse_files()
form = self.parse_form()
print(files)
print(form)
app = Application([("/", Handler)], debug=True)
app.listen(31234)
IOLoop.current().start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment