Skip to content
Myr

api.rst

This file

Path

docs/api.rst

624 lines · 18.8 KiB

Last changed by

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

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      The response status as integer.150151152Sessions153--------154155If you have the :attr:`Flask.secret_key` set you can use sessions in Flask156applications.  A session basically makes it possible to remember157information from one request to another.  The way Flask does this is by158using a signed cookie.  So the user can look at the session contents, but159not modify it unless they know the secret key, so make sure to set that160to something complex and unguessable.161162To access the current session you can use the :class:`session` object:163164.. class:: session165166   The session object works pretty much like an ordinary dict, with the167   difference that it keeps track on modifications.168169   This is a proxy.  See :ref:`notes-on-proxies` for more information.170171   The following attributes are interesting:172173   .. attribute:: new174175      `True` if the session is new, `False` otherwise.176177   .. attribute:: modified178179      `True` if the session object detected a modification.  Be advised180      that modifications on mutable structures are not picked up181      automatically, in that situation you have to explicitly set the182      attribute to `True` yourself.  Here an example::183184          # this change is not picked up because a mutable object (here185          # a list) is changed.186          session['objects'].append(42)187          # so mark it as modified yourself188          session.modified = True189190   .. attribute:: permanent191192      If set to `True` the session lives for193      :attr:`~flask.Flask.permanent_session_lifetime` seconds.  The194      default is 31 days.  If set to `False` (which is the default) the195      session will be deleted when the user closes the browser.196197198Session Interface199-----------------200201.. versionadded:: 0.8202203The session interface provides a simple way to replace the session204implementation that Flask is using.205206.. currentmodule:: flask.sessions207208.. autoclass:: SessionInterface209   :members:210211.. autoclass:: SecureCookieSessionInterface212   :members:213214.. autoclass:: NullSession215   :members:216217.. autoclass:: SessionMixin218   :members:219220.. admonition:: Notice221222   The ``PERMANENT_SESSION_LIFETIME`` config key can also be an integer223   starting with Flask 0.8.  Either catch this down yourself or use224   the :attr:`~flask.Flask.permanent_session_lifetime` attribute on the225   app which converts the result to an integer automatically.226227228Test Client229-----------230231.. currentmodule:: flask.testing232233.. autoclass:: FlaskClient234   :members:235236237Application Globals238-------------------239240.. currentmodule:: flask241242To share data that is valid for one request only from one function to243another, a global variable is not good enough because it would break in244threaded environments.  Flask provides you with a special object that245ensures it is only valid for the active request and that will return246different values for each request.  In a nutshell: it does the right247thing, like it does for :class:`request` and :class:`session`.248249.. data:: g250251   Just store on this whatever you want.  For example a database252   connection or the user that is currently logged in.253254   This is a proxy.  See :ref:`notes-on-proxies` for more information.255256257Useful Functions and Classes258----------------------------259260.. data:: current_app261262   Points to the application handling the request.  This is useful for263   extensions that want to support multiple applications running side264   by side.265266   This is a proxy.  See :ref:`notes-on-proxies` for more information.267268.. autofunction:: has_request_context269270.. autofunction:: url_for271272.. function:: abort(code)273274   Raises an :exc:`~werkzeug.exceptions.HTTPException` for the given275   status code.  For example to abort request handling with a page not276   found exception, you would call ``abort(404)``.277278   :param code: the HTTP error code.279280.. autofunction:: redirect281282.. autofunction:: make_response283284.. autofunction:: send_file285286.. autofunction:: send_from_directory287288.. autofunction:: safe_join289290.. autofunction:: escape291292.. autoclass:: Markup293   :members: escape, unescape, striptags294295Message Flashing296----------------297298.. autofunction:: flash299300.. autofunction:: get_flashed_messages301302Returning JSON303--------------304305.. autofunction:: jsonify306307.. data:: json308309    If JSON support is picked up, this will be the module that Flask is310    using to parse and serialize JSON.  So instead of doing this yourself::311312        try:313            import simplejson as json314        except ImportError:315            import json316317    You can instead just do this::318319        from flask import json320321    For usage examples, read the :mod:`json` documentation.322323    The :func:`~json.dumps` function of this json module is also available324    as filter called ``|tojson`` in Jinja2.  Note that inside `script`325    tags no escaping must take place, so make sure to disable escaping326    with ``|safe`` if you intend to use it inside `script` tags:327328    .. sourcecode:: html+jinja329330        <script type=text/javascript>331            doSomethingWith({{ user.username|tojson|safe }});332        </script>333334    Note that the ``|tojson`` filter escapes forward slashes properly.335336Template Rendering337------------------338339.. autofunction:: render_template340341.. autofunction:: render_template_string342343.. autofunction:: get_template_attribute344345Configuration346-------------347348.. autoclass:: Config349   :members:350351Extensions352----------353354.. data:: flask.ext355356   This module acts as redirect import module to Flask extensions.  It was357   added in 0.8 as the canonical way to import Flask extensions and makes358   it possible for us to have more flexibility in how we distribute359   extensions.360361   If you want to use an extension named “Flask-Foo” you would import it362   from :data:`~flask.ext` as follows::363364        from flask.ext import foo365366   .. versionadded:: 0.8367368Useful Internals369----------------370371.. autoclass:: flask.ctx.RequestContext372   :members:373374.. data:: _request_ctx_stack375376   The internal :class:`~werkzeug.local.LocalStack` that is used to implement377   all the context local objects used in Flask.  This is a documented378   instance and can be used by extensions and application code but the379   use is discouraged in general.380381   The following attributes are always present on each layer of the382   stack:383384   `app`385      the active Flask application.386387   `url_adapter`388      the URL adapter that was used to match the request.389390   `request`391      the current request object.392393   `session`394      the active session object.395396   `g`397      an object with all the attributes of the :data:`flask.g` object.398399   `flashes`400      an internal cache for the flashed messages.401402   Example usage::403404      from flask import _request_ctx_stack405406      def get_session():407          ctx = _request_ctx_stack.top408          if ctx is not None:409              return ctx.session410411.. autoclass:: flask.blueprints.BlueprintSetupState412   :members:413414Signals415-------416417.. when modifying this list, also update the one in signals.rst418419.. versionadded:: 0.6420421.. data:: signals_available422423   `True` if the signalling system is available.  This is the case424   when `blinker`_ is installed.425426.. data:: template_rendered427428   This signal is sent when a template was successfully rendered.  The429   signal is invoked with the instance of the template as `template`430   and the context as dictionary (named `context`).431432.. data:: request_started433434   This signal is sent before any request processing started but when the435   request context was set up.  Because the request context is already436   bound, the subscriber can access the request with the standard global437   proxies such as :class:`~flask.request`.438439.. data:: request_finished440441   This signal is sent right before the response is sent to the client.442   It is passed the response to be sent named `response`.443444.. data:: got_request_exception445446   This signal is sent when an exception happens during request processing.447   It is sent *before* the standard exception handling kicks in and even448   in debug mode, where no exception handling happens.  The exception449   itself is passed to the subscriber as `exception`.450451.. data:: request_tearing_down452453   This signal is sent when the application is tearing down the request.454   This is always called, even if an error happened.  No arguments are455   provided.456457.. currentmodule:: None458459.. class:: flask.signals.Namespace460461   An alias for :class:`blinker.base.Namespace` if blinker is available,462   otherwise a dummy class that creates fake signals.  This class is463   available for Flask extensions that want to provide the same fallback464   system as Flask itself.465466   .. method:: signal(name, doc=None)467468      Creates a new signal for this namespace if blinker is available,469      otherwise returns a fake signal that has a send method that will470      do nothing but will fail with a :exc:`RuntimeError` for all other471      operations, including connecting.472473.. _blinker: http://pypi.python.org/pypi/blinker474475Class Based Views476-----------------477478.. versionadded:: 0.7479480.. currentmodule:: None481482.. autoclass:: flask.views.View483   :members:484485.. autoclass:: flask.views.MethodView486   :members:487488.. _url-route-registrations:489490URL Route Registrations491-----------------------492493Generally there are three ways to define rules for the routing system:4944951.  You can use the :meth:`flask.Flask.route` decorator.4962.  You can use the :meth:`flask.Flask.add_url_rule` function.4973.  You can directly access the underlying Werkzeug routing system498    which is exposed as :attr:`flask.Flask.url_map`.499500Variable parts in the route can be specified with angular brackets501(``/user/<username>``).  By default a variable part in the URL accepts any502string without a slash however a different converter can be specified as503well by using ``<converter:name>``.504505Variable parts are passed to the view function as keyword arguments.506507The following converters are available:508509=========== ===============================================510`unicode`   accepts any text without a slash (the default)511`int`       accepts integers512`float`     like `int` but for floating point values513`path`      like the default but also accepts slashes514=========== ===============================================515516Here are some examples::517518    @app.route('/')519    def index():520        pass521522    @app.route('/<username>')523    def show_user(username):524        pass525526    @app.route('/post/<int:post_id>')527    def show_post(post_id):528        pass529530An important detail to keep in mind is how Flask deals with trailing531slashes.  The idea is to keep each URL unique so the following rules532apply:5335341. If a rule ends with a slash and is requested without a slash by the535   user, the user is automatically redirected to the same page with a536   trailing slash attached.5372. If a rule does not end with a trailing slash and the user requests the538   page with a trailing slash, a 404 not found is raised.539540This is consistent with how web servers deal with static files.  This541also makes it possible to use relative link targets safely.542543You can also define multiple rules for the same function.  They have to be544unique however.  Defaults can also be specified.  Here for example is a545definition for a URL that accepts an optional page::546547    @app.route('/users/', defaults={'page': 1})548    @app.route('/users/page/<int:page>')549    def show_users(page):550        pass551552This specifies that ``/users/`` will be the URL for page one and553``/users/page/N`` will be the URL for page `N`.554555Here are the parameters that :meth:`~flask.Flask.route` and556:meth:`~flask.Flask.add_url_rule` accept.  The only difference is that557with the route parameter the view function is defined with the decorator558instead of the `view_func` parameter.559560=============== ==========================================================561`rule`          the URL roule as string562`endpoint`      the endpoint for the registered URL rule.  Flask itself563                assumes that the name of the view function is the name564                of the endpoint if not explicitly stated.565`view_func`     the function to call when serving a request to the566                provided endpoint.  If this is not provided one can567                specify the function later by storing it in the568                :attr:`~flask.Flask.view_functions` dictionary with the569                endpoint as key.570`defaults`      A dictionary with defaults for this rule.  See the571                example above for how defaults work.572`subdomain`     specifies the rule for the subdomain in case subdomain573                matching is in use.  If not specified the default574                subdomain is assumed.575`**options`     the options to be forwarded to the underlying576                :class:`~werkzeug.routing.Rule` object.  A change to577                Werkzeug is handling of method options.  methods is a list578                of methods this rule should be limited to (`GET`, `POST`579                etc.).  By default a rule just listens for `GET` (and580                implicitly `HEAD`).  Starting with Flask 0.6, `OPTIONS` is581                implicitly added and handled by the standard request582                handling.  They have to be specified as keyword arguments.583=============== ==========================================================584585.. _view-func-options:586587View Function Options588---------------------589590For internal usage the view functions can have some attributes attached to591customize behavior the view function would normally not have control over.592The following attributes can be provided optionally to either override593some defaults to :meth:`~flask.Flask.add_url_rule` or general behavior:594595-   `__name__`: The name of a function is by default used as endpoint.  If596    endpoint is provided explicitly this value is used.  Additionally this597    will be prefixed with the name of the blueprint by default which598    cannot be customized from the function itself.599600-   `methods`: If methods are not provided when the URL rule is added,601    Flask will look on the view function object itself is an `methods`602    attribute exists.  If it does, it will pull the information for the603    methods from there.604605-   `provide_automatic_options`: if this attribute is set Flask will606    either force enable or disable the automatic implementation of the607    HTTP `OPTIONS` response.  This can be useful when working with608    decorators that want to customize the `OPTIONS` response on a per-view609    basis.610611Full example::612613    def index():614        if request.method == 'OPTIONS':615            # custom options handling here616            ...617        return 'Hello World!'618    index.provide_automatic_options = False619    index.methods = ['GET', 'OPTIONS']620621    app.add_url_rule('/', index)622623.. versionadded:: 0.8624   The `provide_automatic_options` functionality was added.