design.rst
This file
Path
docs/design.rst
228 lines · 10.8 KiB
Last changed by
Merge branch '2.2.x'David Lordbefore adoption87584e8
History of this fileTake it
1Design Decisions in Flask2=========================34If you are curious why Flask does certain things the way it does and not5differently, this section is for you. This should give you an idea about6some of the design decisions that may appear arbitrary and surprising at7first, especially in direct comparison with other frameworks.8910The Explicit Application Object11-------------------------------1213A Python web application based on WSGI has to have one central callable14object that implements the actual application. In Flask this is an15instance of the :class:`~flask.Flask` class. Each Flask application has16to create an instance of this class itself and pass it the name of the17module, but why can't Flask do that itself?1819Without such an explicit application object the following code::2021 from flask import Flask22 app = Flask(__name__)2324 @app.route('/')25 def index():26 return 'Hello World!'2728Would look like this instead::2930 from hypothetical_flask import route3132 @route('/')33 def index():34 return 'Hello World!'3536There are three major reasons for this. The most important one is that37implicit application objects require that there may only be one instance at38the time. There are ways to fake multiple applications with a single39application object, like maintaining a stack of applications, but this40causes some problems I won't outline here in detail. Now the question is:41when does a microframework need more than one application at the same42time? A good example for this is unit testing. When you want to test43something it can be very helpful to create a minimal application to test44specific behavior. When the application object is deleted everything it45allocated will be freed again.4647Another thing that becomes possible when you have an explicit object lying48around in your code is that you can subclass the base class49(:class:`~flask.Flask`) to alter specific behavior. This would not be50possible without hacks if the object were created ahead of time for you51based on a class that is not exposed to you.5253But there is another very important reason why Flask depends on an54explicit instantiation of that class: the package name. Whenever you55create a Flask instance you usually pass it `__name__` as package name.56Flask depends on that information to properly load resources relative57to your module. With Python's outstanding support for reflection it can58then access the package to figure out where the templates and static files59are stored (see :meth:`~flask.Flask.open_resource`). Now obviously there60are frameworks around that do not need any configuration and will still be61able to load templates relative to your application module. But they have62to use the current working directory for that, which is a very unreliable63way to determine where the application is. The current working directory64is process-wide and if you are running multiple applications in one65process (which could happen in a webserver without you knowing) the paths66will be off. Worse: many webservers do not set the working directory to67the directory of your application but to the document root which does not68have to be the same folder.6970The third reason is "explicit is better than implicit". That object is71your WSGI application, you don't have to remember anything else. If you72want to apply a WSGI middleware, just wrap it and you're done (though73there are better ways to do that so that you do not lose the reference74to the application object :meth:`~flask.Flask.wsgi_app`).7576Furthermore this design makes it possible to use a factory function to77create the application which is very helpful for unit testing and similar78things (:doc:`/patterns/appfactories`).7980The Routing System81------------------8283Flask uses the Werkzeug routing system which was designed to84automatically order routes by complexity. This means that you can declare85routes in arbitrary order and they will still work as expected. This is a86requirement if you want to properly implement decorator based routing87since decorators could be fired in undefined order when the application is88split into multiple modules.8990Another design decision with the Werkzeug routing system is that routes91in Werkzeug try to ensure that URLs are unique. Werkzeug will go quite far92with that in that it will automatically redirect to a canonical URL if a route93is ambiguous.949596One Template Engine97-------------------9899Flask decides on one template engine: Jinja2. Why doesn't Flask have a100pluggable template engine interface? You can obviously use a different101template engine, but Flask will still configure Jinja2 for you. While102that limitation that Jinja2 is *always* configured will probably go away,103the decision to bundle one template engine and use that will not.104105Template engines are like programming languages and each of those engines106has a certain understanding about how things work. On the surface they107all work the same: you tell the engine to evaluate a template with a set108of variables and take the return value as string.109110But that's about where similarities end. Jinja2 for example has an111extensive filter system, a certain way to do template inheritance,112support for reusable blocks (macros) that can be used from inside113templates and also from Python code, supports iterative template114rendering, configurable syntax and more. On the other hand an engine115like Genshi is based on XML stream evaluation, template inheritance by116taking the availability of XPath into account and more. Mako on the117other hand treats templates similar to Python modules.118119When it comes to connecting a template engine with an application or120framework there is more than just rendering templates. For instance,121Flask uses Jinja2's extensive autoescaping support. Also it provides122ways to access macros from Jinja2 templates.123124A template abstraction layer that would not take the unique features of125the template engines away is a science on its own and a too large126undertaking for a microframework like Flask.127128Furthermore extensions can then easily depend on one template language129being present. You can easily use your own templating language, but an130extension could still depend on Jinja itself.131132133What does "micro" mean?134-----------------------135136“Micro” does not mean that your whole web application has to fit into a single137Python file (although it certainly can), nor does it mean that Flask is lacking138in functionality. The "micro" in microframework means Flask aims to keep the139core simple but extensible. Flask won't make many decisions for you, such as140what database to use. Those decisions that it does make, such as what141templating engine to use, are easy to change. Everything else is up to you, so142that Flask can be everything you need and nothing you don't.143144By default, Flask does not include a database abstraction layer, form145validation or anything else where different libraries already exist that can146handle that. Instead, Flask supports extensions to add such functionality to147your application as if it was implemented in Flask itself. Numerous extensions148provide database integration, form validation, upload handling, various open149authentication technologies, and more. Flask may be "micro", but it's ready for150production use on a variety of needs.151152Why does Flask call itself a microframework and yet it depends on two153libraries (namely Werkzeug and Jinja2). Why shouldn't it? If we look154over to the Ruby side of web development there we have a protocol very155similar to WSGI. Just that it's called Rack there, but besides that it156looks very much like a WSGI rendition for Ruby. But nearly all157applications in Ruby land do not work with Rack directly, but on top of a158library with the same name. This Rack library has two equivalents in159Python: WebOb (formerly Paste) and Werkzeug. Paste is still around but160from my understanding it's sort of deprecated in favour of WebOb. The161development of WebOb and Werkzeug started side by side with similar ideas162in mind: be a good implementation of WSGI for other applications to take163advantage.164165Flask is a framework that takes advantage of the work already done by166Werkzeug to properly interface WSGI (which can be a complex task at167times). Thanks to recent developments in the Python package168infrastructure, packages with dependencies are no longer an issue and169there are very few reasons against having libraries that depend on others.170171172Thread Locals173-------------174175Flask uses thread local objects (context local objects in fact, they176support greenlet contexts as well) for request, session and an extra177object you can put your own things on (:data:`~flask.g`). Why is that and178isn't that a bad idea?179180Yes it is usually not such a bright idea to use thread locals. They cause181troubles for servers that are not based on the concept of threads and make182large applications harder to maintain. However Flask is just not designed183for large applications or asynchronous servers. Flask wants to make it184quick and easy to write a traditional web application.185186187Async/await and ASGI support188----------------------------189190Flask supports ``async`` coroutines for view functions by executing the191coroutine on a separate thread instead of using an event loop on the192main thread as an async-first (ASGI) framework would. This is necessary193for Flask to remain backwards compatible with extensions and code built194before ``async`` was introduced into Python. This compromise introduces195a performance cost compared with the ASGI frameworks, due to the196overhead of the threads.197198Due to how tied to WSGI Flask's code is, it's not clear if it's possible199to make the ``Flask`` class support ASGI and WSGI at the same time. Work200is currently being done in Werkzeug to work with ASGI, which may201eventually enable support in Flask as well.202203See :doc:`/async-await` for more discussion.204205206What Flask is, What Flask is Not207--------------------------------208209Flask will never have a database layer. It will not have a form library210or anything else in that direction. Flask itself just bridges to Werkzeug211to implement a proper WSGI application and to Jinja2 to handle templating.212It also binds to a few common standard library packages such as logging.213Everything else is up for extensions.214215Why is this the case? Because people have different preferences and216requirements and Flask could not meet those if it would force any of this217into the core. The majority of web applications will need a template218engine in some sort. However not every application needs a SQL database.219220As your codebase grows, you are free to make the design decisions appropriate221for your project. Flask will continue to provide a very simple glue layer to222the best that Python has to offer. You can implement advanced patterns in223SQLAlchemy or another database tool, introduce non-relational data persistence224as appropriate, and take advantage of framework-agnostic tools built for WSGI,225the Python web interface.226227The idea of Flask is to build a good foundation for all applications.228Everything else is up to you or extensions.