Skip to content
Myr

flask.py

This file

Path

flask.py

801 lines · 29.9 KiB · Python

Last changed by

Use setdefault() because it sets session.modified correctly.florentxbefore adoptiondbe0df7

History of this file

Take it

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 1–11
1# -*- coding: utf-8 -*-
2"""3 flask4 ~~~~~56 A microframework based on Werkzeug. It's extensively documented7 and follows best practice patterns.89 :copyright: (c) 2010 by Armin Ronacher.10 :license: BSD, see LICENSE for more details.11"""

Can't believe I forgot that future import.Armin Ronacherbefore adoption1d8432e

line 12why, one step back
12from __future__ import with_statement

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 13–14
13import os
14import sys

Flask now runs without the presence of pkg_resources as well.Armin Ronacherbefore adoption2d9bb69

lines 15–16why, one step back
15
16from jinja2 import Environment, PackageLoader, FileSystemLoader

Added testing documentationArmin Ronacherbefore adoption03148db

line 17why, one step back
17from werkzeug import Request as RequestBase, Response as ResponseBase, \

Added JSON Support and started working on jQuery docsArmin Ronacherbefore adoption6e2be6a

line 18why, one step back
18 LocalStack, LocalProxy, create_environ, SharedDataMiddleware, \

Documented some routing converter possibilities.Armin Ronacherbefore adoption95750b3

line 19why, one step back
19 ImmutableDict, cached_property

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

line 20
20from werkzeug.routing import Map, Rule

Removed two unused imports.Armin Ronacherbefore adoption0770f5c

line 21why, one step back
21from werkzeug.exceptions import HTTPException

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 22–23
22from werkzeug.contrib.securecookie import SecureCookie
23

Added JSON Support and started working on jQuery docsArmin Ronacherbefore adoption6e2be6a

lines 24–34why, one step back
24# try to load the best simplejson implementation available. If JSON
25# is not installed, we add a failing class.26json_available = True27try:28 import simplejson as json29except ImportError:30 try:31 import json32 except ImportError:33 json_available = False34

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 35–36
35# utilities we import from Werkzeug and Jinja2 that are unused
36# in the module but are exported as public interface.

Improved documentation, added a contextmanager for request bindingArmin Ronacherbefore adoption3b36bef

line 37why, one step back
37from werkzeug import abort, redirect

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 38–39
38from jinja2 import Markup, escape
39

Flask now runs without the presence of pkg_resources as well.Armin Ronacherbefore adoption2d9bb69

lines 40–47why, one step back
40# use pkg_resource if that works, otherwise fall back to cwd. The
41# current working directory is generally not reliable with the notable42# exception of google appengine.43try:44 import pkg_resources45 pkg_resources.resource_stream46except (ImportError, AttributeError):47 pkg_resources = None

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

line 48
48

Flask now runs without the presence of pkg_resources as well.Armin Ronacherbefore adoption2d9bb69

line 49why, one step back
49

Added testing documentationArmin Ronacherbefore adoption03148db

line 50why, one step back
50class Request(RequestBase):

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 51–52
51 """The request object used by default in flask. Remembers the
52 matched endpoint and view arguments.

Added testing documentationArmin Ronacherbefore adoption03148db

lines 53–56why, one step back
53
54 It is what ends up as :class:`~flask.request`. If you want to replace55 the request object used you can subclass this and set56 :attr:`~flask.Flask.request_class` to your subclass.

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 57–58
57 """
58

Use a tuple to store _flashes, and simplify the flask.Request class.florentxbefore adoption3eacc1d

line 59why, one step back
59 endpoint = view_args = None

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

line 60
60

Added JSON Support and started working on jQuery docsArmin Ronacherbefore adoption6e2be6a

lines 61–65why, one step back
61 @cached_property
62 def json(self):63 """If the mimetype is `application/json` this will contain the64 parsed JSON data.65 """

Some more documentation updates.Armin Ronacherbefore adoption715f64d

lines 66–67why, one step back
66 if __debug__:
67 _assert_have_json()

Added JSON Support and started working on jQuery docsArmin Ronacherbefore adoption6e2be6a

lines 68–69why, one step back
68 if self.mimetype == 'application/json':
69 return json.loads(self.data)

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

line 70
70

Added JSON Support and started working on jQuery docsArmin Ronacherbefore adoption6e2be6a

line 71why, one step back
71

Added testing documentationArmin Ronacherbefore adoption03148db

line 72why, one step back
72class Response(ResponseBase):

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 73–74
73 """The response object that is used by default in flask. Works like the
74 response object from Werkzeug but is set to have a HTML mimetype by

Added testing documentationArmin Ronacherbefore adoption03148db

lines 75–79why, one step back
75 default. Quite often you don't have to create this object yourself because
76 :meth:`~flask.Flask.make_response` will take care of that for you.7778 If you want to replace the response object used you can subclass this and79 set :attr:`~flask.Flask.request_class` to your subclass.

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 80–87
80 """
81 default_mimetype = 'text/html'828384class _RequestGlobals(object):85 pass8687

Session falls back to a dummy object now if secret_key is missing.Armin Ronacherbefore adoption5310fc3

lines 88–102why, one step back
88class _NullSession(SecureCookie):
89 """Class used to generate nicer error messages if sessions are not90 available. Will still allow read-only access to the empty session91 but fail on setting.92 """9394 def _fail(self, *args, **kwargs):95 raise RuntimeError('the session is unavailable because no secret '96 'key was set. Set the secret_key on the '97 'application to something unique and secret')98 __setitem__ = __delitem__ = clear = pop = popitem = \99 update = setdefault = _fail100 del _fail101102

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 103–114
103class _RequestContext(object):
104 """The request context contains all request relevant information. It is105 created at the beginning of the request and pushed to the106 `_request_ctx_stack` and removed at the end of it. It will create the107 URL adapter and request object for the WSGI environment provided.108 """109110 def __init__(self, app, environ):111 self.app = app112 self.url_adapter = app.url_map.bind_to_environ(environ)113 self.request = app.request_class(environ)114 self.session = app.open_session(self.request)

Session falls back to a dummy object now if secret_key is missing.Armin Ronacherbefore adoption5310fc3

lines 115–116why, one step back
115 if self.session is None:
116 self.session = _NullSession()

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 117–119
117 self.g = _RequestGlobals()
118 self.flashes = None119

Preserve the request context in debug mode.Armin Ronacherbefore adoption7b50150

lines 120–121why, one step back
120 def __enter__(self):
121 _request_ctx_stack.push(self)

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

line 122
122

Preserve the request context in debug mode.Armin Ronacherbefore adoption7b50150

lines 123–130why, one step back
123 def __exit__(self, exc_type, exc_value, tb):
124 # do not pop the request stack if we are in debug mode and an125 # exception happened. This will allow the debugger to still126 # access the request object in the interactive shell.127 if tb is None or not self.app.debug:128 _request_ctx_stack.pop()129130

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 131–139
131def url_for(endpoint, **values):
132 """Generates a URL to the given endpoint with the method provided.133134 :param endpoint: the endpoint of the URL (name of the function)135 :param values: the variable arguments of the URL rule136 """137 return _request_ctx_stack.top.url_adapter.build(endpoint, values)138139

Added support for macro pulling and documented certain design decisions.Armin Ronacherbefore adoption190059c

lines 140–153why, one step back
140def get_template_attribute(template_name, attribute):
141 """Loads a macro (or variable) a template exports. This can be used to142 invoke a macro from within Python code. If you for example have a143 template named `_foo.html` with the following contents:144145 .. sourcecode:: html+jinja146147 {% macro hello(name) %}Hello {{ name }}!{% endmacro %}148149 You can access this from Python code like this::150151 hello = get_template_attribute('_foo.html', 'hello')152 return hello('World')153

Added JSON Support and started working on jQuery docsArmin Ronacherbefore adoption6e2be6a

lines 154–155why, one step back
154 .. versionadded:: 0.2
155

Added support for macro pulling and documented certain design decisions.Armin Ronacherbefore adoption190059c

lines 156–162why, one step back
156 :param template_name: the name of the template
157 :param attribute: the name of the variable of macro to acccess158 """159 return getattr(current_app.jinja_env.get_template(template_name).module,160 attribute)161162

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 163–166
163def flash(message):
164 """Flashes a message to the next request. In order to remove the165 flashed message from the session and to display it to the user,166 the template has to call :func:`get_flashed_messages`.

Heavily improved documentationArmin Ronacherbefore adoption05f36c7

lines 167–168why, one step back
167
168 :param message: the message to be flashed.

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

line 169
169 """

Use setdefault() because it sets session.modified correctly.florentxbefore adoptiondbe0df7

line 170why, one step back
170 session.setdefault('_flashes', []).append(message)

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 171–179
171
172173def get_flashed_messages():174 """Pulls all flashed messages from the session and returns them.175 Further calls in the same request to the function will return176 the same messages.177 """178 flashes = _request_ctx_stack.top.flashes179 if flashes is None:

Use setdefault() because it sets session.modified correctly.florentxbefore adoptiondbe0df7

line 180why, one step back
180 _request_ctx_stack.top.flashes = flashes = session.pop('_flashes', [])

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 181–183
181 return flashes
182183

Added JSON Support and started working on jQuery docsArmin Ronacherbefore adoption6e2be6a

lines 184–208why, one step back
184def jsonify(*args, **kwargs):
185 """Creates a :class:`~flask.Response` with the JSON representation of186 the given arguments with an `application/json` mimetype. The arguments187 to this function are the same as to the :class:`dict` constructor.188189 Example usage::190191 @app.route('/_get_current_user')192 def get_current_user():193 return jsonify(username=g.user.username,194 email=g.user.email,195 id=g.user.id)196197 This will send a JSON response like this to the browser::198199 {200 "username": "admin",201 "email": "admin@localhost",202 "id": 42203 }204205 This requires Python 2.6 or an installed version of simplejson.206207 .. versionadded:: 0.2208 """

Some more documentation updates.Armin Ronacherbefore adoption715f64d

lines 209–210why, one step back
209 if __debug__:
210 _assert_have_json()

Added JSON Support and started working on jQuery docsArmin Ronacherbefore adoption6e2be6a

lines 211–214why, one step back
211 return current_app.response_class(json.dumps(dict(*args, **kwargs),
212 indent=None if request.is_xhr else 2), mimetype='application/json')213214

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 215–217
215def render_template(template_name, **context):
216 """Renders a template from the template folder with the given217 context.

Heavily improved documentationArmin Ronacherbefore adoption05f36c7

lines 218–221why, one step back
218
219 :param template_name: the name of the template to be rendered220 :param context: the variables that should be available in the221 context of the template.

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

line 222
222 """

Improved documentation, added a contextmanager for request bindingArmin Ronacherbefore adoption3b36bef

line 223why, one step back
223 current_app.update_template_context(context)

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 224–229
224 return current_app.jinja_env.get_template(template_name).render(context)
225226227def render_template_string(source, **context):228 """Renders a template from the given template source string229 with the given context.

Heavily improved documentationArmin Ronacherbefore adoption05f36c7

lines 230–234why, one step back
230
231 :param template_name: the sourcecode of the template to be232 rendered233 :param context: the variables that should be available in the234 context of the template.

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

line 235
235 """

Improved documentation, added a contextmanager for request bindingArmin Ronacherbefore adoption3b36bef

line 236why, one step back
236 current_app.update_template_context(context)

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 237–239
237 return current_app.jinja_env.from_string(source).render(context)
238239

Fixed a documentation error and implemented template context processors.Armin Ronacherbefore adoptiona01e8b4

lines 240–251why, one step back
240def _default_template_ctx_processor():
241 """Default template context processor. Injects `request`,242 `session` and `g`.243 """244 reqctx = _request_ctx_stack.top245 return dict(246 request=reqctx.request,247 session=reqctx.session,248 g=reqctx.g249 )250251

Some more documentation updates.Armin Ronacherbefore adoption715f64d

line 252why, one step back
252def _assert_have_json():

Fix typos and remove unused import.florentxbefore adoption3c821a0

line 253why, one step back
253 """Helper function that fails if JSON is unavailable."""

Some more documentation updates.Armin Ronacherbefore adoption715f64d

lines 254–257why, one step back
254 if not json_available:
255 raise RuntimeError('simplejson not installed')256257

Added screenshot of the debugger to Flask docs. Flask now runs from theArmin Ronacherbefore adoption40e0024

lines 258–265why, one step back
258def _get_package_path(name):
259 """Returns the path to a package or cwd if that cannot be found."""260 try:261 return os.path.abspath(os.path.dirname(sys.modules[name].__file__))262 except (KeyError, AttributeError):263 return os.getcwd()264265

Tiny refactoringArmin Ronacherbefore adoptionaf3b73f

lines 266–268why, one step back
266# figure out if simplejson escapes slashes. This behaviour was changed
267# from one version to another without reason.268if not json_available or '\\/' not in json.dumps('/'):

Fix a doc oversight, and revert 5876a8fd.florentxbefore adoptionf014ce2

line 269why, one step back
269

Tiny refactoringArmin Ronacherbefore adoptionaf3b73f

line 270why, one step back
270 def _tojson_filter(*args, **kwargs):

Slightly faster _tojson_filter.florentxbefore adoption75057bb

lines 271–272why, one step back
271 if __debug__:
272 _assert_have_json()

Tiny refactoringArmin Ronacherbefore adoptionaf3b73f

line 273why, one step back
273 return json.dumps(*args, **kwargs).replace('/', '\\/')

Slightly faster _tojson_filter.florentxbefore adoption75057bb

lines 274–275why, one step back
274else:
275 _tojson_filter = json.dumps

Fixed a security problem caused by changed simplejson semantics.Armin Ronacherbefore adoptionade4905

lines 276–277why, one step back
276
277

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 278–279
278class Flask(object):
279 """The flask object implements a WSGI application and acts as the central

Started working on documentation.Armin Ronacherbefore adoption4ec7d2a

lines 280–295why, one step back
280 object. It is passed the name of the module or package of the
281 application. Once it is created it will act as a central registry for282 the view functions, the URL rules, template configuration and much more.283284 The name of the package is used to resolve resources from inside the285 package or the folder the module is contained in depending on if the286 package parameter resolves to an actual python package (a folder with287 an `__init__.py` file inside) or a standard module (just a `.py` file).288289 For more information about resource loading, see :func:`open_resource`.290291 Usually you create a :class:`Flask` instance in your main module or292 in the `__init__.py` file of your package like this::293294 from flask import Flask295 app = Flask(__name__)

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 296–297
296 """
297

Added testing documentationArmin Ronacherbefore adoption03148db

lines 298–300why, one step back
298 #: the class that is used for request objects. See :class:`~flask.request`
299 #: for more information.300 request_class = Request

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

line 301
301

Added testing documentationArmin Ronacherbefore adoption03148db

lines 302–304why, one step back
302 #: the class that is used for response objects. See
303 #: :class:`~flask.Response` for more information.304 response_class = Response

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 305–319
305
306 #: path for the static files. If you don't want to use static files307 #: you can set this value to `None` in which case no URL rule is added308 #: and the development server will no longer serve any static files.309 static_path = '/static'310311 #: if a secret key is set, cryptographic components can use this to312 #: sign cookies and other things. Set this to a complex random value313 #: when you want to use the secure cookie for instance.314 secret_key = None315316 #: The secure cookie uses this for the name of the session cookie317 session_cookie_name = 'session'318319 #: options that are passed directly to the Jinja2 environment

Documented some routing converter possibilities.Armin Ronacherbefore adoption95750b3

line 320why, one step back
320 jinja_options = ImmutableDict(

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 321–325
321 autoescape=True,
322 extensions=['jinja2.ext.autoescape', 'jinja2.ext.with_']323 )324325 def __init__(self, package_name):

Started working on documentation.Armin Ronacherbefore adoption4ec7d2a

lines 326–330why, one step back
326 #: the debug flag. Set this to `True` to enable debugging of
327 #: the application. In debug mode the debugger will kick in328 #: when an unhandled exception ocurrs and the integrated server329 #: will automatically reload the application if changes in the330 #: code are detected.

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

line 331
331 self.debug = False

Started working on documentation.Armin Ronacherbefore adoption4ec7d2a

lines 332–334why, one step back
332
333 #: the name of the package or module. Do not change this once334 #: it was set by the constructor.

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

line 335
335 self.package_name = package_name

Started working on documentation.Armin Ronacherbefore adoption4ec7d2a

line 336why, one step back
336

Flask now runs without the presence of pkg_resources as well.Armin Ronacherbefore adoption2d9bb69

line 337why, one step back
337 #: where is the app root located?

Added screenshot of the debugger to Flask docs. Flask now runs from theArmin Ronacherbefore adoption40e0024

line 338why, one step back
338 self.root_path = _get_package_path(self.package_name)

Flask now runs without the presence of pkg_resources as well.Armin Ronacherbefore adoption2d9bb69

line 339why, one step back
339

Started working on documentation.Armin Ronacherbefore adoption4ec7d2a

lines 340–343why, one step back
340 #: a dictionary of all view functions registered. The keys will
341 #: be function names which are also used to generate URLs and342 #: the values are the function objects themselves.343 #: to register a view function, use the :meth:`route` decorator.

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

line 344
344 self.view_functions = {}

Started working on documentation.Armin Ronacherbefore adoption4ec7d2a

lines 345–350why, one step back
345
346 #: a dictionary of all registered error handlers. The key is347 #: be the error code as integer, the value the function that348 #: should handle that error.349 #: To register a error handler, use the :meth:`errorhandler`350 #: decorator.

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

line 351
351 self.error_handlers = {}

Started working on documentation.Armin Ronacherbefore adoption4ec7d2a

lines 352–356why, one step back
352
353 #: a list of functions that should be called at the beginning354 #: of the request before request dispatching kicks in. This355 #: can for example be used to open database connections or356 #: getting hold of the currently logged in user.

request_init -> before_request and request_shutdown -> after_requestArmin Ronacherbefore adoptionfb2d2e4

line 357why, one step back
357 #: To register a function here, use the :meth:`before_request`

Started working on documentation.Armin Ronacherbefore adoption4ec7d2a

line 358why, one step back
358 #: decorator.

request_init -> before_request and request_shutdown -> after_requestArmin Ronacherbefore adoptionfb2d2e4

line 359why, one step back
359 self.before_request_funcs = []

Started working on documentation.Armin Ronacherbefore adoption4ec7d2a

lines 360–361why, one step back
360
361 #: a list of functions that are called at the end of the

Fixed typo and added AUTHORS file and license text to docs.Armin Ronacherbefore adoption3a1e518

line 362why, one step back
362 #: request. The function is passed the current response

Started working on documentation.Armin Ronacherbefore adoption4ec7d2a

line 363why, one step back
363 #: object and modify it in place or replace it.

request_init -> before_request and request_shutdown -> after_requestArmin Ronacherbefore adoptionfb2d2e4

line 364why, one step back
364 #: To register a function here use the :meth:`after_request`

Started working on documentation.Armin Ronacherbefore adoption4ec7d2a

line 365why, one step back
365 #: decorator.

request_init -> before_request and request_shutdown -> after_requestArmin Ronacherbefore adoptionfb2d2e4

line 366why, one step back
366 self.after_request_funcs = []

Fixed a documentation error and implemented template context processors.Armin Ronacherbefore adoptiona01e8b4

lines 367–374why, one step back
367
368 #: a list of functions that are called without arguments369 #: to populate the template context. Each returns a dictionary370 #: that the template context is updated with.371 #: To register a function here, use the :meth:`context_processor`372 #: decorator.373 self.template_context_processors = [_default_template_ctx_processor]374

Documented some routing converter possibilities.Armin Ronacherbefore adoption95750b3

lines 375–389why, one step back
375 #: the :class:`~werkzeug.routing.Map` for this instance. You can use
376 #: this to change the routing converters after the class was created377 #: but before any routes are connected. Example::378 #:379 #: from werkzeug import BaseConverter380 #:381 #: class ListConverter(BaseConverter):382 #: def to_python(self, value):383 #: return value.split(',')384 #: def to_url(self, values):385 #: return ','.join(BaseConverter.to_url(value)386 #: for value in values)387 #:388 #: app = Flask(__name__)389 #: app.url_map.converters['list'] = ListConverter

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 390–392
390 self.url_map = Map()
391392 if self.static_path is not None:

Documented some routing converter possibilities.Armin Ronacherbefore adoption95750b3

lines 393–394why, one step back
393 self.add_url_rule(self.static_path + '/<filename>',
394 build_only=True, endpoint='static')

Flask now runs without the presence of pkg_resources as well.Armin Ronacherbefore adoption2d9bb69

lines 395–398why, one step back
395 if pkg_resources is not None:
396 target = (self.package_name, 'static')397 else:398 target = os.path.join(self.root_path, 'static')

Static files are active in the WSGI app now, not just the server.Armin Ronacherbefore adoptionca520fb

line 399why, one step back
399 self.wsgi_app = SharedDataMiddleware(self.wsgi_app, {

Flask now runs without the presence of pkg_resources as well.Armin Ronacherbefore adoption2d9bb69

line 400why, one step back
400 self.static_path: target

Static files are active in the WSGI app now, not just the server.Armin Ronacherbefore adoptionca520fb

line 401why, one step back
401 })

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

line 402
402

Started working on documentation.Armin Ronacherbefore adoption4ec7d2a

lines 403–405why, one step back
403 #: the Jinja2 environment. It is created from the
404 #: :attr:`jinja_options` and the loader that is returned405 #: by the :meth:`create_jinja_loader` function.

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 406–411
406 self.jinja_env = Environment(loader=self.create_jinja_loader(),
407 **self.jinja_options)408 self.jinja_env.globals.update(409 url_for=url_for,410 get_flashed_messages=get_flashed_messages411 )

Some more documentation updates.Armin Ronacherbefore adoption715f64d

line 412why, one step back
412 self.jinja_env.filters['tojson'] = _tojson_filter

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 413–419
413
414 def create_jinja_loader(self):415 """Creates the Jinja loader. By default just a package loader for416 the configured package is returned that looks up templates in the417 `templates` folder. To add other loaders it's possible to418 override this method.419 """

Flask now runs without the presence of pkg_resources as well.Armin Ronacherbefore adoption2d9bb69

lines 420–421why, one step back
420 if pkg_resources is None:
421 return FileSystemLoader(os.path.join(self.root_path, 'templates'))

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 422–423
422 return PackageLoader(self.package_name)
423

Improved documentation, added a contextmanager for request bindingArmin Ronacherbefore adoption3b36bef

lines 424–426why, one step back
424 def update_template_context(self, context):
425 """Update the template context with some commonly used variables.426 This injects request, session and g into the template context.

Heavily improved documentationArmin Ronacherbefore adoption05f36c7

lines 427–429why, one step back
427
428 :param context: the context as a dictionary that is updated in place429 to add extra variables.

Improved documentation, added a contextmanager for request bindingArmin Ronacherbefore adoption3b36bef

line 430why, one step back
430 """

Fixed a documentation error and implemented template context processors.Armin Ronacherbefore adoptiona01e8b4

lines 431–432why, one step back
431 for func in self.template_context_processors:
432 context.update(func())

Improved documentation, added a contextmanager for request bindingArmin Ronacherbefore adoption3b36bef

line 433why, one step back
433

flask uses 127.0.0.1 as host by default now. stupid chrome.Armin Ronacherbefore adoption00f87f6

line 434why, one step back
434 def run(self, host='127.0.0.1', port=5000, **options):

Started working on documentation.Armin Ronacherbefore adoption4ec7d2a

lines 435–437why, one step back
435 """Runs the application on a local development server. If the
436 :attr:`debug` flag is set the server will automatically reload437 for code changes and show a debugger in case an exception happened.

Heavily improved documentationArmin Ronacherbefore adoption05f36c7

lines 438–444why, one step back
438
439 :param host: the hostname to listen on. set this to ``'0.0.0.0'``440 to have the server available externally as well.441 :param port: the port of the webserver442 :param options: the options to be forwarded to the underlying443 Werkzeug server. See :func:`werkzeug.run_simple`444 for more information.

Started working on documentation.Armin Ronacherbefore adoption4ec7d2a

line 445why, one step back
445 """

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 446–452
446 from werkzeug import run_simple
447 if 'debug' in options:448 self.debug = options.pop('debug')449 options.setdefault('use_reloader', self.debug)450 options.setdefault('use_debugger', self.debug)451 return run_simple(host, port, self, **options)452

Added tests for minitwit. Testing with Flask is awesomeArmin Ronacherbefore adoptionf2dc38c

line 453why, one step back
453 def test_client(self):

Added testing documentationArmin Ronacherbefore adoption03148db

lines 454–456why, one step back
454 """Creates a test client for this application. For information
455 about unit testing head over to :ref:`testing`.456 """

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 457–460
457 from werkzeug import Client
458 return Client(self, self.response_class, use_cookies=True)459460 def open_resource(self, resource):

Started working on documentation.Armin Ronacherbefore adoption4ec7d2a

lines 461–477why, one step back
461 """Opens a resource from the application's resource folder. To see
462 how this works, consider the following folder structure::463464 /myapplication.py465 /schemal.sql466 /static467 /style.css468 /template469 /layout.html470 /index.html471472 If you want to open the `schema.sql` file you would do the473 following::474475 with app.open_resource('schema.sql') as f:476 contents = f.read()477 do_something_with(contents)

Heavily improved documentationArmin Ronacherbefore adoption05f36c7

lines 478–480why, one step back
478
479 :param resource: the name of the resource. To access resources within480 subfolders use forward slashes as separator.

Started working on documentation.Armin Ronacherbefore adoption4ec7d2a

line 481why, one step back
481 """

Flask now runs without the presence of pkg_resources as well.Armin Ronacherbefore adoption2d9bb69

lines 482–483why, one step back
482 if pkg_resources is None:
483 return open(os.path.join(self.root_path, resource), 'rb')

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 484–486
484 return pkg_resources.resource_stream(self.package_name, resource)
485486 def open_session(self, request):

Started working on documentation.Armin Ronacherbefore adoption4ec7d2a

lines 487–489why, one step back
487 """Creates or opens a new session. Default implementation stores all
488 session data in a signed cookie. This requires that the489 :attr:`secret_key` is set.

Heavily improved documentationArmin Ronacherbefore adoption05f36c7

lines 490–491why, one step back
490
491 :param request: an instance of :attr:`request_class`.

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 492–498
492 """
493 key = self.secret_key494 if key is not None:495 return SecureCookie.load_cookie(request, self.session_cookie_name,496 secret_key=key)497498 def save_session(self, session, response):

Started working on documentation.Armin Ronacherbefore adoption4ec7d2a

lines 499–500why, one step back
499 """Saves the session if it needs updates. For the default
500 implementation, check :meth:`open_session`.

Heavily improved documentationArmin Ronacherbefore adoption05f36c7

lines 501–504why, one step back
501
502 :param session: the session to be saved (a503 :class:`~werkzeug.contrib.securecookie.SecureCookie`504 object)

Fixed a documentation error and implemented template context processors.Armin Ronacherbefore adoptiona01e8b4

line 505why, one step back
505 :param response: an instance of :attr:`response_class`

Started working on documentation.Armin Ronacherbefore adoption4ec7d2a

line 506why, one step back
506 """

Session falls back to a dummy object now if secret_key is missing.Armin Ronacherbefore adoption5310fc3

line 507why, one step back
507 session.save_cookie(response, self.session_cookie_name)

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

line 508
508

Make it easier to associate a rule, endpoint and view_functionunknownbefore adoption3088a93

line 509why, one step back
509 def add_url_rule(self, rule, endpoint, view_func=None, **options):

Documented non-decorator uses of registation.Armin Ronacherbefore adoption7d6b8e9

line 510why, one step back
510 """Connects a URL rule. Works exactly like the :meth:`route`

Fix typos and remove unused import.florentxbefore adoption3c821a0

line 511why, one step back
511 decorator. If a view_func is provided it will be registered with the

Some more documentation updates.Armin Ronacherbefore adoption715f64d

line 512why, one step back
512 endpoint.

Documented non-decorator uses of registation.Armin Ronacherbefore adoption7d6b8e9

lines 513–519why, one step back
513
514 Basically this example::515516 @app.route('/')517 def index():518 pass519

Added docs, fixed some bugs I introduced last commitArmin Ronacherbefore adoption3d719f3

line 520why, one step back
520 Is equivalent to the following::

Documented non-decorator uses of registation.Armin Ronacherbefore adoption7d6b8e9

lines 521–523why, one step back
521
522 def index():523 pass

Make it easier to associate a rule, endpoint and view_functionunknownbefore adoption3088a93

line 524why, one step back
524 app.add_url_rule('/', 'index', index)

Some more documentation updates.Armin Ronacherbefore adoption715f64d

lines 525–528why, one step back
525
526 If the view_func is not provided you will need to connect the endpoint527 to a view function like so::528

Documented non-decorator uses of registation.Armin Ronacherbefore adoption7d6b8e9

line 529why, one step back
529 app.view_functions['index'] = index

Heavily improved documentationArmin Ronacherbefore adoption05f36c7

line 530why, one step back
530

Some more documentation updates.Armin Ronacherbefore adoption715f64d

lines 531–533why, one step back
531 .. versionchanged:: 0.2
532 `view_func` parameter added533

Heavily improved documentationArmin Ronacherbefore adoption05f36c7

lines 534–537why, one step back
534 :param rule: the URL rule as string
535 :param endpoint: the endpoint for the registered URL rule. Flask536 itself assumes the name of the view function as537 endpoint

Fix typos and remove unused import.florentxbefore adoption3c821a0

line 538why, one step back
538 :param view_func: the function to call when serving a request to the

Some more documentation updates.Armin Ronacherbefore adoption715f64d

line 539why, one step back
539 provided endpoint

Heavily improved documentationArmin Ronacherbefore adoption05f36c7

lines 540–541why, one step back
540 :param options: the options to be forwarded to the underlying
541 :class:`~werkzeug.routing.Rule` object

Documented non-decorator uses of registation.Armin Ronacherbefore adoption7d6b8e9

line 542why, one step back
542 """

Added docs, fixed some bugs I introduced last commitArmin Ronacherbefore adoption3d719f3

line 543why, one step back
543 options['endpoint'] = endpoint

Documented non-decorator uses of registation.Armin Ronacherbefore adoption7d6b8e9

lines 544–545why, one step back
544 options.setdefault('methods', ('GET',))
545 self.url_map.add(Rule(rule, **options))

Make it easier to associate a rule, endpoint and view_functionunknownbefore adoption3088a93

lines 546–547why, one step back
546 if view_func is not None:
547 self.view_functions[endpoint] = view_func

Documented non-decorator uses of registation.Armin Ronacherbefore adoption7d6b8e9

line 548why, one step back
548

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 549–555
549 def route(self, rule, **options):
550 """A decorator that is used to register a view function for a551 given URL rule. Example::552553 @app.route('/')554 def index():555 return 'Hello World'

Started working on documentation.Armin Ronacherbefore adoption4ec7d2a

lines 556–558why, one step back
556
557 Variables parts in the route can be specified with angular558 brackets (``/user/<username>``). By default a variable part

Added testing documentationArmin Ronacherbefore adoption03148db

line 559why, one step back
559 in the URL accepts any string without a slash however a different

Started working on documentation.Armin Ronacherbefore adoption4ec7d2a

lines 560–586why, one step back
560 converter can be specified as well by using ``<converter:name>``.
561562 Variable parts are passed to the view function as keyword563 arguments.564565 The following converters are possible:566567 =========== ===========================================568 `int` accepts integers569 `float` like `int` but for floating point values570 `path` like the default but also accepts slashes571 =========== ===========================================572573 Here some examples::574575 @app.route('/')576 def index():577 pass578579 @app.route('/<username>')580 def show_user(username):581 pass582583 @app.route('/post/<int:post_id>')584 def show_post(post_id):585 pass586

Updated documentation. Starting to look pretty goodArmin Ronacherbefore adoption4aa7621

lines 587–599why, one step back
587 An important detail to keep in mind is how Flask deals with trailing
588 slashes. The idea is to keep each URL unique so the following rules589 apply:590591 1. If a rule ends with a slash and is requested without a slash592 by the user, the user is automatically redirected to the same593 page with a trailing slash attached.594 2. If a rule does not end with a trailing slash and the user request595 the page with a trailing slash, a 404 not found is raised.596597 This is consistent with how web servers deal with static files. This598 also makes it possible to use relative link targets safely.599

Started working on documentation.Armin Ronacherbefore adoption4ec7d2a

lines 600–602why, one step back
600 The :meth:`route` decorator accepts a couple of other arguments
601 as well:602

Heavily improved documentationArmin Ronacherbefore adoption05f36c7

line 603why, one step back
603 :param rule: the URL rule as string

Started working on documentation.Armin Ronacherbefore adoption4ec7d2a

line 604why, one step back
604 :param methods: a list of methods this rule should be limited

Updated documentation. Starting to look pretty goodArmin Ronacherbefore adoption4aa7621

lines 605–606why, one step back
605 to (``GET``, ``POST`` etc.). By default a rule
606 just listens for ``GET`` (and implicitly ``HEAD``).

Started working on documentation.Armin Ronacherbefore adoption4ec7d2a

lines 607–610why, one step back
607 :param subdomain: specifies the rule for the subdoain in case
608 subdomain matching is in use.609 :param strict_slashes: can be used to disable the strict slashes610 setting for this rule. See above.

Heavily improved documentationArmin Ronacherbefore adoption05f36c7

lines 611–612why, one step back
611 :param options: other options to be forwarded to the underlying
612 :class:`~werkzeug.routing.Rule` object.

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 613–614
613 """
614 def decorator(f):

Refactored the @route decorator to use the new add_url_rule method.cgrindsbefore adoption5acc491

line 615why, one step back
615 self.add_url_rule(rule, f.__name__, f, **options)

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 616–625
616 return f
617 return decorator618619 def errorhandler(self, code):620 """A decorator that is used to register a function give a given621 error code. Example::622623 @app.errorhandler(404)624 def page_not_found():625 return 'This page does not exist', 404

Documented non-decorator uses of registation.Armin Ronacherbefore adoption7d6b8e9

lines 626–633why, one step back
626
627 You can also register a function as error handler without using628 the :meth:`errorhandler` decorator. The following example is629 equivalent to the one above::630631 def page_not_found():632 return 'This page does not exist', 404633 app.error_handlers[404] = page_not_found

Heavily improved documentationArmin Ronacherbefore adoption05f36c7

lines 634–635why, one step back
634
635 :param code: the code as integer for the handler

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 636–641
636 """
637 def decorator(f):638 self.error_handlers[code] = f639 return f640 return decorator641

request_init -> before_request and request_shutdown -> after_requestArmin Ronacherbefore adoptionfb2d2e4

line 642why, one step back
642 def before_request(self, f):

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

line 643
643 """Registers a function to run before each request."""

request_init -> before_request and request_shutdown -> after_requestArmin Ronacherbefore adoptionfb2d2e4

line 644why, one step back
644 self.before_request_funcs.append(f)

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 645–646
645 return f
646

request_init -> before_request and request_shutdown -> after_requestArmin Ronacherbefore adoptionfb2d2e4

line 647why, one step back
647 def after_request(self, f):

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

line 648
648 """Register a function to be run after each request."""

request_init -> before_request and request_shutdown -> after_requestArmin Ronacherbefore adoptionfb2d2e4

line 649why, one step back
649 self.after_request_funcs.append(f)

Fixed a documentation error and implemented template context processors.Armin Ronacherbefore adoptiona01e8b4

lines 650–654why, one step back
650 return f
651652 def context_processor(self, f):653 """Registers a template context processor function."""654 self.template_context_processors.append(f)

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 655–688
655 return f
656657 def match_request(self):658 """Matches the current request against the URL map and also659 stores the endpoint and view arguments on the request object660 is successful, otherwise the exception is stored.661 """662 rv = _request_ctx_stack.top.url_adapter.match()663 request.endpoint, request.view_args = rv664 return rv665666 def dispatch_request(self):667 """Does the request dispatching. Matches the URL and returns the668 return value of the view or error handler. This does not have to669 be a response object. In order to convert the return value to a670 proper response object, call :func:`make_response`.671 """672 try:673 endpoint, values = self.match_request()674 return self.view_functions[endpoint](**values)675 except HTTPException, e:676 handler = self.error_handlers.get(e.code)677 if handler is None:678 return e679 return handler(e)680 except Exception, e:681 handler = self.error_handlers.get(500)682 if self.debug or handler is None:683 raise684 return handler(e)685686 def make_response(self, rv):687 """Converts the return value from a view function to a real688 response object that is an instance of :attr:`response_class`.

Heavily improved documentationArmin Ronacherbefore adoption05f36c7

lines 689–704why, one step back
689
690 The following types are allowd for `rv`:691692 ======================= ===========================================693 :attr:`response_class` the object is returned unchanged694 :class:`str` a response object is created with the695 string as body696 :class:`unicode` a response object is created with the697 string encoded to utf-8 as body698 :class:`tuple` the response object is created with the699 contents of the tuple as arguments700 a WSGI function the function is called as WSGI application701 and buffered as response object702 ======================= ===========================================703704 :param rv: the return value from the view function

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 705–715
705 """
706 if isinstance(rv, self.response_class):707 return rv708 if isinstance(rv, basestring):709 return self.response_class(rv)710 if isinstance(rv, tuple):711 return self.response_class(*rv)712 return self.response_class.force_type(rv, request.environ)713714 def preprocess_request(self):715 """Called before the actual request dispatching and will

request_init -> before_request and request_shutdown -> after_requestArmin Ronacherbefore adoptionfb2d2e4

line 716why, one step back
716 call every as :meth:`before_request` decorated function.

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 717–720
717 If any of these function returns a value it's handled as
718 if it was the return value from the view and further719 request handling is stopped.720 """

request_init -> before_request and request_shutdown -> after_requestArmin Ronacherbefore adoptionfb2d2e4

line 721why, one step back
721 for func in self.before_request_funcs:

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 722–727
722 rv = func()
723 if rv is not None:724 return rv725726 def process_response(self, response):727 """Can be overridden in order to modify the response object

request_init -> before_request and request_shutdown -> after_requestArmin Ronacherbefore adoptionfb2d2e4

lines 728–729why, one step back
728 before it's sent to the WSGI server. By default this will
729 call all the :meth:`after_request` decorated functions.

Heavily improved documentationArmin Ronacherbefore adoption05f36c7

lines 730–733why, one step back
730
731 :param response: a :attr:`response_class` object.732 :return: a new response object or the same, has to be an733 instance of :attr:`response_class`.

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 734–735
734 """
735 session = _request_ctx_stack.top.session

Session falls back to a dummy object now if secret_key is missing.Armin Ronacherbefore adoption5310fc3

line 736why, one step back
736 if not isinstance(session, _NullSession):

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

line 737
737 self.save_session(session, response)

request_init -> before_request and request_shutdown -> after_requestArmin Ronacherbefore adoptionfb2d2e4

line 738why, one step back
738 for handler in self.after_request_funcs:

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 739–743
739 response = handler(response)
740 return response741742 def wsgi_app(self, environ, start_response):743 """The actual WSGI application. This is not implemented in

Added support for macro pulling and documented certain design decisions.Armin Ronacherbefore adoption190059c

lines 744–745why, one step back
744 `__call__` so that middlewares can be applied without losing a
745 reference to the class. So instead of doing this::

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

line 746
746

Added support for macro pulling and documented certain design decisions.Armin Ronacherbefore adoption190059c

lines 747–750why, one step back
747 app = MyMiddleware(app)
748749 It's a better idea to do this instead::750

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

line 751
751 app.wsgi_app = MyMiddleware(app.wsgi_app)

Added support for macro pulling and documented certain design decisions.Armin Ronacherbefore adoption190059c

lines 752–754why, one step back
752
753 Then you still have the original application object around and754 can continue to call methods on it.

Heavily improved documentationArmin Ronacherbefore adoption05f36c7

lines 755–759why, one step back
755
756 :param environ: a WSGI environment757 :param start_response: a callable accepting a status code,758 a list of headers and an optional759 exception context to start the response

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

line 760
760 """

Improved documentation, added a contextmanager for request bindingArmin Ronacherbefore adoption3b36bef

line 761why, one step back
761 with self.request_context(environ):

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 762–767
762 rv = self.preprocess_request()
763 if rv is None:764 rv = self.dispatch_request()765 response = self.make_response(rv)766 response = self.process_response(response)767 return response(environ, start_response)

Improved documentation, added a contextmanager for request bindingArmin Ronacherbefore adoption3b36bef

lines 768–778why, one step back
768
769 def request_context(self, environ):770 """Creates a request context from the given environment and binds771 it to the current context. This must be used in combination with772 the `with` statement because the request is only bound to the773 current context for the duration of the `with` block.774775 Example usage::776777 with app.request_context(environ):778 do_something_with(request)

Heavily improved documentationArmin Ronacherbefore adoption05f36c7

lines 779–780why, one step back
779
780 :params environ: a WSGI environment

Improved documentation, added a contextmanager for request bindingArmin Ronacherbefore adoption3b36bef

line 781why, one step back
781 """

Preserve the request context in debug mode.Armin Ronacherbefore adoption7b50150

line 782why, one step back
782 return _RequestContext(self, environ)

Improved documentation, added a contextmanager for request bindingArmin Ronacherbefore adoption3b36bef

lines 783–785why, one step back
783
784 def test_request_context(self, *args, **kwargs):785 """Creates a WSGI environment from the given values (see

Heavily improved documentationArmin Ronacherbefore adoption05f36c7

lines 786–787why, one step back
786 :func:`werkzeug.create_environ` for more information, this
787 function accepts the same arguments).

Improved documentation, added a contextmanager for request bindingArmin Ronacherbefore adoption3b36bef

lines 788–789why, one step back
788 """
789 return self.request_context(create_environ(*args, **kwargs))

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 790–791
790
791 def __call__(self, environ, start_response):

Fix typos and remove unused import.florentxbefore adoption3c821a0

line 792why, one step back
792 """Shortcut for :attr:`wsgi_app`."""

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 793–801
793 return self.wsgi_app(environ, start_response)
794795796# context locals797_request_ctx_stack = LocalStack()798current_app = LocalProxy(lambda: _request_ctx_stack.top.app)799request = LocalProxy(lambda: _request_ctx_stack.top.request)800session = LocalProxy(lambda: _request_ctx_stack.top.session)801g = LocalProxy(lambda: _request_ctx_stack.top.g)