api.rst
This file
Path
docs/api.rst
835 lines · 24.9 KiB
Last changed by
resolve merge conflictsKenneth Reitzbefore adoption31174fe
History of this fileTake it
The walk stopped after 200 commits: lines older than bd51d2b point at it.
Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
lines 1–32why, one step back1.. _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:resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 33why, one step back33 :inherited-members:Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
lines 34–39why, one step back3435 .. attribute:: environ3637 The underlying WSGI environment.3839 .. attribute:: pathMerge pull request #1163 from boreq/docs-updateMarkus Unterwaditzerbefore adoption670d2a4
line 40why, one step back40 .. attribute:: full_pathMerge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
lines 41–45why, one step back41 .. attribute:: script_root42 .. attribute:: url43 .. attribute:: base_url44 .. attribute:: url_root45Fix broken linkMarkus Unterwaditzerbefore adoption9c1cf1b
lines 46–48why, one step back46 Provides different ways to look at the current `IRI47 <http://tools.ietf.org/html/rfc3987>`_. Imagine your application is48 listening on the following application root::Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
lines 49–51why, one step back4950 http://www.example.com/myapplication51Merge pull request #1325 from bsutherland/rqst_properteis_doc_iri_patchMarkus Unterwaditzerbefore adoption7ae1c5a
line 52why, one step back52 And a user requests the following URI::Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
line 53why, one step back53Merge pull request #1325 from bsutherland/rqst_properteis_doc_iri_patchMarkus Unterwaditzerbefore adoption7ae1c5a
line 54why, one step back54 http://www.example.com/myapplication/%CF%80/page.html?x=yMerge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
lines 55–59why, one step back5556 In this case the values of the above mentioned attributes would be57 the following:5859 ============= ======================================================Merge pull request #1325 from bsutherland/rqst_properteis_doc_iri_patchMarkus Unterwaditzerbefore adoption7ae1c5a
lines 60–65why, one step back60 `path` ``u'/π/page.html'``61 `full_path` ``u'/π/page.html?x=y'``62 `script_root` ``u'/myapplication'``63 `base_url` ``u'http://www.example.com/myapplication/π/page.html'``64 `url` ``u'http://www.example.com/myapplication/π/page.html?x=y'``65 `url_root` ``u'http://www.example.com/myapplication/'``Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
lines 66–68why, one step back66 ============= ======================================================6768resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 69why, one step back69.. attribute:: requestMerge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
lines 70–91why, one step back7071 To access incoming request data, you can use the global `request`72 object. Flask parses incoming request data for you and gives you73 access to it through that global object. Internally Flask makes74 sure that you always get the correct data for the active thread if you75 are in a multithreaded environment.7677 This is a proxy. See :ref:`notes-on-proxies` for more information.7879 The request object is an instance of a :class:`~werkzeug.wrappers.Request`80 subclass and provides all of the attributes Werkzeug defines. This81 just shows a quick overview of the most important ones.828384Response Objects85----------------8687.. autoclass:: flask.Response88 :members: set_cookie, data, mimetype8990 .. attribute:: headers91Merge pull request #1161 from pbu88/masterMarkus Unterwaditzerbefore adoption96d7cc9
line 92why, one step back92 A :class:`~werkzeug.datastructures.Headers` object representing the response headers.Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
lines 93–125why, one step back9394 .. attribute:: status9596 A string with a response status.9798 .. attribute:: status_code99100 The response status as integer.101102103Sessions104--------105106If you have the :attr:`Flask.secret_key` set you can use sessions in Flask107applications. A session basically makes it possible to remember108information from one request to another. The way Flask does this is by109using a signed cookie. So the user can look at the session contents, but110not modify it unless they know the secret key, so make sure to set that111to something complex and unguessable.112113To access the current session you can use the :class:`session` object:114115.. class:: session116117 The session object works pretty much like an ordinary dict, with the118 difference that it keeps track on modifications.119120 This is a proxy. See :ref:`notes-on-proxies` for more information.121122 The following attributes are interesting:123124 .. attribute:: new125Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 126why, one step back126 ``True`` if the session is new, ``False`` otherwise.Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
lines 127–129why, one step back127128 .. attribute:: modified129Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 130why, one step back130 ``True`` if the session object detected a modification. Be advisedMerge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
lines 131–132why, one step back131 that modifications on mutable structures are not picked up132 automatically, in that situation you have to explicitly set theMerge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 133why, one step back133 attribute to ``True`` yourself. Here an example::Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
lines 134–142why, one step back134135 # this change is not picked up because a mutable object (here136 # a list) is changed.137 session['objects'].append(42)138 # so mark it as modified yourself139 session.modified = True140141 .. attribute:: permanent142Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 143why, one step back143 If set to ``True`` the session lives forMerge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
line 144why, one step back144 :attr:`~flask.Flask.permanent_session_lifetime` seconds. TheMerge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 145why, one step back145 default is 31 days. If set to ``False`` (which is the default) theMerge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
lines 146–226why, one step back146 session will be deleted when the user closes the browser.147148149Session Interface150-----------------151152.. versionadded:: 0.8153154The session interface provides a simple way to replace the session155implementation that Flask is using.156157.. currentmodule:: flask.sessions158159.. autoclass:: SessionInterface160 :members:161162.. autoclass:: SecureCookieSessionInterface163 :members:164165.. autoclass:: SecureCookieSession166 :members:167168.. autoclass:: NullSession169 :members:170171.. autoclass:: SessionMixin172 :members:173174.. autodata:: session_json_serializer175176 This object provides dumping and loading methods similar to simplejson177 but it also tags certain builtin Python objects that commonly appear in178 sessions. Currently the following extended values are supported in179 the JSON it dumps:180181 - :class:`~markupsafe.Markup` objects182 - :class:`~uuid.UUID` objects183 - :class:`~datetime.datetime` objects184 - :class:`tuple`\s185186.. admonition:: Notice187188 The ``PERMANENT_SESSION_LIFETIME`` config key can also be an integer189 starting with Flask 0.8. Either catch this down yourself or use190 the :attr:`~flask.Flask.permanent_session_lifetime` attribute on the191 app which converts the result to an integer automatically.192193194Test Client195-----------196197.. currentmodule:: flask.testing198199.. autoclass:: FlaskClient200 :members:201202203Application Globals204-------------------205206.. currentmodule:: flask207208To share data that is valid for one request only from one function to209another, a global variable is not good enough because it would break in210threaded environments. Flask provides you with a special object that211ensures it is only valid for the active request and that will return212different values for each request. In a nutshell: it does the right213thing, like it does for :class:`request` and :class:`session`.214215.. data:: g216217 Just store on this whatever you want. For example a database218 connection or the user that is currently logged in.219220 Starting with Flask 0.10 this is stored on the application context and221 no longer on the request context which means it becomes available if222 only the application context is bound and not yet a request. This223 is especially useful when combined with the :ref:`faking-resources`224 pattern for testing.225226 Additionally as of 0.10 you can use the :meth:`get` method toMerge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 227why, one step back227 get an attribute or ``None`` (or the second argument) if it's not set.Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
lines 228–235why, one step back228 These two usages are now equivalent::229230 user = getattr(flask.g, 'user', None)231 user = flask.g.get('user', None)232233 It's now also possible to use the ``in`` operator on it to see if an234 attribute is defined and it yields all keys on iteration.235resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 236–238why, one step back236 As of 0.11 you can use :meth:`pop` and :meth:`setdefault` in the same237 way you would use them on a dictionary.238Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
lines 239–262why, one step back239 This is a proxy. See :ref:`notes-on-proxies` for more information.240241242Useful Functions and Classes243----------------------------244245.. data:: current_app246247 Points to the application handling the request. This is useful for248 extensions that want to support multiple applications running side249 by side. This is powered by the application context and not by the250 request context, so you can change the value of this proxy by251 using the :meth:`~flask.Flask.app_context` method.252253 This is a proxy. See :ref:`notes-on-proxies` for more information.254255.. autofunction:: has_request_context256257.. autofunction:: copy_current_request_context258259.. autofunction:: has_app_context260261.. autofunction:: url_for262resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 263why, one step back263.. autofunction:: abortMerge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
lines 264–294why, one step back264265.. autofunction:: redirect266267.. autofunction:: make_response268269.. autofunction:: after_this_request270271.. autofunction:: send_file272273.. autofunction:: send_from_directory274275.. autofunction:: safe_join276277.. autofunction:: escape278279.. autoclass:: Markup280 :members: escape, unescape, striptags281282Message Flashing283----------------284285.. autofunction:: flash286287.. autofunction:: get_flashed_messages288289JSON Support290------------291292.. module:: flask.json293294Flask uses ``simplejson`` for the JSON implementation. Since simplejsonMerge pull request #1273 from prakashpp/patch-1Markus Unterwaditzerbefore adoption41b5d77
line 295why, one step back295is provided by both the standard library as well as extension, Flask willMerge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
lines 296–320why, one step back296try simplejson first and then fall back to the stdlib json module. On top297of that it will delegate access to the current application's JSON encoders298and decoders for easier customization.299300So for starters instead of doing::301302 try:303 import simplejson as json304 except ImportError:305 import json306307You can instead just do this::308309 from flask import json310311For usage examples, read the :mod:`json` documentation in the standard312library. The following extensions are by default applied to the stdlib's313JSON module:3143151. ``datetime`` objects are serialized as :rfc:`822` strings.3162. Any object with an ``__html__`` method (like :class:`~flask.Markup`)317 will have that method called and then the return value is serialized318 as string.319320The :func:`~htmlsafe_dumps` function of this json module is also availableMerge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 321why, one step back321as filter called ``|tojson`` in Jinja2. Note that inside ``script``Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
line 322why, one step back322tags no escaping must take place, so make sure to disable escapingMerge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 323why, one step back323with ``|safe`` if you intend to use it inside ``script`` tags unlessMerge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
lines 324–451why, one step back324you are using Flask 0.10 which implies that:325326.. sourcecode:: html+jinja327328 <script type=text/javascript>329 doSomethingWith({{ user.username|tojson|safe }});330 </script>331332.. admonition:: Auto-Sort JSON Keys333334 The configuration variable ``JSON_SORT_KEYS`` (:ref:`config`) can be335 set to false to stop Flask from auto-sorting keys. By default sorting336 is enabled and outside of the app context sorting is turned on.337338 Notice that disabling key sorting can cause issues when using content339 based HTTP caches and Python's hash randomization feature.340341.. autofunction:: jsonify342343.. autofunction:: dumps344345.. autofunction:: dump346347.. autofunction:: loads348349.. autofunction:: load350351.. autoclass:: JSONEncoder352 :members:353354.. autoclass:: JSONDecoder355 :members:356357Template Rendering358------------------359360.. currentmodule:: flask361362.. autofunction:: render_template363364.. autofunction:: render_template_string365366.. autofunction:: get_template_attribute367368Configuration369-------------370371.. autoclass:: Config372 :members:373374Extensions375----------376377.. data:: flask.ext378379 This module acts as redirect import module to Flask extensions. It was380 added in 0.8 as the canonical way to import Flask extensions and makes381 it possible for us to have more flexibility in how we distribute382 extensions.383384 If you want to use an extension named “Flask-Foo” you would import it385 from :data:`~flask.ext` as follows::386387 from flask.ext import foo388389 .. versionadded:: 0.8390391Stream Helpers392--------------393394.. autofunction:: stream_with_context395396Useful Internals397----------------398399.. autoclass:: flask.ctx.RequestContext400 :members:401402.. data:: _request_ctx_stack403404 The internal :class:`~werkzeug.local.LocalStack` that is used to implement405 all the context local objects used in Flask. This is a documented406 instance and can be used by extensions and application code but the407 use is discouraged in general.408409 The following attributes are always present on each layer of the410 stack:411412 `app`413 the active Flask application.414415 `url_adapter`416 the URL adapter that was used to match the request.417418 `request`419 the current request object.420421 `session`422 the active session object.423424 `g`425 an object with all the attributes of the :data:`flask.g` object.426427 `flashes`428 an internal cache for the flashed messages.429430 Example usage::431432 from flask import _request_ctx_stack433434 def get_session():435 ctx = _request_ctx_stack.top436 if ctx is not None:437 return ctx.session438439.. autoclass:: flask.ctx.AppContext440 :members:441442.. data:: _app_ctx_stack443444 Works similar to the request context but only binds the application.445 This is mainly there for extensions to store data.446447 .. versionadded:: 0.9448449.. autoclass:: flask.blueprints.BlueprintSetupState450 :members:451resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 452–453why, one step back452.. _core-signals-list:453Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
lines 454–458why, one step back454Signals455-------456457.. versionadded:: 0.6458resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 459why, one step back459.. data:: signals.signals_availableMerge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
line 460why, one step back460Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 461why, one step back461 ``True`` if the signaling system is available. This is the caseMerge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
lines 462–463why, one step back462 when `blinker`_ is installed.463resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 464–465why, one step back464The following signals exist in Flask:465Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
lines 466–471why, one step back466.. data:: template_rendered467468 This signal is sent when a template was successfully rendered. The469 signal is invoked with the instance of the template as `template`470 and the context as dictionary (named `context`).471resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 472–498why, one step back472 Example subscriber::473474 def log_template_renders(sender, template, context, **extra):475 sender.logger.debug('Rendering template "%s" with context %s',476 template.name or 'string template',477 context)478479 from flask import template_rendered480 template_rendered.connect(log_template_renders, app)481482.. data:: flask.before_render_template483 :noindex:484485 This signal is sent before template rendering process. The486 signal is invoked with the instance of the template as `template`487 and the context as dictionary (named `context`).488489 Example subscriber::490491 def log_template_renders(sender, template, context, **extra):492 sender.logger.debug('Rendering template "%s" with context %s',493 template.name or 'string template',494 context)495496 from flask import before_render_template497 before_render_template.connect(log_template_renders, app)498Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
lines 499–500why, one step back499.. data:: request_started500resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 501–502why, one step back501 This signal is sent when the request context is set up, before502 any request processing happens. Because the request context is alreadyMerge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
lines 503–505why, one step back503 bound, the subscriber can access the request with the standard global504 proxies such as :class:`~flask.request`.505resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 506–513why, one step back506 Example subscriber::507508 def log_request(sender, **extra):509 sender.logger.debug('Request context is set up')510511 from flask import request_started512 request_started.connect(log_request, app)513Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
lines 514–518why, one step back514.. data:: request_finished515516 This signal is sent right before the response is sent to the client.517 It is passed the response to be sent named `response`.518resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 519–527why, one step back519 Example subscriber::520521 def log_response(sender, response, **extra):522 sender.logger.debug('Request context is about to close down. '523 'Response: %s', response)524525 from flask import request_finished526 request_finished.connect(log_response, app)527Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
lines 528–534why, one step back528.. data:: got_request_exception529530 This signal is sent when an exception happens during request processing.531 It is sent *before* the standard exception handling kicks in and even532 in debug mode, where no exception handling happens. The exception533 itself is passed to the subscriber as `exception`.534resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 535–542why, one step back535 Example subscriber::536537 def log_exception(sender, exception, **extra):538 sender.logger.debug('Got exception during processing: %s', exception)539540 from flask import got_request_exception541 got_request_exception.connect(log_exception, app)542Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
lines 543–544why, one step back543.. data:: request_tearing_down544resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 545–548why, one step back545 This signal is sent when the request is tearing down. This is always546 called, even if an exception is caused. Currently functions listening547 to this signal are called after the regular teardown handlers, but this548 is not something you can rely on.Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
line 549why, one step back549resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 550why, one step back550 Example subscriber::Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
line 551why, one step back551resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 552–561why, one step back552 def close_db_connection(sender, **extra):553 session.close()554555 from flask import request_tearing_down556 request_tearing_down.connect(close_db_connection, app)557558 As of Flask 0.9, this will also be passed an `exc` keyword argument559 that has a reference to the exception that caused the teardown if560 there was one.561Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
lines 562–563why, one step back562.. data:: appcontext_tearing_down563resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 564–567why, one step back564 This signal is sent when the app context is tearing down. This is always565 called, even if an exception is caused. Currently functions listening566 to this signal are called after the regular teardown handlers, but this567 is not something you can rely on.Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
line 568why, one step back568resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 569–579why, one step back569 Example subscriber::570571 def close_db_connection(sender, **extra):572 session.close()573574 from flask import appcontext_tearing_down575 appcontext_tearing_down.connect(close_db_connection, app)576577 This will also be passed an `exc` keyword argument that has a reference578 to the exception that caused the teardown if there was one.579Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
lines 580–582why, one step back580.. data:: appcontext_pushed581582 This signal is sent when an application context is pushed. The senderresolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 583–585why, one step back583 is the application. This is usually useful for unittests in order to584 temporarily hook in information. For instance it can be used to585 set a resource early onto the `g` object.Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
line 586why, one step back586resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 587–606why, one step back587 Example usage::588589 from contextlib import contextmanager590 from flask import appcontext_pushed591592 @contextmanager593 def user_set(app, user):594 def handler(sender, **kwargs):595 g.user = user596 with appcontext_pushed.connected_to(handler, app):597 yield598599 And in the testcode::600601 def test_user_me(self):602 with user_set(app, 'john'):603 c = app.test_client()604 resp = c.get('/users/me')605 assert resp.data == 'username=john'606Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
lines 607–616why, one step back607 .. versionadded:: 0.10608609.. data:: appcontext_popped610611 This signal is sent when an application context is popped. The sender612 is the application. This usually falls in line with the613 :data:`appcontext_tearing_down` signal.614615 .. versionadded:: 0.10616resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 617why, one step back617Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
lines 618–623why, one step back618.. data:: message_flashed619620 This signal is sent when the application is flashing a message. The621 messages is sent as `message` keyword argument and the category as622 `category`.623resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 624why, one step back624 Example subscriber::Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
line 625why, one step back625resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 626–628why, one step back626 recorded = []627 def record(sender, message, category, **extra):628 recorded.append((message, category))Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
line 629why, one step back629resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 630–631why, one step back630 from flask import message_flashed631 message_flashed.connect(record, app)Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
line 632why, one step back632resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 633–636why, one step back633 .. versionadded:: 0.10634635.. class:: signals.Namespace636Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
lines 637–648why, one step back637 An alias for :class:`blinker.base.Namespace` if blinker is available,638 otherwise a dummy class that creates fake signals. This class is639 available for Flask extensions that want to provide the same fallback640 system as Flask itself.641642 .. method:: signal(name, doc=None)643644 Creates a new signal for this namespace if blinker is available,645 otherwise returns a fake signal that has a send method that will646 do nothing but will fail with a :exc:`RuntimeError` for all other647 operations, including connecting.648resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 649why, one step back649Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
lines 650–651why, one step back650.. _blinker: https://pypi.python.org/pypi/blinker651resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 652why, one step back652Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
lines 653–691why, one step back653Class-Based Views654-----------------655656.. versionadded:: 0.7657658.. currentmodule:: None659660.. autoclass:: flask.views.View661 :members:662663.. autoclass:: flask.views.MethodView664 :members:665666.. _url-route-registrations:667668URL Route Registrations669-----------------------670671Generally there are three ways to define rules for the routing system:6726731. You can use the :meth:`flask.Flask.route` decorator.6742. You can use the :meth:`flask.Flask.add_url_rule` function.6753. You can directly access the underlying Werkzeug routing system676 which is exposed as :attr:`flask.Flask.url_map`.677678Variable parts in the route can be specified with angular brackets679(``/user/<username>``). By default a variable part in the URL accepts any680string without a slash however a different converter can be specified as681well by using ``<converter:name>``.682683Variable parts are passed to the view function as keyword arguments.684685The following converters are available:686687=========== ===============================================688`string` accepts any text without a slash (the default)689`int` accepts integers690`float` like `int` but for floating point values691`path` like the default but also accepts slashesresolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 692–693why, one step back692`any` matches one of the items provided693`uuid` accepts UUID stringsMerge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
lines 694–695why, one step back694=========== ===============================================695Merge pull request #1448 from fordhurley/custom_convertersMarkus Unterwaditzerbefore adoption73c8335
lines 696–697why, one step back696Custom converters can be defined using :attr:`flask.Flask.url_map`.697Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
lines 698–759why, one step back698Here are some examples::699700 @app.route('/')701 def index():702 pass703704 @app.route('/<username>')705 def show_user(username):706 pass707708 @app.route('/post/<int:post_id>')709 def show_post(post_id):710 pass711712An important detail to keep in mind is how Flask deals with trailing713slashes. The idea is to keep each URL unique so the following rules714apply:7157161. If a rule ends with a slash and is requested without a slash by the717 user, the user is automatically redirected to the same page with a718 trailing slash attached.7192. If a rule does not end with a trailing slash and the user requests the720 page with a trailing slash, a 404 not found is raised.721722This is consistent with how web servers deal with static files. This723also makes it possible to use relative link targets safely.724725You can also define multiple rules for the same function. They have to be726unique however. Defaults can also be specified. Here for example is a727definition for a URL that accepts an optional page::728729 @app.route('/users/', defaults={'page': 1})730 @app.route('/users/page/<int:page>')731 def show_users(page):732 pass733734This specifies that ``/users/`` will be the URL for page one and735``/users/page/N`` will be the URL for page `N`.736737Here are the parameters that :meth:`~flask.Flask.route` and738:meth:`~flask.Flask.add_url_rule` accept. The only difference is that739with the route parameter the view function is defined with the decorator740instead of the `view_func` parameter.741742=============== ==========================================================743`rule` the URL rule as string744`endpoint` the endpoint for the registered URL rule. Flask itself745 assumes that the name of the view function is the name746 of the endpoint if not explicitly stated.747`view_func` the function to call when serving a request to the748 provided endpoint. If this is not provided one can749 specify the function later by storing it in the750 :attr:`~flask.Flask.view_functions` dictionary with the751 endpoint as key.752`defaults` A dictionary with defaults for this rule. See the753 example above for how defaults work.754`subdomain` specifies the rule for the subdomain in case subdomain755 matching is in use. If not specified the default756 subdomain is assumed.757`**options` the options to be forwarded to the underlying758 :class:`~werkzeug.routing.Rule` object. A change to759 Werkzeug is handling of method options. methods is a listMerge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
lines 760–762why, one step back760 of methods this rule should be limited to (``GET``, ``POST``761 etc.). By default a rule just listens for ``GET`` (and762 implicitly ``HEAD``). Starting with Flask 0.6, ``OPTIONS`` isMerge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
lines 763–782why, one step back763 implicitly added and handled by the standard request764 handling. They have to be specified as keyword arguments.765=============== ==========================================================766767.. _view-func-options:768769View Function Options770---------------------771772For internal usage the view functions can have some attributes attached to773customize behavior the view function would normally not have control over.774The following attributes can be provided optionally to either override775some defaults to :meth:`~flask.Flask.add_url_rule` or general behavior:776777- `__name__`: The name of a function is by default used as endpoint. If778 endpoint is provided explicitly this value is used. Additionally this779 will be prefixed with the name of the blueprint by default which780 cannot be customized from the function itself.781782- `methods`: If methods are not provided when the URL rule is added,Merge pull request #1269 from pkuphy/patch-2Markus Unterwaditzerbefore adoption3bf9c2e
line 783why, one step back783 Flask will look on the view function object itself if a `methods`Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
lines 784–788why, one step back784 attribute exists. If it does, it will pull the information for the785 methods from there.786787- `provide_automatic_options`: if this attribute is set Flask will788 either force enable or disable the automatic implementation of theMerge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
lines 789–790why, one step back789 HTTP ``OPTIONS`` response. This can be useful when working with790 decorators that want to customize the ``OPTIONS`` response on a per-viewMerge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
lines 791–819why, one step back791 basis.792793- `required_methods`: if this attribute is set, Flask will always add794 these methods when registering a URL rule even if the methods were795 explicitly overridden in the ``route()`` call.796797Full example::798799 def index():800 if request.method == 'OPTIONS':801 # custom options handling here802 ...803 return 'Hello World!'804 index.provide_automatic_options = False805 index.methods = ['GET', 'OPTIONS']806807 app.add_url_rule('/', index)808809.. versionadded:: 0.8810 The `provide_automatic_options` functionality was added.811812Command Line Interface813----------------------814815.. currentmodule:: flask.cli816817.. autoclass:: FlaskGroup818 :members:819Refactored the scripting interface greatly.Armin Ronacherbefore adoption932f7d7
lines 820–822why, one step back820.. autoclass:: AppGroup821 :members:822Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
lines 823–825why, one step back823.. autoclass:: ScriptInfo824 :members:825Refactored the scripting interface greatly.Armin Ronacherbefore adoption932f7d7
lines 826–827why, one step back826.. autofunction:: with_appcontext827Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
line 828why, one step back828.. autofunction:: pass_script_infoMerge pull request #1161 from pbu88/masterMarkus Unterwaditzerbefore adoption96d7cc9
line 829why, one step back829Added some missing documentation information.Armin Ronacherbefore adoptionafb613c
lines 830–831why, one step back830 Marks a function so that an instance of :class:`ScriptInfo` is passed831 as first argument to the click callback.Merge pull request #1052 from miguelgrinberg/masterKenneth Reitzbefore adoptionbd51d2b
lines 832–835why, one step back832833.. autodata:: run_command834835.. autodata:: shell_command