How to correctly register Flask blueprints with validation? #354
-
From the examples I understand the need to use the Here's an example app.py file: # ./app.py
from flask import Flask
from routes.foo import bp as foo
from routes.bar import bp as bar
from spectree import SpecTree
def create_app():
app = Flask(__name__)
api = SpecTree('flask')
# Register blueprints here
app.register_blueprint(foo)
app.register_blueprint(bar)
@app.route('/health')
def health():
return '👍'
api.register(app=app)
return app And the route definitions: # ./routes/foo.py
from pydantic import BaseModel
from spectree import SpecTree, Response
from flask import Blueprint
class FooRequestV1(BaseModel):
session_id: str
content: str
class FooResponseV1(BaseModel):
session_id: str
response: str
bp = Blueprint('foo', __name__)
api = SpecTree('flask', app=bp)
@bp.route('/v1/foo', methods=['POST'])
@api.validate(json=FooRequestV1, resp=Response(HTTP_200=FooResponseV1, HTTP_403=None, HTTP_204=None))
def foo():
# ... # ./routes/bar.py
from pydantic import BaseModel
from spectree import SpecTree, Response
from flask import Blueprint
class BarRequestV1(BaseModel):
session_id: str
content: str
class BarResponseV1(BaseModel):
session_id: str
response: str
bp = Blueprint('bar', __name__)
api = SpecTree('flask', app=bp)
@bp.route('/v1/bar', methods=['POST'])
@api.validate(json=BarRequestV1, resp=Response(HTTP_200=BarResponseV1, HTTP_403=None, HTTP_204=None))
def bar():
# ... What am I missing here? do I need a global instance of |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Ok, so I've immediately tried my own suggestion and created a single instance of Rubber ducking really is extremely useful. Leaving this here so hopefully it can be useful to someone else in the future 😃 |
Beta Was this translation helpful? Give feedback.
Ok, so I've immediately tried my own suggestion and created a single instance of
SpecTree
in a routes/spec.py file that can be imported from across the app to register endpoints and set up validation.Rubber ducking really is extremely useful. Leaving this here so hopefully it can be useful to someone else in the future 😃