design.rst
This file
Path
docs/design.rst
229 lines · 11.0 KiB
Last changed by
Docs typo/markup fixes (#5829)Hynek Schlawackbefore adoption88a65bb
History of this fileTake it
The walk stopped after 200 commits: lines older than c9a5660 point at it.
Merge pull request #5054 from pallets/session-domainDavid Lordbefore adoptionc9a5660
lines 1–98why, one step back1Design 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-------------------98Merge branch 'stable'David Lordbefore adoption3301232
line 99why, one step back99Flask decides on one template engine: Jinja. Why doesn't Flask have aMerge pull request #5054 from pallets/session-domainDavid Lordbefore adoptionc9a5660
line 100why, one step back100pluggable template engine interface? You can obviously use a differentMerge branch 'stable'David Lordbefore adoption3301232
lines 101–102why, one step back101template engine, but Flask will still configure Jinja for you. While102that limitation that Jinja is *always* configured will probably go away,Merge pull request #5054 from pallets/session-domainDavid Lordbefore adoptionc9a5660
lines 103–109why, one step back103the 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.109Merge branch 'stable'David Lordbefore adoption3301232
line 110why, one step back110But that's about where similarities end. Jinja for example has anMerge pull request #5054 from pallets/session-domainDavid Lordbefore adoptionc9a5660
lines 111–120why, one step back111extensive 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,Merge branch 'stable'David Lordbefore adoption3301232
lines 121–122why, one step back121Flask uses Jinja's extensive autoescaping support. Also it provides122ways to access macros from Jinja templates.Merge pull request #5054 from pallets/session-domainDavid Lordbefore adoptionc9a5660
lines 123–152why, one step back123124A 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 twoMerge branch 'stable'David Lordbefore adoption3301232
line 153why, one step back153libraries (namely Werkzeug and Jinja). Why shouldn't it? If we lookMerge pull request #5054 from pallets/session-domainDavid Lordbefore adoptionc9a5660
lines 154–171why, one step back154over 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.170171merge app and request context (#5812)David Lordbefore adoptionadf3636
lines 172–173why, one step back172Context Locals173--------------Merge pull request #5054 from pallets/session-domainDavid Lordbefore adoptionc9a5660
line 174why, one step back174merge app and request context (#5812)David Lordbefore adoptionadf3636
lines 175–178why, one step back175Flask uses special context locals and proxies to provide access to the176current app and request data to any code running during a request, CLI command,177etc. Context locals are specific to the worker handling the activity, such as a178thread, process, coroutine, or greenlet.Merge pull request #5054 from pallets/session-domainDavid Lordbefore adoptionc9a5660
line 179why, one step back179merge app and request context (#5812)David Lordbefore adoptionadf3636
line 180why, one step back180The context and proxies help solve two development issues: circular imports, andDocs typo/markup fixes (#5829)Hynek Schlawackbefore adoption88a65bb
line 181why, one step back181passing around global data. :data:`.current_app` can be used to access themerge app and request context (#5812)David Lordbefore adoptionadf3636
line 182why, one step back182application object without needing to import the app object directly, avoidingDocs typo/markup fixes (#5829)Hynek Schlawackbefore adoption88a65bb
lines 183–184why, one step back183circular import issues. :data:`.request`, :data:`.session`, and :data:`.g` can184be imported to access the current data for the request, rather than needing tomerge app and request context (#5812)David Lordbefore adoptionadf3636
line 185why, one step back185pass them as arguments through every single function in your project.Merge pull request #5054 from pallets/session-domainDavid Lordbefore adoptionc9a5660
lines 186–211why, one step back186187188Async/await and ASGI support189----------------------------190191Flask supports ``async`` coroutines for view functions by executing the192coroutine on a separate thread instead of using an event loop on the193main thread as an async-first (ASGI) framework would. This is necessary194for Flask to remain backwards compatible with extensions and code built195before ``async`` was introduced into Python. This compromise introduces196a performance cost compared with the ASGI frameworks, due to the197overhead of the threads.198199Due to how tied to WSGI Flask's code is, it's not clear if it's possible200to make the ``Flask`` class support ASGI and WSGI at the same time. Work201is currently being done in Werkzeug to work with ASGI, which may202eventually enable support in Flask as well.203204See :doc:`/async-await` for more discussion.205206207What Flask is, What Flask is Not208--------------------------------209210Flask will never have a database layer. It will not have a form library211or anything else in that direction. Flask itself just bridges to WerkzeugMerge branch 'stable'David Lordbefore adoption3301232
line 212why, one step back212to implement a proper WSGI application and to Jinja to handle templating.Merge pull request #5054 from pallets/session-domainDavid Lordbefore adoptionc9a5660
lines 213–229why, one step back213It also binds to a few common standard library packages such as logging.214Everything else is up for extensions.215216Why is this the case? Because people have different preferences and217requirements and Flask could not meet those if it would force any of this218into the core. The majority of web applications will need a template219engine in some sort. However not every application needs a SQL database.220221As your codebase grows, you are free to make the design decisions appropriate222for your project. Flask will continue to provide a very simple glue layer to223the best that Python has to offer. You can implement advanced patterns in224SQLAlchemy or another database tool, introduce non-relational data persistence225as appropriate, and take advantage of framework-agnostic tools built for WSGI,226the Python web interface.227228The idea of Flask is to build a good foundation for all applications.229Everything else is up to you or extensions.