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
Provenance
- Commit
190059c- Tree
ac71986- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
ab54924
6 files changed+187 added−1 removed
modified:docs/api.rst+2 added
205 unmodified lines206 207 .. autofunction:: render_template208 209 .. autofunction:: render_template_string210+211+.. autofunction:: get_template_attributeadded:docs/design.rst+147 added
1+Design Decisions in Flask2+=========================3+4+If you are curious why Flask does certain things the way it does and not5+different, this section is for you. This should give you an idea about6+some of the design decisions that may appear arbitrary and surprising at7+first, especially in direct comparison with other frameworks.8+9+10+The Explicit Application Object11+-------------------------------12+13+A Python web application based on WSGI has to have one central callable14+object that implements the actual application. In Flask this is an15+instance of the :class:`~flask.Flask` class. Each Flask application has16+to create an instance of this class itself and pass it the name of the17+module, but why can't Flask do that itself?18+19+Without such an explicit application object the following code::20+21+ from flask import Flask22+ app = Flask(__name__)23+24+ @app.route('/')25+ def index():26+ return 'Hello World!'27+28+Would look like this instead::29+30+ from hypothetical_flask import route31+32+ @route('/')33+ def index():34+ return 'Hello World!'35+36+There are three major reasons for this. The most important one is that37+implicit application objects require that there may only be one class at38+the time. There are ways to fake multiple application with a single39+application object, like maintaining a stack of applications, but this40+causes some problems I won't outline here in detail. Now the question is:41+when does a microframework need more than one application at the same42+time? A good example for this is unittesting. When you want to test43+something it can be very helpful to create a minimal application to test44+specific behavior. When the application object is deleted everything it45+allocated will be freed again.46+47+Another thing that becomes possible with having an explicit object laying48+around in your code is that you can subclass the base class49+(:class:`~flask.Flask`) to alter specific behaviour. This would not be50+possible without hacks if the object was created ahead of time for you51+based on a class that is not exposed to you.52+53+But there is another very important reason why Flask depends on an54+explicit instanciation of that class: the package name. Whenever you55+create a Flask instance you usually pass it `__name__` as package name.56+Flask depends on that information to properly load resources relative57+to your module. With Python's outstanding support for reflection it can58+then access the package to figure out where the templates and static files59+are stored (see :meth:`~flask.Flask.open_resource`). Now obviously there60+are frameworks around that do not need any configuration and will still be61+able to load templates relative to your application module. But they have62+to use the current working directory for that, which is a very unreliable63+way to determine where the application is. The current working directory64+is process-wide and if you are running multiple applications in one65+process (which could happen in a webserver without you knowing) the paths66+will be off. Worse: many webservers do not set the working directory to67+the directory of your application but to the document root which does not68+have to be the same folder.69+70+The third reason is "explicit is better than implicit". That object is71+your WSGI application, you don't have to remember anything else. If you72+want to apply a WSGI middleware, just wrap it and you're done (though73+there are better ways to do that so that you do not lose the reference74+to the application object :meth:`~flask.Flask.wsgi_app`).75+76+One Template Engine77+-------------------78+79+Flask decides on one template engine: Jinja2. Why doesn't Flask have a80+pluggable template engine interface? You can obviously use a different81+template engine, but Flask will still configure Jinja2 for you. While82+that limitation that Jinja2 is *always* configured will probably go away,83+the decision to bundle one template engine and use that will not.84+85+Template engines are like programming languages and each of those engines86+has a certain understandment about how things work. On the surface they87+all work the same: you tell the engine to evaluate a template with a set88+of variables and take the return value as string.89+90+But that's about where similarities end. Jinja2 for example has an91+extensive filter system, a certain way to do template inheritance, support92+for reusable blocks (macros) that can be used from inside templates and93+also from Python code, is using unicode for all operations, supports94+iterative template rendering, configurable syntax and more. On the other95+hand an engine like Genshi is based on XML stream evaluation, template96+inheritance by taking the availability of XPath into account and more.97+Mako on the other hand treats templates similar to Python modules.98+99+When it comes to bridge a template engine with an application or framework100+there is more than just rendering templates. Flask uses Jinja2's101+extensive autoescaping support for instance. Also it provides ways to102+access macros from Jinja2 templates.103+104+A template abstraction layer that would not take the unique features of105+the template engines away is a science on its own and a too large106+undertaking for a microframework like Flask.107+108+109+Micro with Dependencies110+-----------------------111+112+Why does Flask call itself a microframework and yet it depends on two113+libraries (namely Werkzeug and Jinja2). Why shouldn't it? If we look114+over to the Ruby side of web development there we have a protocol very115+similar to WSGI. Just that it's called Rack there, but besides that it116+looks very much like a WSGI rendition for Ruby. But nearly all117+applications in Ruby land do not work with Rack directly, but on top of a118+lirbary with the same name. This Rack library has two equivalents in119+Python: WebOb (formerly Paste) and Werkzeug. Paste is still around but120+from my understanding it's sortof deprecated in favour of WebOb. The121+development of WebOb and Werkzeug started side by side with similar ideas122+in mind: be a good implementation of WSGI for other applications to take123+advantage.124+125+Flask is a framework that takes advantage of the work already done by126+Werkzeug to properly interface WSGI (which can be a complex task at127+times). Thanks to recent developments in the Python package128+infrastructure, packages with depencencies are no longer an issue and129+there are very few reasons against having libraries that depend on others.130+131+132+Thread Locals133+-------------134+135+Flask uses thread local objects (context local objects in fact, they136+support greenlet contexts as well) for request, session and an extra137+object you can put your own things on (:data:`~flask.g`). Why is that and138+isn't that a bad idea?139+140+Yes it is usually not such a bright idea to use thread locals. They cause141+troubles for servers that are not based on the concept of threads and make142+large applications harder to maintain. However Flask is just not designed143+for large applications or asyncronous servers. Flask wants to make it144+quick and easy to write a traditional web application.145+146+Also see the :ref:`becomingbig` section of the documentation for some147+inspiration for larger applications based on Flask.modified:docs/index.rst+1 added
41 unmodified lines42 testing43 patterns/index44 deploying45 becomingbig46+ design47 48 Reference49 ---------50 7 unmodified linesadded:tests/templates/_macro.html+1 added
1{% macro hello(name) %}Hello {{ name }}!{% endmacro %}modified:tests/flask_tests.py+6 added
195 unmodified lines196 '<p>Hello World!',197 '<p>Hello World!'198 ]199 200+ 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!'205 206+207 if __name__ == '__main__':208 unittest.main()modified:flask.py+30 added-1 removed
118 unmodified lines119 """120 return _request_ctx_stack.top.url_adapter.build(endpoint, values)121 122 123+def 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:127+128+ .. sourcecode:: html+jinja129+130+ {% macro hello(name) %}Hello {{ name }}!{% endmacro %}131+132+ You can access this from Python code like this::133+134+ hello = get_template_attribute('_foo.html', 'hello')135+ return hello('World')136+137+ :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)142+143+144 def 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 lines646 return response647 648 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::652 653+ app = MyMiddleware(app)654+655+ It's a better idea to do this instead::656+657 app.wsgi_app = MyMiddleware(app.wsgi_app)658 659+ Then you still have the original application object around and660+ can continue to call methods on it.661+662 :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 response42 unmodified lines