Skip to content
Myr

api.rst

This file

Path

docs/api.rst

789 lines · 23.7 KiB

Last changed by

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

History of this file

Take it

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:: form3536      A :class:`~werkzeug.datastructures.MultiDict` with the parsed form data from ``POST``37      or ``PUT`` requests.  Please keep in mind that file uploads will not38      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 a74      ``POST`` or ``PUT`` request.  Each file is stored as75      :class:`~werkzeug.datastructures.FileStorage` object.  It basically behaves like a76      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:: path89   .. attribute:: full_path90   .. attribute:: script_root91   .. attribute:: url92   .. attribute:: base_url93   .. attribute:: url_root9495      Provides different ways to look at the current URL.  Imagine your96      application is listening on the following URL::9798          http://www.example.com/myapplication99100      And a user requests the following URL::101102          http://www.example.com/myapplication/page.html?x=y103104      In this case the values of the above mentioned attributes would be105      the following:106107      ============= ======================================================108      `path`        ``/page.html``109      `full_path`   ``/page.html?x=y``110      `script_root` ``/myapplication``111      `base_url`    ``http://www.example.com/myapplication/page.html``112      `url`         ``http://www.example.com/myapplication/page.html?x=y``113      `url_root`    ``http://www.example.com/myapplication/``114      ============= ======================================================115116   .. attribute:: is_xhr117118      ``True`` if the request was triggered via a JavaScript119      `XMLHttpRequest`. This only works with libraries that support the120      ``X-Requested-With`` header and set it to `XMLHttpRequest`.121      Libraries that do that are prototype, jQuery and Mochikit and122      probably some more.123124.. class:: request125126   To access incoming request data, you can use the global `request`127   object.  Flask parses incoming request data for you and gives you128   access to it through that global object.  Internally Flask makes129   sure that you always get the correct data for the active thread if you130   are in a multithreaded environment.131132   This is a proxy.  See :ref:`notes-on-proxies` for more information.133134   The request object is an instance of a :class:`~werkzeug.wrappers.Request`135   subclass and provides all of the attributes Werkzeug defines.  This136   just shows a quick overview of the most important ones.137138139Response Objects140----------------141142.. autoclass:: flask.Response143   :members: set_cookie, data, mimetype144145   .. attribute:: headers146147      A :class:`~werkzeug.datastructures.Headers` object representing the response headers.148149   .. attribute:: status150151      A string with a response status.152153   .. attribute:: status_code154155      The response status as integer.156157158Sessions159--------160161If you have the :attr:`Flask.secret_key` set you can use sessions in Flask162applications.  A session basically makes it possible to remember163information from one request to another.  The way Flask does this is by164using a signed cookie.  So the user can look at the session contents, but165not modify it unless they know the secret key, so make sure to set that166to something complex and unguessable.167168To access the current session you can use the :class:`session` object:169170.. class:: session171172   The session object works pretty much like an ordinary dict, with the173   difference that it keeps track on modifications.174175   This is a proxy.  See :ref:`notes-on-proxies` for more information.176177   The following attributes are interesting:178179   .. attribute:: new180181      ``True`` if the session is new, ``False`` otherwise.182183   .. attribute:: modified184185      ``True`` if the session object detected a modification.  Be advised186      that modifications on mutable structures are not picked up187      automatically, in that situation you have to explicitly set the188      attribute to ``True`` yourself.  Here an example::189190          # this change is not picked up because a mutable object (here191          # a list) is changed.192          session['objects'].append(42)193          # so mark it as modified yourself194          session.modified = True195196   .. attribute:: permanent197198      If set to ``True`` the session lives for199      :attr:`~flask.Flask.permanent_session_lifetime` seconds.  The200      default is 31 days.  If set to ``False`` (which is the default) the201      session will be deleted when the user closes the browser.202203204Session Interface205-----------------206207.. versionadded:: 0.8208209The session interface provides a simple way to replace the session210implementation that Flask is using.211212.. currentmodule:: flask.sessions213214.. autoclass:: SessionInterface215   :members:216217.. autoclass:: SecureCookieSessionInterface218   :members:219220.. autoclass:: SecureCookieSession221   :members:222223.. autoclass:: NullSession224   :members:225226.. autoclass:: SessionMixin227   :members:228229.. autodata:: session_json_serializer230231   This object provides dumping and loading methods similar to simplejson232   but it also tags certain builtin Python objects that commonly appear in233   sessions.  Currently the following extended values are supported in234   the JSON it dumps:235236   -    :class:`~markupsafe.Markup` objects237   -    :class:`~uuid.UUID` objects238   -    :class:`~datetime.datetime` objects239   -   :class:`tuple`\s240241.. admonition:: Notice242243   The ``PERMANENT_SESSION_LIFETIME`` config key can also be an integer244   starting with Flask 0.8.  Either catch this down yourself or use245   the :attr:`~flask.Flask.permanent_session_lifetime` attribute on the246   app which converts the result to an integer automatically.247248249Test Client250-----------251252.. currentmodule:: flask.testing253254.. autoclass:: FlaskClient255   :members:256257258Application Globals259-------------------260261.. currentmodule:: flask262263To share data that is valid for one request only from one function to264another, a global variable is not good enough because it would break in265threaded environments.  Flask provides you with a special object that266ensures it is only valid for the active request and that will return267different values for each request.  In a nutshell: it does the right268thing, like it does for :class:`request` and :class:`session`.269270.. data:: g271272   Just store on this whatever you want.  For example a database273   connection or the user that is currently logged in.274275   Starting with Flask 0.10 this is stored on the application context and276   no longer on the request context which means it becomes available if277   only the application context is bound and not yet a request.  This278   is especially useful when combined with the :ref:`faking-resources`279   pattern for testing.280281   Additionally as of 0.10 you can use the :meth:`get` method to282   get an attribute or ``None`` (or the second argument) if it's not set.283   These two usages are now equivalent::284285        user = getattr(flask.g, 'user', None)286        user = flask.g.get('user', None)287288   It's now also possible to use the ``in`` operator on it to see if an289   attribute is defined and it yields all keys on iteration.290291   This is a proxy.  See :ref:`notes-on-proxies` for more information.292293294Useful Functions and Classes295----------------------------296297.. data:: current_app298299   Points to the application handling the request.  This is useful for300   extensions that want to support multiple applications running side301   by side.  This is powered by the application context and not by the302   request context, so you can change the value of this proxy by303   using the :meth:`~flask.Flask.app_context` method.304305   This is a proxy.  See :ref:`notes-on-proxies` for more information.306307.. autofunction:: has_request_context308309.. autofunction:: copy_current_request_context310311.. autofunction:: has_app_context312313.. autofunction:: url_for314315.. function:: abort(code)316317   Raises an :exc:`~werkzeug.exceptions.HTTPException` for the given318   status code.  For example to abort request handling with a page not319   found exception, you would call ``abort(404)``.320321   :param code: the HTTP error code.322323.. autofunction:: redirect324325.. autofunction:: make_response326327.. autofunction:: after_this_request328329.. autofunction:: send_file330331.. autofunction:: send_from_directory332333.. autofunction:: safe_join334335.. autofunction:: escape336337.. autoclass:: Markup338   :members: escape, unescape, striptags339340Message Flashing341----------------342343.. autofunction:: flash344345.. autofunction:: get_flashed_messages346347JSON Support348------------349350.. module:: flask.json351352Flask uses ``simplejson`` for the JSON implementation.  Since simplejson353is provided by both the standard library as well as extension, Flask will354try simplejson first and then fall back to the stdlib json module.  On top355of that it will delegate access to the current application's JSON encoders356and decoders for easier customization.357358So for starters instead of doing::359360    try:361        import simplejson as json362    except ImportError:363        import json364365You can instead just do this::366367    from flask import json368369For usage examples, read the :mod:`json` documentation in the standard370library.  The following extensions are by default applied to the stdlib's371JSON module:3723731.  ``datetime`` objects are serialized as :rfc:`822` strings.3742.  Any object with an ``__html__`` method (like :class:`~flask.Markup`)375    will have that method called and then the return value is serialized376    as string.377378The :func:`~htmlsafe_dumps` function of this json module is also available379as filter called ``|tojson`` in Jinja2.  Note that inside ``script``380tags no escaping must take place, so make sure to disable escaping381with ``|safe`` if you intend to use it inside ``script`` tags unless382you are using Flask 0.10 which implies that:383384.. sourcecode:: html+jinja385386    <script type=text/javascript>387        doSomethingWith({{ user.username|tojson|safe }});388    </script>389390.. admonition:: Auto-Sort JSON Keys391392    The configuration variable ``JSON_SORT_KEYS`` (:ref:`config`) can be393    set to false to stop Flask from auto-sorting keys.  By default sorting394    is enabled and outside of the app context sorting is turned on.395396    Notice that disabling key sorting can cause issues when using content397    based HTTP caches and Python's hash randomization feature.398399.. autofunction:: jsonify400401.. autofunction:: dumps402403.. autofunction:: dump404405.. autofunction:: loads406407.. autofunction:: load408409.. autoclass:: JSONEncoder410   :members:411412.. autoclass:: JSONDecoder413   :members:414415Template Rendering416------------------417418.. currentmodule:: flask419420.. autofunction:: render_template421422.. autofunction:: render_template_string423424.. autofunction:: get_template_attribute425426Configuration427-------------428429.. autoclass:: Config430   :members:431432Extensions433----------434435.. data:: flask.ext436437   This module acts as redirect import module to Flask extensions.  It was438   added in 0.8 as the canonical way to import Flask extensions and makes439   it possible for us to have more flexibility in how we distribute440   extensions.441442   If you want to use an extension named “Flask-Foo” you would import it443   from :data:`~flask.ext` as follows::444445        from flask.ext import foo446447   .. versionadded:: 0.8448449Stream Helpers450--------------451452.. autofunction:: stream_with_context453454Useful Internals455----------------456457.. autoclass:: flask.ctx.RequestContext458   :members:459460.. data:: _request_ctx_stack461462   The internal :class:`~werkzeug.local.LocalStack` that is used to implement463   all the context local objects used in Flask.  This is a documented464   instance and can be used by extensions and application code but the465   use is discouraged in general.466467   The following attributes are always present on each layer of the468   stack:469470   `app`471      the active Flask application.472473   `url_adapter`474      the URL adapter that was used to match the request.475476   `request`477      the current request object.478479   `session`480      the active session object.481482   `g`483      an object with all the attributes of the :data:`flask.g` object.484485   `flashes`486      an internal cache for the flashed messages.487488   Example usage::489490      from flask import _request_ctx_stack491492      def get_session():493          ctx = _request_ctx_stack.top494          if ctx is not None:495              return ctx.session496497.. autoclass:: flask.ctx.AppContext498   :members:499500.. data:: _app_ctx_stack501502   Works similar to the request context but only binds the application.503   This is mainly there for extensions to store data.504505   .. versionadded:: 0.9506507.. autoclass:: flask.blueprints.BlueprintSetupState508   :members:509510Signals511-------512513.. when modifying this list, also update the one in signals.rst514515.. versionadded:: 0.6516517.. data:: signals_available518519   ``True`` if the signaling system is available.  This is the case520   when `blinker`_ is installed.521522.. data:: template_rendered523524   This signal is sent when a template was successfully rendered.  The525   signal is invoked with the instance of the template as `template`526   and the context as dictionary (named `context`).527528.. data:: request_started529530   This signal is sent before any request processing started but when the531   request context was set up.  Because the request context is already532   bound, the subscriber can access the request with the standard global533   proxies such as :class:`~flask.request`.534535.. data:: request_finished536537   This signal is sent right before the response is sent to the client.538   It is passed the response to be sent named `response`.539540.. data:: got_request_exception541542   This signal is sent when an exception happens during request processing.543   It is sent *before* the standard exception handling kicks in and even544   in debug mode, where no exception handling happens.  The exception545   itself is passed to the subscriber as `exception`.546547.. data:: request_tearing_down548549   This signal is sent when the application is tearing down the request.550   This is always called, even if an error happened.  An `exc` keyword551   argument is passed with the exception that caused the teardown.552553   .. versionchanged:: 0.9554      The `exc` parameter was added.555556.. data:: appcontext_tearing_down557558   This signal is sent when the application is tearing down the559   application context.  This is always called, even if an error happened.560   An `exc` keyword argument is passed with the exception that caused the561   teardown.  The sender is the application.562563.. data:: appcontext_pushed564565   This signal is sent when an application context is pushed.  The sender566   is the application.567568   .. versionadded:: 0.10569570.. data:: appcontext_popped571572   This signal is sent when an application context is popped.  The sender573   is the application.  This usually falls in line with the574   :data:`appcontext_tearing_down` signal.575576   .. versionadded:: 0.10577578.. data:: message_flashed579580   This signal is sent when the application is flashing a message.  The581   messages is sent as `message` keyword argument and the category as582   `category`.583584   .. versionadded:: 0.10585586.. currentmodule:: None587588.. class:: flask.signals.Namespace589590   An alias for :class:`blinker.base.Namespace` if blinker is available,591   otherwise a dummy class that creates fake signals.  This class is592   available for Flask extensions that want to provide the same fallback593   system as Flask itself.594595   .. method:: signal(name, doc=None)596597      Creates a new signal for this namespace if blinker is available,598      otherwise returns a fake signal that has a send method that will599      do nothing but will fail with a :exc:`RuntimeError` for all other600      operations, including connecting.601602.. _blinker: https://pypi.python.org/pypi/blinker603604Class-Based Views605-----------------606607.. versionadded:: 0.7608609.. currentmodule:: None610611.. autoclass:: flask.views.View612   :members:613614.. autoclass:: flask.views.MethodView615   :members:616617.. _url-route-registrations:618619URL Route Registrations620-----------------------621622Generally there are three ways to define rules for the routing system:6236241.  You can use the :meth:`flask.Flask.route` decorator.6252.  You can use the :meth:`flask.Flask.add_url_rule` function.6263.  You can directly access the underlying Werkzeug routing system627    which is exposed as :attr:`flask.Flask.url_map`.628629Variable parts in the route can be specified with angular brackets630(``/user/<username>``).  By default a variable part in the URL accepts any631string without a slash however a different converter can be specified as632well by using ``<converter:name>``.633634Variable parts are passed to the view function as keyword arguments.635636The following converters are available:637638=========== ===============================================639`string`    accepts any text without a slash (the default)640`int`       accepts integers641`float`     like `int` but for floating point values642`path`      like the default but also accepts slashes643=========== ===============================================644645Here are some examples::646647    @app.route('/')648    def index():649        pass650651    @app.route('/<username>')652    def show_user(username):653        pass654655    @app.route('/post/<int:post_id>')656    def show_post(post_id):657        pass658659An important detail to keep in mind is how Flask deals with trailing660slashes.  The idea is to keep each URL unique so the following rules661apply:6626631. If a rule ends with a slash and is requested without a slash by the664   user, the user is automatically redirected to the same page with a665   trailing slash attached.6662. If a rule does not end with a trailing slash and the user requests the667   page with a trailing slash, a 404 not found is raised.668669This is consistent with how web servers deal with static files.  This670also makes it possible to use relative link targets safely.671672You can also define multiple rules for the same function.  They have to be673unique however.  Defaults can also be specified.  Here for example is a674definition for a URL that accepts an optional page::675676    @app.route('/users/', defaults={'page': 1})677    @app.route('/users/page/<int:page>')678    def show_users(page):679        pass680681This specifies that ``/users/`` will be the URL for page one and682``/users/page/N`` will be the URL for page `N`.683684Here are the parameters that :meth:`~flask.Flask.route` and685:meth:`~flask.Flask.add_url_rule` accept.  The only difference is that686with the route parameter the view function is defined with the decorator687instead of the `view_func` parameter.688689=============== ==========================================================690`rule`          the URL rule as string691`endpoint`      the endpoint for the registered URL rule.  Flask itself692                assumes that the name of the view function is the name693                of the endpoint if not explicitly stated.694`view_func`     the function to call when serving a request to the695                provided endpoint.  If this is not provided one can696                specify the function later by storing it in the697                :attr:`~flask.Flask.view_functions` dictionary with the698                endpoint as key.699`defaults`      A dictionary with defaults for this rule.  See the700                example above for how defaults work.701`subdomain`     specifies the rule for the subdomain in case subdomain702                matching is in use.  If not specified the default703                subdomain is assumed.704`**options`     the options to be forwarded to the underlying705                :class:`~werkzeug.routing.Rule` object.  A change to706                Werkzeug is handling of method options.  methods is a list707                of methods this rule should be limited to (``GET``, ``POST``708                etc.).  By default a rule just listens for ``GET`` (and709                implicitly ``HEAD``).  Starting with Flask 0.6, ``OPTIONS`` is710                implicitly added and handled by the standard request711                handling.  They have to be specified as keyword arguments.712=============== ==========================================================713714.. _view-func-options:715716View Function Options717---------------------718719For internal usage the view functions can have some attributes attached to720customize behavior the view function would normally not have control over.721The following attributes can be provided optionally to either override722some defaults to :meth:`~flask.Flask.add_url_rule` or general behavior:723724-   `__name__`: The name of a function is by default used as endpoint.  If725    endpoint is provided explicitly this value is used.  Additionally this726    will be prefixed with the name of the blueprint by default which727    cannot be customized from the function itself.728729-   `methods`: If methods are not provided when the URL rule is added,730    Flask will look on the view function object itself if a `methods`731    attribute exists.  If it does, it will pull the information for the732    methods from there.733734-   `provide_automatic_options`: if this attribute is set Flask will735    either force enable or disable the automatic implementation of the736    HTTP ``OPTIONS`` response.  This can be useful when working with737    decorators that want to customize the ``OPTIONS`` response on a per-view738    basis.739740-   `required_methods`: if this attribute is set, Flask will always add741    these methods when registering a URL rule even if the methods were742    explicitly overridden in the ``route()`` call.743744Full example::745746    def index():747        if request.method == 'OPTIONS':748            # custom options handling here749            ...750        return 'Hello World!'751    index.provide_automatic_options = False752    index.methods = ['GET', 'OPTIONS']753754    app.add_url_rule('/', index)755756.. versionadded:: 0.8757   The `provide_automatic_options` functionality was added.758759Command Line Interface760----------------------761762.. currentmodule:: flask.cli763764.. autoclass:: FlaskGroup765   :members:766767.. autoclass:: AppGroup768   :members:769770.. autoclass:: ScriptInfo771   :members:772773.. autofunction:: with_appcontext774775.. autofunction:: pass_script_info776777   Marks a function so that an instance of :class:`ScriptInfo` is passed778   as first argument to the click callback.779780.. autofunction:: script_info_option781782   A special decorator that informs a click callback to be passed the783   script info object as first argument.  This is normally not useful784   unless you implement very special commands like the run command which785   does not want the application to be loaded yet.786787.. autodata:: run_command788789.. autodata:: shell_command