Issue
- I am (rather) new to flask
- I understand the following entities exist
wsgi.py
endpoints.py
- How should the decorators in
endpoints.py
know aboutapp
?endpoints
importingwsgi
"feels" wrong (or doesn't it ?!)
- Here is my solution without decorators at all:
$ tree -P "*.py"
.
├── api
│ ├── endpoints.py
│ ├── __pycache__
│ └── wsgi.py
└── tests
└── send_post_request_to_localhost.py
I put "everything" inside the wsgi.py
as follows:
from flask import Flask
from api.endpoints import analyze
if __name__ == '__main__':
app = Flask(__name__)
app.add_url_rule( # <----- this way app is "encapsulated" in wsgi
"/api/v1/system/analyze",
view_func=analyze,
methods=["POST"]
)
app.run()
and so my endpoints are pure and flask-less:
from typing import List, Dict, Union
from flask import request, jsonify
def analyze() -> List[Dict[str, Union[int, str]]]:
return jsonify([
{
"name": "dear " + entry["name"],
"salary": entry["salary"] + 37
}
for entry in request.get_json()
if request.is_json
])
Solution
Flask application itself is WSGI application where WSGI server is provided by other component (mod_wsgi, gunicorn). The typical setup follows documented patterns which provides convenient separation of app into appropriate python modules solving both circular imports issues as well as scaling codebase.
- factory pattern -- https://flask.palletsprojects.com/en/2.1.x/patterns/appfactories/
- blueprints -- https://flask.palletsprojects.com/en/2.1.x/blueprints/
That allows to make binding the app to WSGI server versatile (either via wsgi.py
or other means). The actual code in wsgi.py
then contains only the "binding" but not the app impl itself.
app.py
from flask import Flask
from endpoints import bp
def create_app():
app = Flask(__name__)
app.register_blueprint(bp, url_prefix='/')
return app
endpoints.py
from flask import Blueprint, jsonify
bp = Blueprint('endpoints', __name__)
@bp.route('/api/v1/system/analyze', methods=['POST'])
## not sure about types here, the flask view function must return flask.Response
def analyze():
return jsonify([
{
"name": "dear " + entry["name"],
"salary": entry["salary"] + 37
}
for entry in request.get_json()
if request.is_json
])
wsgi.py
applicaton = create_app()
if __name__ == '__main__':
application.run()
Great source for inspiration might be tutorial app https://github.com/pallets/flask/blob/main/examples/tutorial/flaskr/ or other community examples https://github.com/carc1n0gen/flask-examples/tree/master/flask-starter.
Answered By - Radoslav Bodó
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.