Last active
July 13, 2023 20:47
-
-
Save Lancetnik/0d33f098e6b342ac71e7606f1059db70 to your computer and use it in GitHub Desktop.
A little FastDepends presentation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from functools import wraps | |
from flask import Flask, request | |
from flask.scaffold import setupmethod | |
from fast_depends import inject | |
from fast_depends.library import CustomField | |
from pydantic import PositiveInt, ValidationError | |
class Body(CustomField): | |
def use(self, **kwargs): | |
return { | |
**super().use(**kwargs), | |
self.param_name: (request.json or {}).get(self.param_name) | |
} | |
def catch_validation_error(handler): | |
@wraps(handler) | |
def catch_wrapper(*args, **kwargs): | |
try: | |
return handler(*args, **kwargs) | |
except ValidationError as e: | |
return e.json(), 400 | |
return catch_wrapper | |
class FastFlask(Flask): | |
@setupmethod | |
def route(self, rule: str, **options): | |
def decorator(f): | |
f = catch_validation_error(inject(f)) | |
endpoint = options.pop("endpoint", None) | |
self.add_url_rule(rule, endpoint, f, **options) | |
return f | |
return decorator | |
app = FastFlask(__name__) | |
@app.post("/<name>") | |
def hello( | |
name: str, | |
user_id: PositiveInt = Body(), | |
): | |
return { | |
name: user_id | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment