Skip to content

Instantly share code, notes, and snippets.

@huangsam
Created May 20, 2024 00:17
Show Gist options
  • Save huangsam/2f19cf9e0a5d411c60850db042a1af9d to your computer and use it in GitHub Desktop.
Save huangsam/2f19cf9e0a5d411c60850db042a1af9d to your computer and use it in GitHub Desktop.
flask_app_context.py
from flask import Flask, Response, current_app, jsonify, make_response
from flask.views import MethodView
def create_app() -> Flask:
"""Create application context."""
created_app = Flask(__name__)
return created_app
app = create_app()
def _validate_app_instance() -> None:
"""Validate app instance in routes and views."""
assert isinstance(current_app, Flask)
@app.route("/hello")
def hello() -> Response:
"""Good old hello world at work."""
_validate_app_instance()
return make_response("hello")
class FooApi(MethodView):
def __init__(self, some_common_content: str, **options):
self.content = some_common_content
self.options = options
def get(self) -> Response:
"""The args and kwargs all exist"""
_validate_app_instance()
return jsonify({"message": self.content, **self.options})
app.add_url_rule("/foo", view_func=FooApi.as_view("foo", "hello champ", can_teach=True, can_show=True))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment