Skip to content
Myr

api.rst

This file

Path

docs/api.rst

882 lines · 26.6 KiB

Last changed by

Deduplicate signals docsMarkus Unterwaditzerbefore adoptionbeec47a

History of this file

Take it

The walk stopped after 200 commits: lines older than 135d090 point at it.

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption135d090

lines 1–35why, one step back
1.. _api:
23API4===56.. module:: flask78This part of the documentation covers all the interfaces of Flask. For9parts where Flask depends on external libraries, we document the most10important right here and provide links to the canonical documentation.111213Application Object14------------------1516.. autoclass:: Flask17 :members:18 :inherited-members:192021Blueprint Objects22-----------------2324.. autoclass:: Blueprint25 :members:26 :inherited-members:2728Incoming Request Data29---------------------3031.. autoclass:: Request32 :members:3334 .. attribute:: form35

Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae

lines 36–37why, one step back
36 A :class:`~werkzeug.datastructures.MultiDict` with the parsed form data from ``POST``
37 or ``PUT`` requests. Please keep in mind that file uploads will not

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption135d090

lines 38–73why, one step back
38 end up here, but instead in the :attr:`files` attribute.
3940 .. attribute:: args4142 A :class:`~werkzeug.datastructures.MultiDict` with the parsed contents of the query43 string. (The part in the URL after the question mark).4445 .. attribute:: values4647 A :class:`~werkzeug.datastructures.CombinedMultiDict` with the contents of both48 :attr:`form` and :attr:`args`.4950 .. attribute:: cookies5152 A :class:`dict` with the contents of all cookies transmitted with53 the request.5455 .. attribute:: stream5657 If the incoming form data was not encoded with a known mimetype58 the data is stored unmodified in this stream for consumption. Most59 of the time it is a better idea to use :attr:`data` which will give60 you that data as a string. The stream only returns the data once.6162 .. attribute:: headers6364 The incoming request headers as a dictionary like object.6566 .. attribute:: data6768 Contains the incoming request data as string in case it came with69 a mimetype Flask does not handle.7071 .. attribute:: files7273 A :class:`~werkzeug.datastructures.MultiDict` with files uploaded as part of a

Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae

line 74why, one step back
74 ``POST`` or ``PUT`` request. Each file is stored as

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption135d090

lines 75–88why, one step back
75 :class:`~werkzeug.datastructures.FileStorage` object. It basically behaves like a
76 standard file object you know from Python, with the difference that77 it also has a :meth:`~werkzeug.datastructures.FileStorage.save` function that can78 store the file on the filesystem.7980 .. attribute:: environ8182 The underlying WSGI environment.8384 .. attribute:: method8586 The current request method (``POST``, ``GET`` etc.)8788 .. attribute:: path

Merge pull request #1163 from boreq/docs-updateMarkus Unterwaditzerbefore adoption670d2a4

line 89why, one step back
89 .. attribute:: full_path

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption135d090

lines 90–94why, one step back
90 .. attribute:: script_root
91 .. attribute:: url92 .. attribute:: base_url93 .. attribute:: url_root94

Fix broken linkMarkus Unterwaditzerbefore adoption9c1cf1b

lines 95–97why, one step back
95 Provides different ways to look at the current `IRI
96 <http://tools.ietf.org/html/rfc3987>`_. Imagine your application is97 listening on the following application root::

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption135d090

lines 98–100why, one step back
98
99 http://www.example.com/myapplication100

Merge pull request #1325 from bsutherland/rqst_properteis_doc_iri_patchMarkus Unterwaditzerbefore adoption7ae1c5a

line 101why, one step back
101 And a user requests the following URI::

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption135d090

line 102why, one step back
102

Merge pull request #1325 from bsutherland/rqst_properteis_doc_iri_patchMarkus Unterwaditzerbefore adoption7ae1c5a

line 103why, one step back
103 http://www.example.com/myapplication/%CF%80/page.html?x=y

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption135d090

lines 104–108why, one step back
104
105 In this case the values of the above mentioned attributes would be106 the following:107108 ============= ======================================================

Merge pull request #1325 from bsutherland/rqst_properteis_doc_iri_patchMarkus Unterwaditzerbefore adoption7ae1c5a

lines 109–114why, one step back
109 `path` ``u'/π/page.html'``
110 `full_path` ``u'/π/page.html?x=y'``111 `script_root` ``u'/myapplication'``112 `base_url` ``u'http://www.example.com/myapplication/π/page.html'``113 `url` ``u'http://www.example.com/myapplication/π/page.html?x=y'``114 `url_root` ``u'http://www.example.com/myapplication/'``

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption135d090

lines 115–118why, one step back
115 ============= ======================================================
116117 .. attribute:: is_xhr118

Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae

line 119why, one step back
119 ``True`` if the request was triggered via a JavaScript

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption135d090

lines 120–147why, one step back
120 `XMLHttpRequest`. This only works with libraries that support the
121 ``X-Requested-With`` header and set it to `XMLHttpRequest`.122 Libraries that do that are prototype, jQuery and Mochikit and123 probably some more.124125.. class:: request126127 To access incoming request data, you can use the global `request`128 object. Flask parses incoming request data for you and gives you129 access to it through that global object. Internally Flask makes130 sure that you always get the correct data for the active thread if you131 are in a multithreaded environment.132133 This is a proxy. See :ref:`notes-on-proxies` for more information.134135 The request object is an instance of a :class:`~werkzeug.wrappers.Request`136 subclass and provides all of the attributes Werkzeug defines. This137 just shows a quick overview of the most important ones.138139140Response Objects141----------------142143.. autoclass:: flask.Response144 :members: set_cookie, data, mimetype145146 .. attribute:: headers147

Merge pull request #1161 from pbu88/masterMarkus Unterwaditzerbefore adoption96d7cc9

line 148why, one step back
148 A :class:`~werkzeug.datastructures.Headers` object representing the response headers.

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption135d090

lines 149–181why, one step back
149
150 .. attribute:: status151152 A string with a response status.153154 .. attribute:: status_code155156 The response status as integer.157158159Sessions160--------161162If you have the :attr:`Flask.secret_key` set you can use sessions in Flask163applications. A session basically makes it possible to remember164information from one request to another. The way Flask does this is by165using a signed cookie. So the user can look at the session contents, but166not modify it unless they know the secret key, so make sure to set that167to something complex and unguessable.168169To access the current session you can use the :class:`session` object:170171.. class:: session172173 The session object works pretty much like an ordinary dict, with the174 difference that it keeps track on modifications.175176 This is a proxy. See :ref:`notes-on-proxies` for more information.177178 The following attributes are interesting:179180 .. attribute:: new181

Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae

line 182why, one step back
182 ``True`` if the session is new, ``False`` otherwise.

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption135d090

lines 183–185why, one step back
183
184 .. attribute:: modified185

Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae

line 186why, one step back
186 ``True`` if the session object detected a modification. Be advised

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption135d090

lines 187–188why, one step back
187 that modifications on mutable structures are not picked up
188 automatically, in that situation you have to explicitly set the

Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae

line 189why, one step back
189 attribute to ``True`` yourself. Here an example::

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption135d090

lines 190–198why, one step back
190
191 # this change is not picked up because a mutable object (here192 # a list) is changed.193 session['objects'].append(42)194 # so mark it as modified yourself195 session.modified = True196197 .. attribute:: permanent198

Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae

line 199why, one step back
199 If set to ``True`` the session lives for

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption135d090

line 200why, one step back
200 :attr:`~flask.Flask.permanent_session_lifetime` seconds. The

Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae

line 201why, one step back
201 default is 31 days. If set to ``False`` (which is the default) the

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption135d090

lines 202–282why, one step back
202 session will be deleted when the user closes the browser.
203204205Session Interface206-----------------207208.. versionadded:: 0.8209210The session interface provides a simple way to replace the session211implementation that Flask is using.212213.. currentmodule:: flask.sessions214215.. autoclass:: SessionInterface216 :members:217218.. autoclass:: SecureCookieSessionInterface219 :members:220221.. autoclass:: SecureCookieSession222 :members:223224.. autoclass:: NullSession225 :members:226227.. autoclass:: SessionMixin228 :members:229230.. autodata:: session_json_serializer231232 This object provides dumping and loading methods similar to simplejson233 but it also tags certain builtin Python objects that commonly appear in234 sessions. Currently the following extended values are supported in235 the JSON it dumps:236237 - :class:`~markupsafe.Markup` objects238 - :class:`~uuid.UUID` objects239 - :class:`~datetime.datetime` objects240 - :class:`tuple`\s241242.. admonition:: Notice243244 The ``PERMANENT_SESSION_LIFETIME`` config key can also be an integer245 starting with Flask 0.8. Either catch this down yourself or use246 the :attr:`~flask.Flask.permanent_session_lifetime` attribute on the247 app which converts the result to an integer automatically.248249250Test Client251-----------252253.. currentmodule:: flask.testing254255.. autoclass:: FlaskClient256 :members:257258259Application Globals260-------------------261262.. currentmodule:: flask263264To share data that is valid for one request only from one function to265another, a global variable is not good enough because it would break in266threaded environments. Flask provides you with a special object that267ensures it is only valid for the active request and that will return268different values for each request. In a nutshell: it does the right269thing, like it does for :class:`request` and :class:`session`.270271.. data:: g272273 Just store on this whatever you want. For example a database274 connection or the user that is currently logged in.275276 Starting with Flask 0.10 this is stored on the application context and277 no longer on the request context which means it becomes available if278 only the application context is bound and not yet a request. This279 is especially useful when combined with the :ref:`faking-resources`280 pattern for testing.281282 Additionally as of 0.10 you can use the :meth:`get` method to

Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae

line 283why, one step back
283 get an attribute or ``None`` (or the second argument) if it's not set.

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption135d090

lines 284–353why, one step back
284 These two usages are now equivalent::
285286 user = getattr(flask.g, 'user', None)287 user = flask.g.get('user', None)288289 It's now also possible to use the ``in`` operator on it to see if an290 attribute is defined and it yields all keys on iteration.291292 This is a proxy. See :ref:`notes-on-proxies` for more information.293294295Useful Functions and Classes296----------------------------297298.. data:: current_app299300 Points to the application handling the request. This is useful for301 extensions that want to support multiple applications running side302 by side. This is powered by the application context and not by the303 request context, so you can change the value of this proxy by304 using the :meth:`~flask.Flask.app_context` method.305306 This is a proxy. See :ref:`notes-on-proxies` for more information.307308.. autofunction:: has_request_context309310.. autofunction:: copy_current_request_context311312.. autofunction:: has_app_context313314.. autofunction:: url_for315316.. function:: abort(code)317318 Raises an :exc:`~werkzeug.exceptions.HTTPException` for the given319 status code. For example to abort request handling with a page not320 found exception, you would call ``abort(404)``.321322 :param code: the HTTP error code.323324.. autofunction:: redirect325326.. autofunction:: make_response327328.. autofunction:: after_this_request329330.. autofunction:: send_file331332.. autofunction:: send_from_directory333334.. autofunction:: safe_join335336.. autofunction:: escape337338.. autoclass:: Markup339 :members: escape, unescape, striptags340341Message Flashing342----------------343344.. autofunction:: flash345346.. autofunction:: get_flashed_messages347348JSON Support349------------350351.. module:: flask.json352353Flask uses ``simplejson`` for the JSON implementation. Since simplejson

Merge pull request #1273 from prakashpp/patch-1Markus Unterwaditzerbefore adoption41b5d77

line 354why, one step back
354is provided by both the standard library as well as extension, Flask will

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption135d090

lines 355–379why, one step back
355try simplejson first and then fall back to the stdlib json module. On top
356of that it will delegate access to the current application's JSON encoders357and decoders for easier customization.358359So for starters instead of doing::360361 try:362 import simplejson as json363 except ImportError:364 import json365366You can instead just do this::367368 from flask import json369370For usage examples, read the :mod:`json` documentation in the standard371library. The following extensions are by default applied to the stdlib's372JSON module:3733741. ``datetime`` objects are serialized as :rfc:`822` strings.3752. Any object with an ``__html__`` method (like :class:`~flask.Markup`)376 will have that method called and then the return value is serialized377 as string.378379The :func:`~htmlsafe_dumps` function of this json module is also available

Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae

line 380why, one step back
380as filter called ``|tojson`` in Jinja2. Note that inside ``script``

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption135d090

line 381why, one step back
381tags no escaping must take place, so make sure to disable escaping

Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae

line 382why, one step back
382with ``|safe`` if you intend to use it inside ``script`` tags unless

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption135d090

lines 383–510why, one step back
383you are using Flask 0.10 which implies that:
384385.. sourcecode:: html+jinja386387 <script type=text/javascript>388 doSomethingWith({{ user.username|tojson|safe }});389 </script>390391.. admonition:: Auto-Sort JSON Keys392393 The configuration variable ``JSON_SORT_KEYS`` (:ref:`config`) can be394 set to false to stop Flask from auto-sorting keys. By default sorting395 is enabled and outside of the app context sorting is turned on.396397 Notice that disabling key sorting can cause issues when using content398 based HTTP caches and Python's hash randomization feature.399400.. autofunction:: jsonify401402.. autofunction:: dumps403404.. autofunction:: dump405406.. autofunction:: loads407408.. autofunction:: load409410.. autoclass:: JSONEncoder411 :members:412413.. autoclass:: JSONDecoder414 :members:415416Template Rendering417------------------418419.. currentmodule:: flask420421.. autofunction:: render_template422423.. autofunction:: render_template_string424425.. autofunction:: get_template_attribute426427Configuration428-------------429430.. autoclass:: Config431 :members:432433Extensions434----------435436.. data:: flask.ext437438 This module acts as redirect import module to Flask extensions. It was439 added in 0.8 as the canonical way to import Flask extensions and makes440 it possible for us to have more flexibility in how we distribute441 extensions.442443 If you want to use an extension named “Flask-Foo” you would import it444 from :data:`~flask.ext` as follows::445446 from flask.ext import foo447448 .. versionadded:: 0.8449450Stream Helpers451--------------452453.. autofunction:: stream_with_context454455Useful Internals456----------------457458.. autoclass:: flask.ctx.RequestContext459 :members:460461.. data:: _request_ctx_stack462463 The internal :class:`~werkzeug.local.LocalStack` that is used to implement464 all the context local objects used in Flask. This is a documented465 instance and can be used by extensions and application code but the466 use is discouraged in general.467468 The following attributes are always present on each layer of the469 stack:470471 `app`472 the active Flask application.473474 `url_adapter`475 the URL adapter that was used to match the request.476477 `request`478 the current request object.479480 `session`481 the active session object.482483 `g`484 an object with all the attributes of the :data:`flask.g` object.485486 `flashes`487 an internal cache for the flashed messages.488489 Example usage::490491 from flask import _request_ctx_stack492493 def get_session():494 ctx = _request_ctx_stack.top495 if ctx is not None:496 return ctx.session497498.. autoclass:: flask.ctx.AppContext499 :members:500501.. data:: _app_ctx_stack502503 Works similar to the request context but only binds the application.504 This is mainly there for extensions to store data.505506 .. versionadded:: 0.9507508.. autoclass:: flask.blueprints.BlueprintSetupState509 :members:510

Deduplicate signals docsMarkus Unterwaditzerbefore adoptionbeec47a

lines 511–512why, one step back
511.. _core-signals-list:
512

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption135d090

lines 513–517why, one step back
513Signals
514-------515516.. versionadded:: 0.6517

Deduplicate signals docsMarkus Unterwaditzerbefore adoptionbeec47a

line 518why, one step back
518.. data:: signals.signals_available

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption135d090

line 519why, one step back
519

Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae

line 520why, one step back
520 ``True`` if the signaling system is available. This is the case

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption135d090

lines 521–522why, one step back
521 when `blinker`_ is installed.
522

Deduplicate signals docsMarkus Unterwaditzerbefore adoptionbeec47a

lines 523–524why, one step back
523The following signals exist in Flask:
524

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption135d090

lines 525–530why, one step back
525.. data:: template_rendered
526527 This signal is sent when a template was successfully rendered. The528 signal is invoked with the instance of the template as `template`529 and the context as dictionary (named `context`).530

Deduplicate signals docsMarkus Unterwaditzerbefore adoptionbeec47a

lines 531–540why, one step back
531 Example subscriber::
532533 def log_template_renders(sender, template, context, **extra):534 sender.logger.debug('Rendering template "%s" with context %s',535 template.name or 'string template',536 context)537538 from flask import template_rendered539 template_rendered.connect(log_template_renders, app)540

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption135d090

lines 541–542why, one step back
541.. data:: request_started
542

Deduplicate signals docsMarkus Unterwaditzerbefore adoptionbeec47a

lines 543–544why, one step back
543 This signal is sent when the request context is set up, before
544 any request processing happens. Because the request context is already

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption135d090

lines 545–547why, one step back
545 bound, the subscriber can access the request with the standard global
546 proxies such as :class:`~flask.request`.547

Deduplicate signals docsMarkus Unterwaditzerbefore adoptionbeec47a

lines 548–555why, one step back
548 Example subscriber::
549550 def log_request(sender, **extra):551 sender.logger.debug('Request context is set up')552553 from flask import request_started554 request_started.connect(log_request, app)555

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption135d090

lines 556–560why, one step back
556.. data:: request_finished
557558 This signal is sent right before the response is sent to the client.559 It is passed the response to be sent named `response`.560

Deduplicate signals docsMarkus Unterwaditzerbefore adoptionbeec47a

lines 561–569why, one step back
561 Example subscriber::
562563 def log_response(sender, response, **extra):564 sender.logger.debug('Request context is about to close down. '565 'Response: %s', response)566567 from flask import request_finished568 request_finished.connect(log_response, app)569

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption135d090

lines 570–576why, one step back
570.. data:: got_request_exception
571572 This signal is sent when an exception happens during request processing.573 It is sent *before* the standard exception handling kicks in and even574 in debug mode, where no exception handling happens. The exception575 itself is passed to the subscriber as `exception`.576

Deduplicate signals docsMarkus Unterwaditzerbefore adoptionbeec47a

lines 577–584why, one step back
577 Example subscriber::
578579 def log_exception(sender, exception, **extra):580 sender.logger.debug('Got exception during processing: %s', exception)581582 from flask import got_request_exception583 got_request_exception.connect(log_exception, app)584

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption135d090

lines 585–586why, one step back
585.. data:: request_tearing_down
586

Deduplicate signals docsMarkus Unterwaditzerbefore adoptionbeec47a

lines 587–590why, one step back
587 This signal is sent when the request is tearing down. This is always
588 called, even if an exception is caused. Currently functions listening589 to this signal are called after the regular teardown handlers, but this590 is not something you can rely on.

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption135d090

line 591why, one step back
591

Deduplicate signals docsMarkus Unterwaditzerbefore adoptionbeec47a

line 592why, one step back
592 Example subscriber::

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption135d090

line 593why, one step back
593

Deduplicate signals docsMarkus Unterwaditzerbefore adoptionbeec47a

lines 594–603why, one step back
594 def close_db_connection(sender, **extra):
595 session.close()596597 from flask import request_tearing_down598 request_tearing_down.connect(close_db_connection, app)599600 As of Flask 0.9, this will also be passed an `exc` keyword argument601 that has a reference to the exception that caused the teardown if602 there was one.603

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption135d090

lines 604–605why, one step back
604.. data:: appcontext_tearing_down
605

Deduplicate signals docsMarkus Unterwaditzerbefore adoptionbeec47a

lines 606–609why, one step back
606 This signal is sent when the app context is tearing down. This is always
607 called, even if an exception is caused. Currently functions listening608 to this signal are called after the regular teardown handlers, but this609 is not something you can rely on.

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption135d090

line 610why, one step back
610

Deduplicate signals docsMarkus Unterwaditzerbefore adoptionbeec47a

lines 611–621why, one step back
611 Example subscriber::
612613 def close_db_connection(sender, **extra):614 session.close()615616 from flask import appcontext_tearing_down617 appcontext_tearing_down.connect(close_db_connection, app)618619 This will also be passed an `exc` keyword argument that has a reference620 to the exception that caused the teardown if there was one.621

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption135d090

lines 622–624why, one step back
622.. data:: appcontext_pushed
623624 This signal is sent when an application context is pushed. The sender

Deduplicate signals docsMarkus Unterwaditzerbefore adoptionbeec47a

lines 625–627why, one step back
625 is the application. This is usually useful for unittests in order to
626 temporarily hook in information. For instance it can be used to627 set a resource early onto the `g` object.

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption135d090

line 628why, one step back
628

Deduplicate signals docsMarkus Unterwaditzerbefore adoptionbeec47a

lines 629–648why, one step back
629 Example usage::
630631 from contextlib import contextmanager632 from flask import appcontext_pushed633634 @contextmanager635 def user_set(app, user):636 def handler(sender, **kwargs):637 g.user = user638 with appcontext_pushed.connected_to(handler, app):639 yield640641 And in the testcode::642643 def test_user_me(self):644 with user_set(app, 'john'):645 c = app.test_client()646 resp = c.get('/users/me')647 assert resp.data == 'username=john'648

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption135d090

lines 649–658why, one step back
649 .. versionadded:: 0.10
650651.. data:: appcontext_popped652653 This signal is sent when an application context is popped. The sender654 is the application. This usually falls in line with the655 :data:`appcontext_tearing_down` signal.656657 .. versionadded:: 0.10658

Deduplicate signals docsMarkus Unterwaditzerbefore adoptionbeec47a

line 659why, one step back
659

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption135d090

lines 660–665why, one step back
660.. data:: message_flashed
661662 This signal is sent when the application is flashing a message. The663 messages is sent as `message` keyword argument and the category as664 `category`.665

Deduplicate signals docsMarkus Unterwaditzerbefore adoptionbeec47a

line 666why, one step back
666 Example subscriber::

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption135d090

line 667why, one step back
667

Deduplicate signals docsMarkus Unterwaditzerbefore adoptionbeec47a

lines 668–670why, one step back
668 recorded = []
669 def record(sender, message, category, **extra):670 recorded.append((message, category))

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption135d090

line 671why, one step back
671

Deduplicate signals docsMarkus Unterwaditzerbefore adoptionbeec47a

lines 672–673why, one step back
672 from flask import message_flashed
673 message_flashed.connect(record, app)

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption135d090

line 674why, one step back
674

Deduplicate signals docsMarkus Unterwaditzerbefore adoptionbeec47a

lines 675–678why, one step back
675 .. versionadded:: 0.10
676677.. class:: signals.Namespace678

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption135d090

lines 679–690why, one step back
679 An alias for :class:`blinker.base.Namespace` if blinker is available,
680 otherwise a dummy class that creates fake signals. This class is681 available for Flask extensions that want to provide the same fallback682 system as Flask itself.683684 .. method:: signal(name, doc=None)685686 Creates a new signal for this namespace if blinker is available,687 otherwise returns a fake signal that has a send method that will688 do nothing but will fail with a :exc:`RuntimeError` for all other689 operations, including connecting.690

Deduplicate signals docsMarkus Unterwaditzerbefore adoptionbeec47a

line 691why, one step back
691

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption67e4d3e

line 692why, one step back
692.. _blinker: https://pypi.python.org/pypi/blinker

Deduplicate signals docsMarkus Unterwaditzerbefore adoptionbeec47a

line 693why, one step back
693

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption135d090

lines 694–735why, one step back
694
695Class-Based Views696-----------------697698.. versionadded:: 0.7699700.. currentmodule:: None701702.. autoclass:: flask.views.View703 :members:704705.. autoclass:: flask.views.MethodView706 :members:707708.. _url-route-registrations:709710URL Route Registrations711-----------------------712713Generally there are three ways to define rules for the routing system:7147151. You can use the :meth:`flask.Flask.route` decorator.7162. You can use the :meth:`flask.Flask.add_url_rule` function.7173. You can directly access the underlying Werkzeug routing system718 which is exposed as :attr:`flask.Flask.url_map`.719720Variable parts in the route can be specified with angular brackets721(``/user/<username>``). By default a variable part in the URL accepts any722string without a slash however a different converter can be specified as723well by using ``<converter:name>``.724725Variable parts are passed to the view function as keyword arguments.726727The following converters are available:728729=========== ===============================================730`string` accepts any text without a slash (the default)731`int` accepts integers732`float` like `int` but for floating point values733`path` like the default but also accepts slashes734=========== ===============================================735

Merge pull request #1448 from fordhurley/custom_convertersMarkus Unterwaditzerbefore adoption73c8335

lines 736–737why, one step back
736Custom converters can be defined using :attr:`flask.Flask.url_map`.
737

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption135d090

lines 738–799why, one step back
738Here are some examples::
739740 @app.route('/')741 def index():742 pass743744 @app.route('/<username>')745 def show_user(username):746 pass747748 @app.route('/post/<int:post_id>')749 def show_post(post_id):750 pass751752An important detail to keep in mind is how Flask deals with trailing753slashes. The idea is to keep each URL unique so the following rules754apply:7557561. If a rule ends with a slash and is requested without a slash by the757 user, the user is automatically redirected to the same page with a758 trailing slash attached.7592. If a rule does not end with a trailing slash and the user requests the760 page with a trailing slash, a 404 not found is raised.761762This is consistent with how web servers deal with static files. This763also makes it possible to use relative link targets safely.764765You can also define multiple rules for the same function. They have to be766unique however. Defaults can also be specified. Here for example is a767definition for a URL that accepts an optional page::768769 @app.route('/users/', defaults={'page': 1})770 @app.route('/users/page/<int:page>')771 def show_users(page):772 pass773774This specifies that ``/users/`` will be the URL for page one and775``/users/page/N`` will be the URL for page `N`.776777Here are the parameters that :meth:`~flask.Flask.route` and778:meth:`~flask.Flask.add_url_rule` accept. The only difference is that779with the route parameter the view function is defined with the decorator780instead of the `view_func` parameter.781782=============== ==========================================================783`rule` the URL rule as string784`endpoint` the endpoint for the registered URL rule. Flask itself785 assumes that the name of the view function is the name786 of the endpoint if not explicitly stated.787`view_func` the function to call when serving a request to the788 provided endpoint. If this is not provided one can789 specify the function later by storing it in the790 :attr:`~flask.Flask.view_functions` dictionary with the791 endpoint as key.792`defaults` A dictionary with defaults for this rule. See the793 example above for how defaults work.794`subdomain` specifies the rule for the subdomain in case subdomain795 matching is in use. If not specified the default796 subdomain is assumed.797`**options` the options to be forwarded to the underlying798 :class:`~werkzeug.routing.Rule` object. A change to799 Werkzeug is handling of method options. methods is a list

Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae

lines 800–802why, one step back
800 of methods this rule should be limited to (``GET``, ``POST``
801 etc.). By default a rule just listens for ``GET`` (and802 implicitly ``HEAD``). Starting with Flask 0.6, ``OPTIONS`` is

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption135d090

lines 803–822why, one step back
803 implicitly added and handled by the standard request
804 handling. They have to be specified as keyword arguments.805=============== ==========================================================806807.. _view-func-options:808809View Function Options810---------------------811812For internal usage the view functions can have some attributes attached to813customize behavior the view function would normally not have control over.814The following attributes can be provided optionally to either override815some defaults to :meth:`~flask.Flask.add_url_rule` or general behavior:816817- `__name__`: The name of a function is by default used as endpoint. If818 endpoint is provided explicitly this value is used. Additionally this819 will be prefixed with the name of the blueprint by default which820 cannot be customized from the function itself.821822- `methods`: If methods are not provided when the URL rule is added,

Merge pull request #1269 from pkuphy/patch-2Markus Unterwaditzerbefore adoption3bf9c2e

line 823why, one step back
823 Flask will look on the view function object itself if a `methods`

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption135d090

lines 824–828why, one step back
824 attribute exists. If it does, it will pull the information for the
825 methods from there.826827- `provide_automatic_options`: if this attribute is set Flask will828 either force enable or disable the automatic implementation of the

Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae

lines 829–830why, one step back
829 HTTP ``OPTIONS`` response. This can be useful when working with
830 decorators that want to customize the ``OPTIONS`` response on a per-view

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption135d090

lines 831–850why, one step back
831 basis.
832833- `required_methods`: if this attribute is set, Flask will always add834 these methods when registering a URL rule even if the methods were835 explicitly overridden in the ``route()`` call.836837Full example::838839 def index():840 if request.method == 'OPTIONS':841 # custom options handling here842 ...843 return 'Hello World!'844 index.provide_automatic_options = False845 index.methods = ['GET', 'OPTIONS']846847 app.add_url_rule('/', index)848849.. versionadded:: 0.8850 The `provide_automatic_options` functionality was added.

Greatly refactored click integration and documented it a bit more.Armin Ronacherbefore adoption3569fc2

lines 851–859why, one step back
851
852Command Line Interface853----------------------854855.. currentmodule:: flask.cli856857.. autoclass:: FlaskGroup858 :members:859

Refactored the scripting interface greatly.Armin Ronacherbefore adoption932f7d7

lines 860–862why, one step back
860.. autoclass:: AppGroup
861 :members:862

Greatly refactored click integration and documented it a bit more.Armin Ronacherbefore adoption3569fc2

lines 863–865why, one step back
863.. autoclass:: ScriptInfo
864 :members:865

Refactored the scripting interface greatly.Armin Ronacherbefore adoption932f7d7

lines 866–867why, one step back
866.. autofunction:: with_appcontext
867

Greatly refactored click integration and documented it a bit more.Armin Ronacherbefore adoption3569fc2

line 868why, one step back
868.. autofunction:: pass_script_info

Merge pull request #1161 from pbu88/masterMarkus Unterwaditzerbefore adoption96d7cc9

line 869why, one step back
869

Added some missing documentation information.Armin Ronacherbefore adoptionafb613c

lines 870–871why, one step back
870 Marks a function so that an instance of :class:`ScriptInfo` is passed
871 as first argument to the click callback.

Greatly refactored click integration and documented it a bit more.Armin Ronacherbefore adoption3569fc2

lines 872–877why, one step back
872
873.. autofunction:: script_info_option874875 A special decorator that informs a click callback to be passed the876 script info object as first argument. This is normally not useful877 unless you implement very special commands like the run command which

Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae

line 878why, one step back
878 does not want the application to be loaded yet.

Greatly refactored click integration and documented it a bit more.Armin Ronacherbefore adoption3569fc2

lines 879–882why, one step back
879
880.. autodata:: run_command881882.. autodata:: shell_command