Flask is web framework to create web application.
The idea of Flask is to build a good foundation for all applications. Everything else is up to you or extensions.
Flask is just not designed for large applications or asynchronous servers. Flask wants to make it quick and easy to write a traditional web application. See Thread local
Flask is just the paste that glues Werkzeug and Jinja2 together.
For Flask a web application is:
Each Flask application has to:
The name of the module or package helps to locate the application location.
The flask object implements a WSGI application. It acts as a central registry for the view functions, the URL rules, template configuration and much more.
create a Flask instance:
from flask import Flask
app = Flask(__name__)
from flask import Flask
app = Flask(__name__)
from flask import Flask
app = Flask('yourapplication')
# or
app = Flask(__name__.split('.')[0])
With Python reflection, Flask can then access the package to figure out where the templates and static files are stored (see open_resource()).
You don't need to import an app instance when
The Flask application object store global confi in its config attribute.
app.config.from_pyfile(config_filename)
current_app.config['INDEX_TEMPLATE']
See factory
By convention, templates and static files are stored in subdirectories within the application’s Python source tree, with the names templates and static respectively.
Flask uses thread local objects (context local objects in fact, they support greenlet contexts as well) for request, session and an extra object you can put your own things on (g) http://flask.pocoo.org/docs/1.0/api/#flask.g
http://flask.pocoo.org/docs/1.0/appcontext/
Typically, an application context will have the same lifetime as a request.
View functions, error handlers, and other functions that run during a request will have access to current_app. If you try to access current_app, or anything that uses it, outside an application context, you’ll get this error message:
def create_app():
app = Flask(__name__)
# everything that runs in the block will have access to current_app.
with app.app_context():
init_db()
return app
Thread: The context local proxies depend on context which in Flask is defined as being either a thread, process or greenlet.
Flask itself just bridges to Werkzeug to implement a proper WSGI application and to Jinja2 to handle templating. It also binds to a few common standard library packages such as logging. Everything else is up for extensions.
These distributions will be installed automatically when installing Flask.
Optional:
The basic concept of blueprints is that they record operations to execute when registered on an application. Flask associates view functions with blueprints when dispatching requests and generating URLs from one endpoint to another.
Modular Applications
A Blueprint object works similarly to a Flask application object, but it is not actually an application. A blueprint does not have to implement applications or view functions. A Blueprint is a set of operations which can be registered on an application, even multiple times. Like for regular applications, blueprints are considered to be contained in a folder.
Blueprint share application config, and can change an application object as necessary with being registered. The downside is that you cannot unregister a blueprint once an application was created without having to destroy the whole application object.
Example:
from flask import Blueprint, render_template, abort
from jinja2 import TemplateNotFound
simple_page = Blueprint('simple_page', __name__, template_folder='templates')
@simple_page.route('/', defaults={'page': 'index'})
@simple_page.route('/<page>')
def show(page):
try:
return render_template('pages/%s.html' % page)
except TemplateNotFound:
abort(404)
from flask import Flask
from yourapplication.simple_page import simple_page
app = Flask(__name__)
app.register_blueprint(simple_page)
If you check the rules registered on the application, you will find these:
[<Rule '/static/<filename>' (HEAD, OPTIONS, GET) -> static>,
<Rule '/<page>' (HEAD, OPTIONS, GET) -> simple_page.show>,
<Rule '/' (HEAD, OPTIONS, GET) -> simple_page.show>]
http://flask.pocoo.org/docs/1.0/patterns/appfactories/
Flask will automatically detect the application factory (create_app or make_app) in myapp.
The id of the application is the signature of the function.
def create_app(config_filename):
app = Flask(__name__)
app.config.from_pyfile(config_filename)
from yourapplication.model import db
db.init_app(app)
from yourapplication.views.admin import admin
from yourapplication.views.frontend import frontend
app.register_blueprint(admin)
app.register_blueprint(frontend)
return app
export FLASK_APP=hello.py
flask run
# or
python -m flask run
# or
export FLASK_APP="myapp:create_app('dev')"
flask run
If you have the debugger disabled or trust the users on your network, you can make the server publicly available simply by adding –host=0.0.0.0 to the command line:
If you enable debug support the server will reload itself on code changes, and it will also provide you with a helpful debugger if things go wrong.
export FLASK_RUN_PORT=8000
export FLASK_ENV=development
You are in a debug mode if:
http://flask.pocoo.org/docs/1.0/quickstart/#debug-mode
In debug mode, the logger’s level will be set to DEBUG.
To use the debugger on IDEA, you need to disable the debugger to be able to use the internal debugger. Doc
Example:
wd\env\Scripts\python.exe C:\Users\gerard\.IdeaIC2018.2\config\plugins\python-ce\helpers\pydev\pydevd.py --module --multiproc --qt-support=auto --client 127.0.0.1 --port 10531 --file flask run
pydev debugger: process 26360 is connecting
Connected to pydev debugger (build 182.4505.22)
* Serving Flask app "chatbot:create_app('dev')"
* Environment: development
* Debug mode: off
[2019-01-28 15:34:25,547] INFO in _internal: * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
More see werkzeug debugger
http://flask.pocoo.org/docs/dev/logging/
Flask uses standard Python logging. All Flask-related messages are logged under the 'flask' logger namespace. Flask.logger returns the logger named 'flask.app', and can be used to log messages for your application.
https://docs.python.org/3/library/logging.config.html#logging.config.dictConfig