Skip to content
Myr

api.rst

This file

Path

docs/api.rst

642 lines · 19.3 KiB

Last changed by

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

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:: script_root90   .. attribute:: url91   .. attribute:: base_url92   .. attribute:: url_root9394      Provides different ways to look at the current URL.  Imagine your95      application is listening on the following URL::9697          http://www.example.com/myapplication9899      And a user requests the following URL::100101          http://www.example.com/myapplication/page.html?x=y102103      In this case the values of the above mentioned attributes would be104      the following:105106      ============= ======================================================107      `path`        ``/page.html``108      `script_root` ``/myapplication``109      `base_url`    ``http://www.example.com/myapplication/page.html``110      `url`         ``http://www.example.com/myapplication/page.html?x=y``111      `url_root`    ``http://www.example.com/myapplication/``112      ============= ======================================================113114   .. attribute:: is_xhr115116      `True` if the request was triggered via a JavaScript117      `XMLHttpRequest`. This only works with libraries that support the118      ``X-Requested-With`` header and set it to `XMLHttpRequest`.119      Libraries that do that are prototype, jQuery and Mochikit and120      probably some more.121122.. class:: request123124   To access incoming request data, you can use the global `request`125   object.  Flask parses incoming request data for you and gives you126   access to it through that global object.  Internally Flask makes127   sure that you always get the correct data for the active thread if you128   are in a multithreaded environment.129130   This is a proxy.  See :ref:`notes-on-proxies` for more information.131132   The request object is an instance of a :class:`~werkzeug.wrappers.Request`133   subclass and provides all of the attributes Werkzeug defines.  This134   just shows a quick overview of the most important ones.135136137Response Objects138----------------139140.. autoclass:: flask.Response141   :members: set_cookie, data, mimetype142143   .. attribute:: headers144145      A :class:`Headers` object representing the response headers.146147   .. attribute:: status148149      A string with a response status.150151   .. attribute:: status_code152153      The response status as integer.154155156Sessions157--------158159If you have the :attr:`Flask.secret_key` set you can use sessions in Flask160applications.  A session basically makes it possible to remember161information from one request to another.  The way Flask does this is by162using a signed cookie.  So the user can look at the session contents, but163not modify it unless they know the secret key, so make sure to set that164to something complex and unguessable.165166To access the current session you can use the :class:`session` object:167168.. class:: session169170   The session object works pretty much like an ordinary dict, with the171   difference that it keeps track on modifications.172173   This is a proxy.  See :ref:`notes-on-proxies` for more information.174175   The following attributes are interesting:176177   .. attribute:: new178179      `True` if the session is new, `False` otherwise.180181   .. attribute:: modified182183      `True` if the session object detected a modification.  Be advised184      that modifications on mutable structures are not picked up185      automatically, in that situation you have to explicitly set the186      attribute to `True` yourself.  Here an example::187188          # this change is not picked up because a mutable object (here189          # a list) is changed.190          session['objects'].append(42)191          # so mark it as modified yourself192          session.modified = True193194   .. attribute:: permanent195196      If set to `True` the session lives for197      :attr:`~flask.Flask.permanent_session_lifetime` seconds.  The198      default is 31 days.  If set to `False` (which is the default) the199      session will be deleted when the user closes the browser.200201202Session Interface203-----------------204205.. versionadded:: 0.8206207The session interface provides a simple way to replace the session208implementation that Flask is using.209210.. currentmodule:: flask.sessions211212.. autoclass:: SessionInterface213   :members:214215.. autoclass:: SecureCookieSessionInterface216   :members:217218.. autoclass:: NullSession219   :members:220221.. autoclass:: SessionMixin222   :members:223224.. admonition:: Notice225226   The ``PERMANENT_SESSION_LIFETIME`` config key can also be an integer227   starting with Flask 0.8.  Either catch this down yourself or use228   the :attr:`~flask.Flask.permanent_session_lifetime` attribute on the229   app which converts the result to an integer automatically.230231232Test Client233-----------234235.. currentmodule:: flask.testing236237.. autoclass:: FlaskClient238   :members:239240241Application Globals242-------------------243244.. currentmodule:: flask245246To share data that is valid for one request only from one function to247another, a global variable is not good enough because it would break in248threaded environments.  Flask provides you with a special object that249ensures it is only valid for the active request and that will return250different values for each request.  In a nutshell: it does the right251thing, like it does for :class:`request` and :class:`session`.252253.. data:: g254255   Just store on this whatever you want.  For example a database256   connection or the user that is currently logged in.257258   This is a proxy.  See :ref:`notes-on-proxies` for more information.259260261Useful Functions and Classes262----------------------------263264.. data:: current_app265266   Points to the application handling the request.  This is useful for267   extensions that want to support multiple applications running side268   by side.  This is powered by the application context and not by the269   request context, so you can change the value of this proxy by270   using the :meth:`~flask.Flask.app_context` method.271272   This is a proxy.  See :ref:`notes-on-proxies` for more information.273274.. autofunction:: has_request_context275276.. autofunction:: has_app_context277278.. autofunction:: url_for279280.. function:: abort(code)281282   Raises an :exc:`~werkzeug.exceptions.HTTPException` for the given283   status code.  For example to abort request handling with a page not284   found exception, you would call ``abort(404)``.285286   :param code: the HTTP error code.287288.. autofunction:: redirect289290.. autofunction:: make_response291292.. autofunction:: send_file293294.. autofunction:: send_from_directory295296.. autofunction:: safe_join297298.. autofunction:: escape299300.. autoclass:: Markup301   :members: escape, unescape, striptags302303Message Flashing304----------------305306.. autofunction:: flash307308.. autofunction:: get_flashed_messages309310Returning JSON311--------------312313.. autofunction:: jsonify314315.. data:: json316317    If JSON support is picked up, this will be the module that Flask is318    using to parse and serialize JSON.  So instead of doing this yourself::319320        try:321            import simplejson as json322        except ImportError:323            import json324325    You can instead just do this::326327        from flask import json328329    For usage examples, read the :mod:`json` documentation.330331    The :func:`~json.dumps` function of this json module is also available332    as filter called ``|tojson`` in Jinja2.  Note that inside `script`333    tags no escaping must take place, so make sure to disable escaping334    with ``|safe`` if you intend to use it inside `script` tags:335336    .. sourcecode:: html+jinja337338        <script type=text/javascript>339            doSomethingWith({{ user.username|tojson|safe }});340        </script>341342    Note that the ``|tojson`` filter escapes forward slashes properly.343344Template Rendering345------------------346347.. autofunction:: render_template348349.. autofunction:: render_template_string350351.. autofunction:: get_template_attribute352353Configuration354-------------355356.. autoclass:: Config357   :members:358359Extensions360----------361362.. data:: flask.ext363364   This module acts as redirect import module to Flask extensions.  It was365   added in 0.8 as the canonical way to import Flask extensions and makes366   it possible for us to have more flexibility in how we distribute367   extensions.368369   If you want to use an extension named “Flask-Foo” you would import it370   from :data:`~flask.ext` as follows::371372        from flask.ext import foo373374   .. versionadded:: 0.8375376Useful Internals377----------------378379.. autoclass:: flask.ctx.RequestContext380   :members:381382.. data:: _request_ctx_stack383384   The internal :class:`~werkzeug.local.LocalStack` that is used to implement385   all the context local objects used in Flask.  This is a documented386   instance and can be used by extensions and application code but the387   use is discouraged in general.388389   The following attributes are always present on each layer of the390   stack:391392   `app`393      the active Flask application.394395   `url_adapter`396      the URL adapter that was used to match the request.397398   `request`399      the current request object.400401   `session`402      the active session object.403404   `g`405      an object with all the attributes of the :data:`flask.g` object.406407   `flashes`408      an internal cache for the flashed messages.409410   Example usage::411412      from flask import _request_ctx_stack413414      def get_session():415          ctx = _request_ctx_stack.top416          if ctx is not None:417              return ctx.session418419.. autoclass:: flask.ctx.AppContext420   :members:421422.. data:: _app_ctx_stack423424   Works similar to the request context but only binds the application.425   This is mainly there for extensions to store data.426427   .. versionadded:: 0.9428429.. autoclass:: flask.blueprints.BlueprintSetupState430   :members:431432Signals433-------434435.. when modifying this list, also update the one in signals.rst436437.. versionadded:: 0.6438439.. data:: signals_available440441   `True` if the signalling system is available.  This is the case442   when `blinker`_ is installed.443444.. data:: template_rendered445446   This signal is sent when a template was successfully rendered.  The447   signal is invoked with the instance of the template as `template`448   and the context as dictionary (named `context`).449450.. data:: request_started451452   This signal is sent before any request processing started but when the453   request context was set up.  Because the request context is already454   bound, the subscriber can access the request with the standard global455   proxies such as :class:`~flask.request`.456457.. data:: request_finished458459   This signal is sent right before the response is sent to the client.460   It is passed the response to be sent named `response`.461462.. data:: got_request_exception463464   This signal is sent when an exception happens during request processing.465   It is sent *before* the standard exception handling kicks in and even466   in debug mode, where no exception handling happens.  The exception467   itself is passed to the subscriber as `exception`.468469.. data:: request_tearing_down470471   This signal is sent when the application is tearing down the request.472   This is always called, even if an error happened.  No arguments are473   provided.474475.. currentmodule:: None476477.. class:: flask.signals.Namespace478479   An alias for :class:`blinker.base.Namespace` if blinker is available,480   otherwise a dummy class that creates fake signals.  This class is481   available for Flask extensions that want to provide the same fallback482   system as Flask itself.483484   .. method:: signal(name, doc=None)485486      Creates a new signal for this namespace if blinker is available,487      otherwise returns a fake signal that has a send method that will488      do nothing but will fail with a :exc:`RuntimeError` for all other489      operations, including connecting.490491.. _blinker: http://pypi.python.org/pypi/blinker492493Class-Based Views494-----------------495496.. versionadded:: 0.7497498.. currentmodule:: None499500.. autoclass:: flask.views.View501   :members:502503.. autoclass:: flask.views.MethodView504   :members:505506.. _url-route-registrations:507508URL Route Registrations509-----------------------510511Generally there are three ways to define rules for the routing system:5125131.  You can use the :meth:`flask.Flask.route` decorator.5142.  You can use the :meth:`flask.Flask.add_url_rule` function.5153.  You can directly access the underlying Werkzeug routing system516    which is exposed as :attr:`flask.Flask.url_map`.517518Variable parts in the route can be specified with angular brackets519(``/user/<username>``).  By default a variable part in the URL accepts any520string without a slash however a different converter can be specified as521well by using ``<converter:name>``.522523Variable parts are passed to the view function as keyword arguments.524525The following converters are available:526527=========== ===============================================528`string`    accepts any text without a slash (the default)529`int`       accepts integers530`float`     like `int` but for floating point values531`path`      like the default but also accepts slashes532=========== ===============================================533534Here are some examples::535536    @app.route('/')537    def index():538        pass539540    @app.route('/<username>')541    def show_user(username):542        pass543544    @app.route('/post/<int:post_id>')545    def show_post(post_id):546        pass547548An important detail to keep in mind is how Flask deals with trailing549slashes.  The idea is to keep each URL unique so the following rules550apply:5515521. If a rule ends with a slash and is requested without a slash by the553   user, the user is automatically redirected to the same page with a554   trailing slash attached.5552. If a rule does not end with a trailing slash and the user requests the556   page with a trailing slash, a 404 not found is raised.557558This is consistent with how web servers deal with static files.  This559also makes it possible to use relative link targets safely.560561You can also define multiple rules for the same function.  They have to be562unique however.  Defaults can also be specified.  Here for example is a563definition for a URL that accepts an optional page::564565    @app.route('/users/', defaults={'page': 1})566    @app.route('/users/page/<int:page>')567    def show_users(page):568        pass569570This specifies that ``/users/`` will be the URL for page one and571``/users/page/N`` will be the URL for page `N`.572573Here are the parameters that :meth:`~flask.Flask.route` and574:meth:`~flask.Flask.add_url_rule` accept.  The only difference is that575with the route parameter the view function is defined with the decorator576instead of the `view_func` parameter.577578=============== ==========================================================579`rule`          the URL roule as string580`endpoint`      the endpoint for the registered URL rule.  Flask itself581                assumes that the name of the view function is the name582                of the endpoint if not explicitly stated.583`view_func`     the function to call when serving a request to the584                provided endpoint.  If this is not provided one can585                specify the function later by storing it in the586                :attr:`~flask.Flask.view_functions` dictionary with the587                endpoint as key.588`defaults`      A dictionary with defaults for this rule.  See the589                example above for how defaults work.590`subdomain`     specifies the rule for the subdomain in case subdomain591                matching is in use.  If not specified the default592                subdomain is assumed.593`**options`     the options to be forwarded to the underlying594                :class:`~werkzeug.routing.Rule` object.  A change to595                Werkzeug is handling of method options.  methods is a list596                of methods this rule should be limited to (`GET`, `POST`597                etc.).  By default a rule just listens for `GET` (and598                implicitly `HEAD`).  Starting with Flask 0.6, `OPTIONS` is599                implicitly added and handled by the standard request600                handling.  They have to be specified as keyword arguments.601=============== ==========================================================602603.. _view-func-options:604605View Function Options606---------------------607608For internal usage the view functions can have some attributes attached to609customize behavior the view function would normally not have control over.610The following attributes can be provided optionally to either override611some defaults to :meth:`~flask.Flask.add_url_rule` or general behavior:612613-   `__name__`: The name of a function is by default used as endpoint.  If614    endpoint is provided explicitly this value is used.  Additionally this615    will be prefixed with the name of the blueprint by default which616    cannot be customized from the function itself.617618-   `methods`: If methods are not provided when the URL rule is added,619    Flask will look on the view function object itself is an `methods`620    attribute exists.  If it does, it will pull the information for the621    methods from there.622623-   `provide_automatic_options`: if this attribute is set Flask will624    either force enable or disable the automatic implementation of the625    HTTP `OPTIONS` response.  This can be useful when working with626    decorators that want to customize the `OPTIONS` response on a per-view627    basis.628629Full example::630631    def index():632        if request.method == 'OPTIONS':633            # custom options handling here634            ...635        return 'Hello World!'636    index.provide_automatic_options = False637    index.methods = ['GET', 'OPTIONS']638639    app.add_url_rule('/', index)640641.. versionadded:: 0.8642   The `provide_automatic_options` functionality was added.