Skip to content
Myr

Added support for macro pulling and documented certain design decisions.

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Armin Ronacher · committed by Armin Ronacher · parent ab54924 · Browse files · 6 files+187 added−1 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

6 files+187 added−1 removed

  • tests:+7 added−0 removed
  • other:+180 added−1 removed

6 files+187 added−1 removed

modified:docs/api.rst+2 added
205 unmodified lines
206207.. autofunction:: render_template208209.. autofunction:: render_template_string210211.. autofunction:: get_template_attribute
added:docs/design.rst+147 added
1Design Decisions in Flask2=========================34If you are curious why Flask does certain things the way it does and not5different, 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 class at38the time. There are ways to fake multiple application 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 unittesting. 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 with having an explicit object laying48around in your code is that you can subclass the base class49(:class:`~flask.Flask`) to alter specific behaviour. This would not be50possible without hacks if the object was 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 instanciation 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`).7576One Template Engine77-------------------7879Flask decides on one template engine: Jinja2. Why doesn't Flask have a80pluggable template engine interface? You can obviously use a different81template engine, but Flask will still configure Jinja2 for you. While82that limitation that Jinja2 is *always* configured will probably go away,83the decision to bundle one template engine and use that will not.8485Template engines are like programming languages and each of those engines86has a certain understandment about how things work. On the surface they87all work the same: you tell the engine to evaluate a template with a set88of variables and take the return value as string.8990But that's about where similarities end. Jinja2 for example has an91extensive filter system, a certain way to do template inheritance, support92for reusable blocks (macros) that can be used from inside templates and93also from Python code, is using unicode for all operations, supports94iterative template rendering, configurable syntax and more. On the other95hand an engine like Genshi is based on XML stream evaluation, template96inheritance by taking the availability of XPath into account and more.97Mako on the other hand treats templates similar to Python modules.9899When it comes to bridge a template engine with an application or framework100there is more than just rendering templates. Flask uses Jinja2's101extensive autoescaping support for instance. Also it provides ways to102access macros from Jinja2 templates.103104A template abstraction layer that would not take the unique features of105the template engines away is a science on its own and a too large106undertaking for a microframework like Flask.107108109Micro with Dependencies110-----------------------111112Why does Flask call itself a microframework and yet it depends on two113libraries (namely Werkzeug and Jinja2). Why shouldn't it? If we look114over to the Ruby side of web development there we have a protocol very115similar to WSGI. Just that it's called Rack there, but besides that it116looks very much like a WSGI rendition for Ruby. But nearly all117applications in Ruby land do not work with Rack directly, but on top of a118lirbary with the same name. This Rack library has two equivalents in119Python: WebOb (formerly Paste) and Werkzeug. Paste is still around but120from my understanding it's sortof deprecated in favour of WebOb. The121development of WebOb and Werkzeug started side by side with similar ideas122in mind: be a good implementation of WSGI for other applications to take123advantage.124125Flask is a framework that takes advantage of the work already done by126Werkzeug to properly interface WSGI (which can be a complex task at127times). Thanks to recent developments in the Python package128infrastructure, packages with depencencies are no longer an issue and129there are very few reasons against having libraries that depend on others.130131132Thread Locals133-------------134135Flask uses thread local objects (context local objects in fact, they136support greenlet contexts as well) for request, session and an extra137object you can put your own things on (:data:`~flask.g`). Why is that and138isn't that a bad idea?139140Yes it is usually not such a bright idea to use thread locals. They cause141troubles for servers that are not based on the concept of threads and make142large applications harder to maintain. However Flask is just not designed143for large applications or asyncronous servers. Flask wants to make it144quick and easy to write a traditional web application.145146Also see the :ref:`becomingbig` section of the documentation for some147inspiration for larger applications based on Flask.
modified:docs/index.rst+1 added
41 unmodified lines
42 testing43 patterns/index44 deploying45 becomingbig46 design4748Reference49---------50
7 unmodified lines
added:tests/templates/_macro.html+1 added
modified:tests/flask_tests.py+6 added
195 unmodified lines
196 '&lt;p&gt;Hello World!',197 '<p>Hello World!'198 ]199200 def test_macros(self):201 app = flask.Flask(__name__)202 with app.test_request_context():203 macro = flask.get_template_attribute('_macro.html', 'hello')204 assert macro('World') == 'Hello World!'205206207if __name__ == '__main__':208 unittest.main()
modified:flask.py+30 added-1 removed
118 unmodified lines
119 """120 return _request_ctx_stack.top.url_adapter.build(endpoint, values)121122123def get_template_attribute(template_name, attribute):124 """Loads a macro (or variable) a template exports. This can be used to125 invoke a macro from within Python code. If you for example have a126 template named `_foo.html` with the following contents:127128 .. sourcecode:: html+jinja129130 {% macro hello(name) %}Hello {{ name }}!{% endmacro %}131132 You can access this from Python code like this::133134 hello = get_template_attribute('_foo.html', 'hello')135 return hello('World')136137 :param template_name: the name of the template138 :param attribute: the name of the variable of macro to acccess139 """140 return getattr(current_app.jinja_env.get_template(template_name).module,141 attribute)142143144def flash(message):145 """Flashes a message to the next request. In order to remove the146 flashed message from the session and to display it to the user,147 the template has to call :func:`get_flashed_messages`.
498 unmodified lines
646 return response647648 def wsgi_app(self, environ, start_response):649 """The actual WSGI application. This is not implemented in629 `__call__` so that middlewares can be applied:650 `__call__` so that middlewares can be applied without losing a651 reference to the class. So instead of doing this::652653 app = MyMiddleware(app)654655 It's a better idea to do this instead::656657 app.wsgi_app = MyMiddleware(app.wsgi_app)658659 Then you still have the original application object around and660 can continue to call methods on it.661662 :param environ: a WSGI environment663 :param start_response: a callable accepting a status code,664 a list of headers and an optional665 exception context to start the response
42 unmodified lines