api.rst
This file
Path
docs/api.rst
828 lines · 24.6 KiB
Last changed by
Merge pull request #2416 from davidism/dotenvDavid Lordbefore adoption851eaa4
History of this fileTake it
The walk stopped after 200 commits: lines older than 2f60124 point at it.
Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
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:Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
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_pathRemoved ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
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::Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
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::Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
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=yRemoved ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
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/'``Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
lines 66–68why, one step back66 ============= ======================================================6768resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 69why, one step back69.. attribute:: requestRemoved ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
lines 70–87why, 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.ResponseMerge pull request #2358 from davidism/json-mixinDavid Lordbefore adoption63129e8
line 88why, one step back88 :members: set_cookie, data, mimetype, is_json, get_jsonRemoved ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
lines 89–91why, one step back8990 .. 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.Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
lines 93–105why, one step back9394 .. attribute:: status9596 A string with a response status.9798 .. attribute:: status_code99100 The response status as integer.101102103Sessions104--------105Merge pull request #2399 from davidism/docs-secret-keyDavid Lordbefore adoptiond13e41d
lines 106–111why, one step back106If you have set :attr:`Flask.secret_key` (or configured it from107:data:`SECRET_KEY`) you can use sessions in Flask applications. A session makes108it possible to remember information from one request to another. The way Flask109does this is by using a signed cookie. The user can look at the session110contents, but can't modify it unless they know the secret key, so make sure to111set that to something complex and unguessable.Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
lines 112–125why, one step back112113To 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.Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
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 advisedRemoved ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
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::Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
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 forRemoved ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
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) theRemoved ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
lines 146–214why, 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.. admonition:: Notice175176 The ``PERMANENT_SESSION_LIFETIME`` config key can also be an integer177 starting with Flask 0.8. Either catch this down yourself or use178 the :attr:`~flask.Flask.permanent_session_lifetime` attribute on the179 app which converts the result to an integer automatically.180181182Test Client183-----------184185.. currentmodule:: flask.testing186187.. autoclass:: FlaskClient188 :members:189190191Application Globals192-------------------193194.. currentmodule:: flask195196To share data that is valid for one request only from one function to197another, a global variable is not good enough because it would break in198threaded environments. Flask provides you with a special object that199ensures it is only valid for the active request and that will return200different values for each request. In a nutshell: it does the right201thing, like it does for :class:`request` and :class:`session`.202203.. data:: g204205 Just store on this whatever you want. For example a database206 connection or the user that is currently logged in.207208 Starting with Flask 0.10 this is stored on the application context and209 no longer on the request context which means it becomes available if210 only the application context is bound and not yet a request. This211 is especially useful when combined with the :ref:`faking-resources`212 pattern for testing.213214 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 215why, one step back215 get an attribute or ``None`` (or the second argument) if it's not set.Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
lines 216–223why, one step back216 These two usages are now equivalent::217218 user = getattr(flask.g, 'user', None)219 user = flask.g.get('user', None)220221 It's now also possible to use the ``in`` operator on it to see if an222 attribute is defined and it yields all keys on iteration.223resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 224–226why, one step back224 As of 0.11 you can use :meth:`pop` and :meth:`setdefault` in the same225 way you would use them on a dictionary.226Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
lines 227–250why, one step back227 This is a proxy. See :ref:`notes-on-proxies` for more information.228229230Useful Functions and Classes231----------------------------232233.. data:: current_app234235 Points to the application handling the request. This is useful for236 extensions that want to support multiple applications running side237 by side. This is powered by the application context and not by the238 request context, so you can change the value of this proxy by239 using the :meth:`~flask.Flask.app_context` method.240241 This is a proxy. See :ref:`notes-on-proxies` for more information.242243.. autofunction:: has_request_context244245.. autofunction:: copy_current_request_context246247.. autofunction:: has_app_context248249.. autofunction:: url_for250resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 251why, one step back251.. autofunction:: abortRemoved ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
lines 252–282why, one step back252253.. autofunction:: redirect254255.. autofunction:: make_response256257.. autofunction:: after_this_request258259.. autofunction:: send_file260261.. autofunction:: send_from_directory262263.. autofunction:: safe_join264265.. autofunction:: escape266267.. autoclass:: Markup268 :members: escape, unescape, striptags269270Message Flashing271----------------272273.. autofunction:: flash274275.. autofunction:: get_flashed_messages276277JSON Support278------------279280.. module:: flask.json281282Flask uses ``simplejson`` for the JSON implementation. Since simplejsonMerge pull request #1273 from prakashpp/patch-1Markus Unterwaditzerbefore adoption41b5d77
line 283why, one step back283is provided by both the standard library as well as extension, Flask willRemoved ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
lines 284–308why, one step back284try simplejson first and then fall back to the stdlib json module. On top285of that it will delegate access to the current application's JSON encoders286and decoders for easier customization.287288So for starters instead of doing::289290 try:291 import simplejson as json292 except ImportError:293 import json294295You can instead just do this::296297 from flask import json298299For usage examples, read the :mod:`json` documentation in the standard300library. The following extensions are by default applied to the stdlib's301JSON module:3023031. ``datetime`` objects are serialized as :rfc:`822` strings.3042. Any object with an ``__html__`` method (like :class:`~flask.Markup`)305 will have that method called and then the return value is serialized306 as string.307308The :func:`~htmlsafe_dumps` function of this json module is also availableMerge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 309why, one step back309as filter called ``|tojson`` in Jinja2. Note that inside ``script``Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
line 310why, one step back310tags no escaping must take place, so make sure to disable escapingMerge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 311why, one step back311with ``|safe`` if you intend to use it inside ``script`` tags unlessRemoved ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
lines 312–343why, one step back312you are using Flask 0.10 which implies that:313314.. sourcecode:: html+jinja315316 <script type=text/javascript>317 doSomethingWith({{ user.username|tojson|safe }});318 </script>319320.. admonition:: Auto-Sort JSON Keys321322 The configuration variable ``JSON_SORT_KEYS`` (:ref:`config`) can be323 set to false to stop Flask from auto-sorting keys. By default sorting324 is enabled and outside of the app context sorting is turned on.325326 Notice that disabling key sorting can cause issues when using content327 based HTTP caches and Python's hash randomization feature.328329.. autofunction:: jsonify330331.. autofunction:: dumps332333.. autofunction:: dump334335.. autofunction:: loads336337.. autofunction:: load338339.. autoclass:: JSONEncoder340 :members:341342.. autoclass:: JSONDecoder343 :members:Merge pull request #2352 from davidism/json-object-hookDavid Lordbefore adoption62406e6
lines 344–345why, one step back344345.. automodule:: flask.json.tagRemoved ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
lines 346–441why, one step back346347Template Rendering348------------------349350.. currentmodule:: flask351352.. autofunction:: render_template353354.. autofunction:: render_template_string355356.. autofunction:: get_template_attribute357358Configuration359-------------360361.. autoclass:: Config362 :members:363364Extensions365----------366367.. data:: flask.ext368369 This module acts as redirect import module to Flask extensions. It was370 added in 0.8 as the canonical way to import Flask extensions and makes371 it possible for us to have more flexibility in how we distribute372 extensions.373374 If you want to use an extension named “Flask-Foo” you would import it375 from :data:`~flask.ext` as follows::376377 from flask.ext import foo378379 .. versionadded:: 0.8380381Stream Helpers382--------------383384.. autofunction:: stream_with_context385386Useful Internals387----------------388389.. autoclass:: flask.ctx.RequestContext390 :members:391392.. data:: _request_ctx_stack393394 The internal :class:`~werkzeug.local.LocalStack` that is used to implement395 all the context local objects used in Flask. This is a documented396 instance and can be used by extensions and application code but the397 use is discouraged in general.398399 The following attributes are always present on each layer of the400 stack:401402 `app`403 the active Flask application.404405 `url_adapter`406 the URL adapter that was used to match the request.407408 `request`409 the current request object.410411 `session`412 the active session object.413414 `g`415 an object with all the attributes of the :data:`flask.g` object.416417 `flashes`418 an internal cache for the flashed messages.419420 Example usage::421422 from flask import _request_ctx_stack423424 def get_session():425 ctx = _request_ctx_stack.top426 if ctx is not None:427 return ctx.session428429.. autoclass:: flask.ctx.AppContext430 :members:431432.. data:: _app_ctx_stack433434 Works similar to the request context but only binds the application.435 This is mainly there for extensions to store data.436437 .. versionadded:: 0.9438439.. autoclass:: flask.blueprints.BlueprintSetupState440 :members:441resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 442–443why, one step back442.. _core-signals-list:443Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
lines 444–448why, one step back444Signals445-------446447.. versionadded:: 0.6448resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 449why, one step back449.. data:: signals.signals_availableRemoved ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
line 450why, one step back450Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 451why, one step back451 ``True`` if the signaling system is available. This is the caseRemoved ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
lines 452–453why, one step back452 when `blinker`_ is installed.453resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 454–455why, one step back454The following signals exist in Flask:455Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
lines 456–461why, one step back456.. data:: template_rendered457458 This signal is sent when a template was successfully rendered. The459 signal is invoked with the instance of the template as `template`460 and the context as dictionary (named `context`).461resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 462–488why, one step back462 Example subscriber::463464 def log_template_renders(sender, template, context, **extra):465 sender.logger.debug('Rendering template "%s" with context %s',466 template.name or 'string template',467 context)468469 from flask import template_rendered470 template_rendered.connect(log_template_renders, app)471472.. data:: flask.before_render_template473 :noindex:474475 This signal is sent before template rendering process. The476 signal is invoked with the instance of the template as `template`477 and the context as dictionary (named `context`).478479 Example subscriber::480481 def log_template_renders(sender, template, context, **extra):482 sender.logger.debug('Rendering template "%s" with context %s',483 template.name or 'string template',484 context)485486 from flask import before_render_template487 before_render_template.connect(log_template_renders, app)488Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
lines 489–490why, one step back489.. data:: request_started490resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 491–492why, one step back491 This signal is sent when the request context is set up, before492 any request processing happens. Because the request context is alreadyRemoved ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
lines 493–495why, one step back493 bound, the subscriber can access the request with the standard global494 proxies such as :class:`~flask.request`.495resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 496–503why, one step back496 Example subscriber::497498 def log_request(sender, **extra):499 sender.logger.debug('Request context is set up')500501 from flask import request_started502 request_started.connect(log_request, app)503Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
lines 504–508why, one step back504.. data:: request_finished505506 This signal is sent right before the response is sent to the client.507 It is passed the response to be sent named `response`.508resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 509–517why, one step back509 Example subscriber::510511 def log_response(sender, response, **extra):512 sender.logger.debug('Request context is about to close down. '513 'Response: %s', response)514515 from flask import request_finished516 request_finished.connect(log_response, app)517Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
lines 518–524why, one step back518.. data:: got_request_exception519520 This signal is sent when an exception happens during request processing.521 It is sent *before* the standard exception handling kicks in and even522 in debug mode, where no exception handling happens. The exception523 itself is passed to the subscriber as `exception`.524resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 525–532why, one step back525 Example subscriber::526527 def log_exception(sender, exception, **extra):528 sender.logger.debug('Got exception during processing: %s', exception)529530 from flask import got_request_exception531 got_request_exception.connect(log_exception, app)532Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
lines 533–534why, one step back533.. data:: request_tearing_down534resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 535–538why, one step back535 This signal is sent when the request is tearing down. This is always536 called, even if an exception is caused. Currently functions listening537 to this signal are called after the regular teardown handlers, but this538 is not something you can rely on.Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
line 539why, one step back539resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 540why, one step back540 Example subscriber::Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
line 541why, one step back541resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 542–551why, one step back542 def close_db_connection(sender, **extra):543 session.close()544545 from flask import request_tearing_down546 request_tearing_down.connect(close_db_connection, app)547548 As of Flask 0.9, this will also be passed an `exc` keyword argument549 that has a reference to the exception that caused the teardown if550 there was one.551Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
lines 552–553why, one step back552.. data:: appcontext_tearing_down553resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 554–557why, one step back554 This signal is sent when the app context is tearing down. This is always555 called, even if an exception is caused. Currently functions listening556 to this signal are called after the regular teardown handlers, but this557 is not something you can rely on.Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
line 558why, one step back558resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 559–569why, one step back559 Example subscriber::560561 def close_db_connection(sender, **extra):562 session.close()563564 from flask import appcontext_tearing_down565 appcontext_tearing_down.connect(close_db_connection, app)566567 This will also be passed an `exc` keyword argument that has a reference568 to the exception that caused the teardown if there was one.569Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
lines 570–572why, one step back570.. data:: appcontext_pushed571572 This signal is sent when an application context is pushed. The senderresolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 573–575why, one step back573 is the application. This is usually useful for unittests in order to574 temporarily hook in information. For instance it can be used to575 set a resource early onto the `g` object.Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
line 576why, one step back576resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 577–596why, one step back577 Example usage::578579 from contextlib import contextmanager580 from flask import appcontext_pushed581582 @contextmanager583 def user_set(app, user):584 def handler(sender, **kwargs):585 g.user = user586 with appcontext_pushed.connected_to(handler, app):587 yield588589 And in the testcode::590591 def test_user_me(self):592 with user_set(app, 'john'):593 c = app.test_client()594 resp = c.get('/users/me')595 assert resp.data == 'username=john'596Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
lines 597–606why, one step back597 .. versionadded:: 0.10598599.. data:: appcontext_popped600601 This signal is sent when an application context is popped. The sender602 is the application. This usually falls in line with the603 :data:`appcontext_tearing_down` signal.604605 .. versionadded:: 0.10606resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 607why, one step back607Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
lines 608–613why, one step back608.. data:: message_flashed609610 This signal is sent when the application is flashing a message. The611 messages is sent as `message` keyword argument and the category as612 `category`.613resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 614why, one step back614 Example subscriber::Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
line 615why, one step back615resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 616–618why, one step back616 recorded = []617 def record(sender, message, category, **extra):618 recorded.append((message, category))Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
line 619why, one step back619resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 620–621why, one step back620 from flask import message_flashed621 message_flashed.connect(record, app)Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
line 622why, one step back622resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 623–626why, one step back623 .. versionadded:: 0.10624625.. class:: signals.Namespace626Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
lines 627–638why, one step back627 An alias for :class:`blinker.base.Namespace` if blinker is available,628 otherwise a dummy class that creates fake signals. This class is629 available for Flask extensions that want to provide the same fallback630 system as Flask itself.631632 .. method:: signal(name, doc=None)633634 Creates a new signal for this namespace if blinker is available,635 otherwise returns a fake signal that has a send method that will636 do nothing but will fail with a :exc:`RuntimeError` for all other637 operations, including connecting.638resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 639why, one step back639Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
lines 640–641why, one step back640.. _blinker: https://pypi.python.org/pypi/blinker641Merge pull request #2370 from tony/patch-2David Lordbefore adoptione97f6e2
line 642why, one step back642.. _class-based-views:resolve merge conflictsKenneth Reitzbefore adoption31174fe
line 643why, one step back643Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
lines 644–682why, one step back644Class-Based Views645-----------------646647.. versionadded:: 0.7648649.. currentmodule:: None650651.. autoclass:: flask.views.View652 :members:653654.. autoclass:: flask.views.MethodView655 :members:656657.. _url-route-registrations:658659URL Route Registrations660-----------------------661662Generally there are three ways to define rules for the routing system:6636641. You can use the :meth:`flask.Flask.route` decorator.6652. You can use the :meth:`flask.Flask.add_url_rule` function.6663. You can directly access the underlying Werkzeug routing system667 which is exposed as :attr:`flask.Flask.url_map`.668669Variable parts in the route can be specified with angular brackets670(``/user/<username>``). By default a variable part in the URL accepts any671string without a slash however a different converter can be specified as672well by using ``<converter:name>``.673674Variable parts are passed to the view function as keyword arguments.675676The following converters are available:677678=========== ===============================================679`string` accepts any text without a slash (the default)680`int` accepts integers681`float` like `int` but for floating point values682`path` like the default but also accepts slashesresolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 683–684why, one step back683`any` matches one of the items provided684`uuid` accepts UUID stringsRemoved ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
lines 685–686why, one step back685=========== ===============================================686Merge pull request #1448 from fordhurley/custom_convertersMarkus Unterwaditzerbefore adoption73c8335
lines 687–688why, one step back687Custom converters can be defined using :attr:`flask.Flask.url_map`.688Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
lines 689–750why, one step back689Here are some examples::690691 @app.route('/')692 def index():693 pass694695 @app.route('/<username>')696 def show_user(username):697 pass698699 @app.route('/post/<int:post_id>')700 def show_post(post_id):701 pass702703An important detail to keep in mind is how Flask deals with trailing704slashes. The idea is to keep each URL unique so the following rules705apply:7067071. If a rule ends with a slash and is requested without a slash by the708 user, the user is automatically redirected to the same page with a709 trailing slash attached.7102. If a rule does not end with a trailing slash and the user requests the711 page with a trailing slash, a 404 not found is raised.712713This is consistent with how web servers deal with static files. This714also makes it possible to use relative link targets safely.715716You can also define multiple rules for the same function. They have to be717unique however. Defaults can also be specified. Here for example is a718definition for a URL that accepts an optional page::719720 @app.route('/users/', defaults={'page': 1})721 @app.route('/users/page/<int:page>')722 def show_users(page):723 pass724725This specifies that ``/users/`` will be the URL for page one and726``/users/page/N`` will be the URL for page `N`.727728Here are the parameters that :meth:`~flask.Flask.route` and729:meth:`~flask.Flask.add_url_rule` accept. The only difference is that730with the route parameter the view function is defined with the decorator731instead of the `view_func` parameter.732733=============== ==========================================================734`rule` the URL rule as string735`endpoint` the endpoint for the registered URL rule. Flask itself736 assumes that the name of the view function is the name737 of the endpoint if not explicitly stated.738`view_func` the function to call when serving a request to the739 provided endpoint. If this is not provided one can740 specify the function later by storing it in the741 :attr:`~flask.Flask.view_functions` dictionary with the742 endpoint as key.743`defaults` A dictionary with defaults for this rule. See the744 example above for how defaults work.745`subdomain` specifies the rule for the subdomain in case subdomain746 matching is in use. If not specified the default747 subdomain is assumed.748`**options` the options to be forwarded to the underlying749 :class:`~werkzeug.routing.Rule` object. A change to750 Werkzeug is handling of method options. methods is a listMerge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
lines 751–753why, one step back751 of methods this rule should be limited to (``GET``, ``POST``752 etc.). By default a rule just listens for ``GET`` (and753 implicitly ``HEAD``). Starting with Flask 0.6, ``OPTIONS`` isRemoved ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
lines 754–773why, one step back754 implicitly added and handled by the standard request755 handling. They have to be specified as keyword arguments.756=============== ==========================================================757758.. _view-func-options:759760View Function Options761---------------------762763For internal usage the view functions can have some attributes attached to764customize behavior the view function would normally not have control over.765The following attributes can be provided optionally to either override766some defaults to :meth:`~flask.Flask.add_url_rule` or general behavior:767768- `__name__`: The name of a function is by default used as endpoint. If769 endpoint is provided explicitly this value is used. Additionally this770 will be prefixed with the name of the blueprint by default which771 cannot be customized from the function itself.772773- `methods`: If methods are not provided when the URL rule is added,Merge pull request #1269 from pkuphy/patch-2Markus Unterwaditzerbefore adoption3bf9c2e
line 774why, one step back774 Flask will look on the view function object itself if a `methods`Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
lines 775–779why, one step back775 attribute exists. If it does, it will pull the information for the776 methods from there.777778- `provide_automatic_options`: if this attribute is set Flask will779 either force enable or disable the automatic implementation of theMerge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
lines 780–781why, one step back780 HTTP ``OPTIONS`` response. This can be useful when working with781 decorators that want to customize the ``OPTIONS`` response on a per-viewRemoved ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
lines 782–816why, one step back782 basis.783784- `required_methods`: if this attribute is set, Flask will always add785 these methods when registering a URL rule even if the methods were786 explicitly overridden in the ``route()`` call.787788Full example::789790 def index():791 if request.method == 'OPTIONS':792 # custom options handling here793 ...794 return 'Hello World!'795 index.provide_automatic_options = False796 index.methods = ['GET', 'OPTIONS']797798 app.add_url_rule('/', index)799800.. versionadded:: 0.8801 The `provide_automatic_options` functionality was added.802803Command Line Interface804----------------------805806.. currentmodule:: flask.cli807808.. autoclass:: FlaskGroup809 :members:810811.. autoclass:: AppGroup812 :members:813814.. autoclass:: ScriptInfo815 :members:816Merge pull request #2416 from davidism/dotenvDavid Lordbefore adoption851eaa4
lines 817–818why, one step back817.. autofunction:: load_dotenv818Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
lines 819–821why, one step back819.. autofunction:: with_appcontext820821.. autofunction:: pass_script_infoMerge pull request #1161 from pbu88/masterMarkus Unterwaditzerbefore adoption96d7cc9
line 822why, one step back822Removed ridiculous constructor from AppGroupArmin Ronacherbefore adoption2f60124
lines 823–828why, one step back823 Marks a function so that an instance of :class:`ScriptInfo` is passed824 as first argument to the click callback.825826.. autodata:: run_command827828.. autodata:: shell_command