forked from orbit-oss/flask
Merge pull request #1240 from defuz/docs-style-fix-2
Docs style fixes: ``FOO`` vs `FOO` (reloaded)
This commit is contained in:
commit
6fcc2ae3f4
61 changed files with 396 additions and 396 deletions
30
CHANGES
30
CHANGES
|
|
@ -12,9 +12,9 @@ Version 1.0
|
|||
additional keyword arguments to the constructor of
|
||||
:attr:`flask.Flask.test_client_class`.
|
||||
- Added ``SESSION_REFRESH_EACH_REQUEST`` config key that controls the
|
||||
set-cookie behavior. If set to `True` a permanent session will be
|
||||
set-cookie behavior. If set to ``True`` a permanent session will be
|
||||
refreshed each request and get their lifetime extended, if set to
|
||||
`False` it will only be modified if the session actually modifies.
|
||||
``False`` it will only be modified if the session actually modifies.
|
||||
Non permanent sessions are not affected by this and will always
|
||||
expire if the browser window closes.
|
||||
- Made Flask support custom JSON mimetypes for incoming data.
|
||||
|
|
@ -28,7 +28,7 @@ Version 1.0
|
|||
- Added a workaround for a limitation in Python 3.3's namespace loader.
|
||||
- Added support for explicit root paths when using Python 3.3's namespace
|
||||
packages.
|
||||
- Added ``flask`` and the ``flask.cli`` module to start the local
|
||||
- Added :command:`flask` and the ``flask.cli`` module to start the local
|
||||
debug server through the click CLI system. This is recommended over the old
|
||||
``flask.run()`` method as it works faster and more reliable due to a
|
||||
different design and also replaces ``Flask-Script``.
|
||||
|
|
@ -183,7 +183,7 @@ Released on July 1st 2012, codename Campari.
|
|||
explicitly.
|
||||
- Unregister a circular dependency between the WSGI environment and
|
||||
the request object when shutting down the request. This means that
|
||||
environ ``werkzeug.request`` will be `None` after the response was
|
||||
environ ``werkzeug.request`` will be ``None`` after the response was
|
||||
returned to the WSGI server but has the advantage that the garbage
|
||||
collector is not needed on CPython to tear down the request unless
|
||||
the user created circular dependencies themselves.
|
||||
|
|
@ -204,8 +204,8 @@ Released on July 1st 2012, codename Campari.
|
|||
- The :func:`flask.get_flashed_messages` function now allows rendering flashed
|
||||
message categories in separate blocks, through a ``category_filter``
|
||||
argument.
|
||||
- The :meth:`flask.Flask.run` method now accepts `None` for `host` and `port`
|
||||
arguments, using default values when `None`. This allows for calling run
|
||||
- The :meth:`flask.Flask.run` method now accepts ``None`` for `host` and `port`
|
||||
arguments, using default values when ``None``. This allows for calling run
|
||||
using configuration values, e.g. ``app.run(app.config.get('MYHOST'),
|
||||
app.config.get('MYPORT'))``, with proper behavior whether or not a config
|
||||
file is provided.
|
||||
|
|
@ -326,7 +326,7 @@ Released on June 28th 2011, codename Grappa
|
|||
|
||||
- Added :meth:`~flask.Flask.make_default_options_response`
|
||||
which can be used by subclasses to alter the default
|
||||
behavior for `OPTIONS` responses.
|
||||
behavior for ``OPTIONS`` responses.
|
||||
- Unbound locals now raise a proper :exc:`RuntimeError` instead
|
||||
of an :exc:`AttributeError`.
|
||||
- Mimetype guessing and etag support based on file objects is now
|
||||
|
|
@ -339,10 +339,10 @@ Released on June 28th 2011, codename Grappa
|
|||
1.0 the old behavior will continue to work but issue dependency
|
||||
warnings.
|
||||
- fixed a problem for Flask to run on jython.
|
||||
- added a `PROPAGATE_EXCEPTIONS` configuration variable that can be
|
||||
- added a ``PROPAGATE_EXCEPTIONS`` configuration variable that can be
|
||||
used to flip the setting of exception propagation which previously
|
||||
was linked to `DEBUG` alone and is now linked to either `DEBUG` or
|
||||
`TESTING`.
|
||||
was linked to ``DEBUG`` alone and is now linked to either ``DEBUG`` or
|
||||
``TESTING``.
|
||||
- Flask no longer internally depends on rules being added through the
|
||||
`add_url_rule` function and can now also accept regular werkzeug
|
||||
rules added to the url map.
|
||||
|
|
@ -379,8 +379,8 @@ Version 0.6.1
|
|||
|
||||
Bugfix release, released on December 31st 2010
|
||||
|
||||
- Fixed an issue where the default `OPTIONS` response was
|
||||
not exposing all valid methods in the `Allow` header.
|
||||
- Fixed an issue where the default ``OPTIONS`` response was
|
||||
not exposing all valid methods in the ``Allow`` header.
|
||||
- Jinja2 template loading syntax now allows "./" in front of
|
||||
a template load path. Previously this caused issues with
|
||||
module setups.
|
||||
|
|
@ -450,7 +450,7 @@ Released on July 6th 2010, codename Calvados
|
|||
|
||||
- fixed a bug with subdomains that was caused by the inability to
|
||||
specify the server name. The server name can now be set with
|
||||
the `SERVER_NAME` config key. This key is now also used to set
|
||||
the ``SERVER_NAME`` config key. This key is now also used to set
|
||||
the session cookie cross-subdomain wide.
|
||||
- autoescaping is no longer active for all templates. Instead it
|
||||
is only active for ``.html``, ``.htm``, ``.xml`` and ``.xhtml``.
|
||||
|
|
@ -482,8 +482,8 @@ Released on June 18th 2010, codename Rakia
|
|||
requests that do not pop the request stack for testing.
|
||||
- because the Python standard library caches loggers, the name of
|
||||
the logger is configurable now to better support unittests.
|
||||
- added `TESTING` switch that can activate unittesting helpers.
|
||||
- the logger switches to `DEBUG` mode now if debug is enabled.
|
||||
- added ``TESTING`` switch that can activate unittesting helpers.
|
||||
- the logger switches to ``DEBUG`` mode now if debug is enabled.
|
||||
|
||||
Version 0.3.1
|
||||
-------------
|
||||
|
|
|
|||
38
docs/api.rst
38
docs/api.rst
|
|
@ -33,8 +33,8 @@ Incoming Request Data
|
|||
|
||||
.. attribute:: form
|
||||
|
||||
A :class:`~werkzeug.datastructures.MultiDict` with the parsed form data from `POST`
|
||||
or `PUT` requests. Please keep in mind that file uploads will not
|
||||
A :class:`~werkzeug.datastructures.MultiDict` with the parsed form data from ``POST``
|
||||
or ``PUT`` requests. Please keep in mind that file uploads will not
|
||||
end up here, but instead in the :attr:`files` attribute.
|
||||
|
||||
.. attribute:: args
|
||||
|
|
@ -71,7 +71,7 @@ Incoming Request Data
|
|||
.. attribute:: files
|
||||
|
||||
A :class:`~werkzeug.datastructures.MultiDict` with files uploaded as part of a
|
||||
`POST` or `PUT` request. Each file is stored as
|
||||
``POST`` or ``PUT`` request. Each file is stored as
|
||||
:class:`~werkzeug.datastructures.FileStorage` object. It basically behaves like a
|
||||
standard file object you know from Python, with the difference that
|
||||
it also has a :meth:`~werkzeug.datastructures.FileStorage.save` function that can
|
||||
|
|
@ -115,7 +115,7 @@ Incoming Request Data
|
|||
|
||||
.. attribute:: is_xhr
|
||||
|
||||
`True` if the request was triggered via a JavaScript
|
||||
``True`` if the request was triggered via a JavaScript
|
||||
`XMLHttpRequest`. This only works with libraries that support the
|
||||
``X-Requested-With`` header and set it to `XMLHttpRequest`.
|
||||
Libraries that do that are prototype, jQuery and Mochikit and
|
||||
|
|
@ -178,14 +178,14 @@ To access the current session you can use the :class:`session` object:
|
|||
|
||||
.. attribute:: new
|
||||
|
||||
`True` if the session is new, `False` otherwise.
|
||||
``True`` if the session is new, ``False`` otherwise.
|
||||
|
||||
.. attribute:: modified
|
||||
|
||||
`True` if the session object detected a modification. Be advised
|
||||
``True`` if the session object detected a modification. Be advised
|
||||
that modifications on mutable structures are not picked up
|
||||
automatically, in that situation you have to explicitly set the
|
||||
attribute to `True` yourself. Here an example::
|
||||
attribute to ``True`` yourself. Here an example::
|
||||
|
||||
# this change is not picked up because a mutable object (here
|
||||
# a list) is changed.
|
||||
|
|
@ -195,9 +195,9 @@ To access the current session you can use the :class:`session` object:
|
|||
|
||||
.. attribute:: permanent
|
||||
|
||||
If set to `True` the session lives for
|
||||
If set to ``True`` the session lives for
|
||||
:attr:`~flask.Flask.permanent_session_lifetime` seconds. The
|
||||
default is 31 days. If set to `False` (which is the default) the
|
||||
default is 31 days. If set to ``False`` (which is the default) the
|
||||
session will be deleted when the user closes the browser.
|
||||
|
||||
|
||||
|
|
@ -279,7 +279,7 @@ thing, like it does for :class:`request` and :class:`session`.
|
|||
pattern for testing.
|
||||
|
||||
Additionally as of 0.10 you can use the :meth:`get` method to
|
||||
get an attribute or `None` (or the second argument) if it's not set.
|
||||
get an attribute or ``None`` (or the second argument) if it's not set.
|
||||
These two usages are now equivalent::
|
||||
|
||||
user = getattr(flask.g, 'user', None)
|
||||
|
|
@ -376,9 +376,9 @@ JSON module:
|
|||
as string.
|
||||
|
||||
The :func:`~htmlsafe_dumps` function of this json module is also available
|
||||
as filter called ``|tojson`` in Jinja2. Note that inside `script`
|
||||
as filter called ``|tojson`` in Jinja2. Note that inside ``script``
|
||||
tags no escaping must take place, so make sure to disable escaping
|
||||
with ``|safe`` if you intend to use it inside `script` tags unless
|
||||
with ``|safe`` if you intend to use it inside ``script`` tags unless
|
||||
you are using Flask 0.10 which implies that:
|
||||
|
||||
.. sourcecode:: html+jinja
|
||||
|
|
@ -516,7 +516,7 @@ Signals
|
|||
|
||||
.. data:: signals_available
|
||||
|
||||
`True` if the signaling system is available. This is the case
|
||||
``True`` if the signaling system is available. This is the case
|
||||
when `blinker`_ is installed.
|
||||
|
||||
.. data:: template_rendered
|
||||
|
|
@ -704,9 +704,9 @@ instead of the `view_func` parameter.
|
|||
`**options` the options to be forwarded to the underlying
|
||||
:class:`~werkzeug.routing.Rule` object. A change to
|
||||
Werkzeug is handling of method options. methods is a list
|
||||
of methods this rule should be limited to (`GET`, `POST`
|
||||
etc.). By default a rule just listens for `GET` (and
|
||||
implicitly `HEAD`). Starting with Flask 0.6, `OPTIONS` is
|
||||
of methods this rule should be limited to (``GET``, ``POST``
|
||||
etc.). By default a rule just listens for ``GET`` (and
|
||||
implicitly ``HEAD``). Starting with Flask 0.6, ``OPTIONS`` is
|
||||
implicitly added and handled by the standard request
|
||||
handling. They have to be specified as keyword arguments.
|
||||
=============== ==========================================================
|
||||
|
|
@ -733,8 +733,8 @@ some defaults to :meth:`~flask.Flask.add_url_rule` or general behavior:
|
|||
|
||||
- `provide_automatic_options`: if this attribute is set Flask will
|
||||
either force enable or disable the automatic implementation of the
|
||||
HTTP `OPTIONS` response. This can be useful when working with
|
||||
decorators that want to customize the `OPTIONS` response on a per-view
|
||||
HTTP ``OPTIONS`` response. This can be useful when working with
|
||||
decorators that want to customize the ``OPTIONS`` response on a per-view
|
||||
basis.
|
||||
|
||||
- `required_methods`: if this attribute is set, Flask will always add
|
||||
|
|
@ -782,7 +782,7 @@ Command Line Interface
|
|||
A special decorator that informs a click callback to be passed the
|
||||
script info object as first argument. This is normally not useful
|
||||
unless you implement very special commands like the run command which
|
||||
does not want the application to be loaded yet.
|
||||
does not want the application to be loaded yet.
|
||||
|
||||
.. autodata:: run_command
|
||||
|
||||
|
|
|
|||
|
|
@ -159,7 +159,7 @@ blueprint::
|
|||
admin = Blueprint('admin', __name__, static_folder='static')
|
||||
|
||||
By default the rightmost part of the path is where it is exposed on the
|
||||
web. Because the folder is called ``static`` here it will be available at
|
||||
web. Because the folder is called :file:`static` here it will be available at
|
||||
the location of the blueprint + ``/static``. Say the blueprint is
|
||||
registered for ``/admin`` the static folder will be at ``/admin/static``.
|
||||
|
||||
|
|
@ -185,10 +185,10 @@ provides in the actual application.
|
|||
So if you have a blueprint in the folder ``yourapplication/admin`` and you
|
||||
want to render the template ``'admin/index.html'`` and you have provided
|
||||
``templates`` as a `template_folder` you will have to create a file like
|
||||
this: ``yourapplication/admin/templates/admin/index.html``.
|
||||
this: :file:`yourapplication/admin/templates/admin/index.html`.
|
||||
|
||||
To further reiterate this: if you have a blueprint named ``admin`` and you
|
||||
want to render a template called ``index.html`` which is specific to this
|
||||
want to render a template called :file:`index.html` which is specific to this
|
||||
blueprint, the best idea is to lay out your templates like this::
|
||||
|
||||
yourpackage/
|
||||
|
|
@ -199,7 +199,7 @@ blueprint, the best idea is to lay out your templates like this::
|
|||
index.html
|
||||
__init__.py
|
||||
|
||||
And then when you want to render the template, use ``admin/index.html`` as
|
||||
And then when you want to render the template, use :file:`admin/index.html` as
|
||||
the name to look up the template by. If you encounter problems loading
|
||||
the correct templates enable the ``EXPLAIN_TEMPLATE_LOADING`` config
|
||||
variable which will instruct Flask to print out the steps it goes through
|
||||
|
|
|
|||
26
docs/cli.rst
26
docs/cli.rst
|
|
@ -15,7 +15,7 @@ applications.
|
|||
Basic Usage
|
||||
-----------
|
||||
|
||||
After installation of Flask you will now find a ``flask`` script installed
|
||||
After installation of Flask you will now find a :command:`flask` script installed
|
||||
into your virtualenv. If you don't want to install Flask or you have a
|
||||
special use-case you can also use ``python -m flask`` to accomplish exactly
|
||||
the same.
|
||||
|
|
@ -25,9 +25,9 @@ your Flask application's :attr:`Flask.cli` instance as well as some
|
|||
built-in commands that are always there. Flask extensions can also
|
||||
register more commands there if they desire so.
|
||||
|
||||
For the ``flask`` script to work, an application needs to be discovered.
|
||||
For the :command:`flask` script to work, an application needs to be discovered.
|
||||
The two most common ways are either an environment variable
|
||||
(``FLASK_APP``) or the ``--app`` / ``-a`` parameter. It should be the
|
||||
(``FLASK_APP``) or the :option:`--app` / :option:`-a` parameter. It should be the
|
||||
import path for your application or the path to a Python file. In the
|
||||
latter case Flask will attempt to setup the Python path for you
|
||||
automatically and discover the module name but that might not always work.
|
||||
|
|
@ -35,7 +35,7 @@ automatically and discover the module name but that might not always work.
|
|||
In that imported file the name of the app needs to be called ``app`` or
|
||||
optionally be specified after a colon.
|
||||
|
||||
Given a ``hello.py`` file with the application in it named ``app`` this is
|
||||
Given a :file:`hello.py` file with the application in it named ``app`` this is
|
||||
how it can be run.
|
||||
|
||||
Environment variables (On Windows use ``set`` instead of ``export``)::
|
||||
|
|
@ -62,7 +62,7 @@ automatically also activate the correct application name.
|
|||
Debug Flag
|
||||
----------
|
||||
|
||||
The ``flask`` script can be run with ``--debug`` or ``--no-debug`` to
|
||||
The :command:`flask` script can be run with :option:`--debug` or :option:`--no-debug` to
|
||||
automatically flip the debug flag of the application. This can also be
|
||||
configured by setting ``FLASK_DEBUG`` to ``1`` or ``0``.
|
||||
|
||||
|
|
@ -122,7 +122,7 @@ Factory Functions
|
|||
-----------------
|
||||
|
||||
In case you are using factory functions to create your application (see
|
||||
:ref:`app-factories`) you will discover that the ``flask`` command cannot
|
||||
:ref:`app-factories`) you will discover that the :command:`flask` command cannot
|
||||
work with them directly. Flask won't be able to figure out how to
|
||||
instantiate your application properly by itself. Because of this reason
|
||||
the recommendation is to create a separate file that instantiates
|
||||
|
|
@ -133,7 +133,7 @@ For instance if you have a factory function that creates an application
|
|||
from a filename you could make a separate file that creates such an
|
||||
application from an environment variable.
|
||||
|
||||
This could be a file named ``autoapp.py`` with these contents::
|
||||
This could be a file named :file:`autoapp.py` with these contents::
|
||||
|
||||
import os
|
||||
from yourapplication import create_app
|
||||
|
|
@ -145,14 +145,14 @@ it up::
|
|||
export YOURAPPLICATION_CONFIG=/path/to/config.cfg
|
||||
export FLASK_APP=/path/to/autoapp.py
|
||||
|
||||
From this point onwards ``flask`` will find your application.
|
||||
From this point onwards :command:`flask` will find your application.
|
||||
|
||||
.. _custom-scripts:
|
||||
|
||||
Custom Scripts
|
||||
--------------
|
||||
|
||||
While the most common way is to use the ``flask`` command, you can also
|
||||
While the most common way is to use the :command:`flask` command, you can also
|
||||
make your own "driver scripts". Since Flask uses click for the scripts
|
||||
there is no reason you cannot hook these scripts into any click
|
||||
application. There is one big caveat and that is, that commands
|
||||
|
|
@ -162,7 +162,7 @@ necessary so that the commands know which Flask application they have to
|
|||
work with.
|
||||
|
||||
To understand why you might want custom scripts you need to understand how
|
||||
click finds and executes the Flask application. If you use the ``flask``
|
||||
click finds and executes the Flask application. If you use the :command:`flask`
|
||||
script you specify the application to work with on the command line or
|
||||
environment variable as an import name. This is simple but it has some
|
||||
limitations. Primarily it does not work with application factory
|
||||
|
|
@ -179,7 +179,7 @@ We won't go into detail now about the differences but if you are curious
|
|||
you can have a look at the :ref:`script-info-object` section to learn all
|
||||
about it.
|
||||
|
||||
To explain all of this, here is an example ``manage.py`` script that
|
||||
To explain all of this, here is an example :file:`manage.py` script that
|
||||
manages a hypothetical wiki application. We will go through the details
|
||||
afterwards::
|
||||
|
||||
|
|
@ -223,7 +223,7 @@ step.
|
|||
call that function with the script info and ask for it to be created.
|
||||
4. In step 2 you could see that the config is passed to the actual
|
||||
creation function. This config comes from the :func:`script_info_option`
|
||||
decorator for the main script. It accepts a ``--config`` option and
|
||||
decorator for the main script. It accepts a :option:`--config` option and
|
||||
then stores it in the script info so we can use it to create the
|
||||
application.
|
||||
5. All is rounded up by invoking the script.
|
||||
|
|
@ -239,7 +239,7 @@ both provide custom commands to click as well as not loading your
|
|||
application unless it has to. The reason for this is added flexibility.
|
||||
|
||||
This way an application can provide custom commands, but even in the
|
||||
absence of an application the ``flask`` script is still operational on a
|
||||
absence of an application the :command:`flask` script is still operational on a
|
||||
basic level. In addition to that it means that the individual commands
|
||||
have the option to avoid creating an instance of the Flask application
|
||||
unless required. This is very useful as it allows the server commands for
|
||||
|
|
|
|||
|
|
@ -56,9 +56,9 @@ The following configuration values are used internally by Flask:
|
|||
``TESTING`` enable/disable testing mode
|
||||
``PROPAGATE_EXCEPTIONS`` explicitly enable or disable the
|
||||
propagation of exceptions. If not set or
|
||||
explicitly set to `None` this is
|
||||
implicitly true if either `TESTING` or
|
||||
`DEBUG` is true.
|
||||
explicitly set to ``None`` this is
|
||||
implicitly true if either ``TESTING`` or
|
||||
``DEBUG`` is true.
|
||||
``PRESERVE_CONTEXT_ON_EXCEPTION`` By default if the application is in
|
||||
debug mode the request context is not
|
||||
popped on exceptions to enable debuggers
|
||||
|
|
@ -80,20 +80,20 @@ The following configuration values are used internally by Flask:
|
|||
that is not set for ``'/'``.
|
||||
``SESSION_COOKIE_HTTPONLY`` controls if the cookie should be set
|
||||
with the httponly flag. Defaults to
|
||||
`True`.
|
||||
``True``.
|
||||
``SESSION_COOKIE_SECURE`` controls if the cookie should be set
|
||||
with the secure flag. Defaults to
|
||||
`False`.
|
||||
``False``.
|
||||
``PERMANENT_SESSION_LIFETIME`` the lifetime of a permanent session as
|
||||
:class:`datetime.timedelta` object.
|
||||
Starting with Flask 0.8 this can also be
|
||||
an integer representing seconds.
|
||||
``SESSION_REFRESH_EACH_REQUEST`` this flag controls how permanent
|
||||
sessions are refreshed. If set to `True`
|
||||
sessions are refreshed. If set to ``True``
|
||||
(which is the default) then the cookie
|
||||
is refreshed each request which
|
||||
automatically bumps the lifetime. If
|
||||
set to `False` a `set-cookie` header is
|
||||
set to ``False`` a `set-cookie` header is
|
||||
only sent if the session is modified.
|
||||
Non permanent sessions are not affected
|
||||
by this.
|
||||
|
|
@ -127,7 +127,7 @@ The following configuration values are used internally by Flask:
|
|||
reject incoming requests with a
|
||||
content length greater than this by
|
||||
returning a 413 status code.
|
||||
``SEND_FILE_MAX_AGE_DEFAULT``: Default cache control max age to use with
|
||||
``SEND_FILE_MAX_AGE_DEFAULT`` Default cache control max age to use with
|
||||
:meth:`~flask.Flask.send_static_file` (the
|
||||
default static file handler) and
|
||||
:func:`~flask.send_file`, in
|
||||
|
|
@ -260,7 +260,7 @@ So a common pattern is this::
|
|||
|
||||
This first loads the configuration from the
|
||||
`yourapplication.default_settings` module and then overrides the values
|
||||
with the contents of the file the :envvar:`YOURAPPLICATION_SETTINGS`
|
||||
with the contents of the file the :envvar:``YOURAPPLICATION_SETTINGS``
|
||||
environment variable points to. This environment variable can be set on
|
||||
Linux or OS X with the export command in the shell before starting the
|
||||
server::
|
||||
|
|
@ -323,7 +323,7 @@ in the example above::
|
|||
app.config.from_object('yourapplication.default_settings')
|
||||
app.config.from_envvar('YOURAPPLICATION_SETTINGS')
|
||||
|
||||
Then you just have to add a separate `config.py` file and export
|
||||
Then you just have to add a separate :file:`config.py` file and export
|
||||
``YOURAPPLICATION_SETTINGS=/path/to/config.py`` and you are done. However
|
||||
there are alternative ways as well. For example you could use imports or
|
||||
subclassing.
|
||||
|
|
|
|||
|
|
@ -24,7 +24,7 @@ Creating a `.cgi` file
|
|||
----------------------
|
||||
|
||||
First you need to create the CGI application file. Let's call it
|
||||
`yourapplication.cgi`::
|
||||
:file:`yourapplication.cgi`::
|
||||
|
||||
#!/usr/bin/python
|
||||
from wsgiref.handlers import CGIHandler
|
||||
|
|
@ -36,7 +36,7 @@ Server Setup
|
|||
------------
|
||||
|
||||
Usually there are two ways to configure the server. Either just copy the
|
||||
`.cgi` into a `cgi-bin` (and use `mod_rewrite` or something similar to
|
||||
``.cgi`` into a :file:`cgi-bin` (and use `mod_rewrite` or something similar to
|
||||
rewrite the URL) or let the server point to the file directly.
|
||||
|
||||
In Apache for example you can put something like this into the config:
|
||||
|
|
@ -46,8 +46,8 @@ In Apache for example you can put something like this into the config:
|
|||
ScriptAlias /app /path/to/the/application.cgi
|
||||
|
||||
On shared webhosting, though, you might not have access to your Apache config.
|
||||
In this case, a file called `.htaccess`, sitting in the public directory you want
|
||||
your app to be available, works too but the `ScriptAlias` directive won't
|
||||
In this case, a file called ``.htaccess``, sitting in the public directory you want
|
||||
your app to be available, works too but the ``ScriptAlias`` directive won't
|
||||
work in that case:
|
||||
|
||||
.. sourcecode:: apache
|
||||
|
|
|
|||
|
|
@ -40,8 +40,8 @@ socket to the :class:`~flup.server.fcgi.WSGIServer`::
|
|||
The path has to be the exact same path you define in the server
|
||||
config.
|
||||
|
||||
Save the `yourapplication.fcgi` file somewhere you will find it again.
|
||||
It makes sense to have that in `/var/www/yourapplication` or something
|
||||
Save the :file:`yourapplication.fcgi` file somewhere you will find it again.
|
||||
It makes sense to have that in :file:`/var/www/yourapplication` or something
|
||||
similar.
|
||||
|
||||
Make sure to set the executable bit on that file so that the servers
|
||||
|
|
@ -56,7 +56,7 @@ Configuring Apache
|
|||
|
||||
The example above is good enough for a basic Apache deployment but your
|
||||
`.fcgi` file will appear in your application URL e.g.
|
||||
example.com/yourapplication.fcgi/news/. There are few ways to configure
|
||||
``example.com/yourapplication.fcgi/news/``. There are few ways to configure
|
||||
your application so that yourapplication.fcgi does not appear in the URL.
|
||||
A preferable way is to use the ScriptAlias and SetHandler configuration
|
||||
directives to route requests to the FastCGI server. The following example
|
||||
|
|
@ -153,7 +153,7 @@ A basic FastCGI configuration for lighttpd looks like that::
|
|||
)
|
||||
|
||||
Remember to enable the FastCGI, alias and rewrite modules. This configuration
|
||||
binds the application to `/yourapplication`. If you want the application to
|
||||
binds the application to ``/yourapplication``. If you want the application to
|
||||
work in the URL root you have to work around a lighttpd bug with the
|
||||
:class:`~werkzeug.contrib.fixers.LighttpdCGIRootFix` middleware.
|
||||
|
||||
|
|
@ -180,9 +180,9 @@ A basic Flask FastCGI configuration for nginx looks like this::
|
|||
fastcgi_pass unix:/tmp/yourapplication-fcgi.sock;
|
||||
}
|
||||
|
||||
This configuration binds the application to `/yourapplication`. If you
|
||||
This configuration binds the application to ``/yourapplication``. If you
|
||||
want to have it in the URL root it's a bit simpler because you don't
|
||||
have to figure out how to calculate `PATH_INFO` and `SCRIPT_NAME`::
|
||||
have to figure out how to calculate ``PATH_INFO`` and ``SCRIPT_NAME``::
|
||||
|
||||
location / { try_files $uri @yourapplication; }
|
||||
location @yourapplication {
|
||||
|
|
|
|||
|
|
@ -52,7 +52,7 @@ reload you can safely ignore them. Just restart the server.
|
|||
Creating a `.wsgi` file
|
||||
-----------------------
|
||||
|
||||
To run your application you need a `yourapplication.wsgi` file. This file
|
||||
To run your application you need a :file:`yourapplication.wsgi` file. This file
|
||||
contains the code `mod_wsgi` is executing on startup to get the application
|
||||
object. The object called `application` in that file is then used as
|
||||
application.
|
||||
|
|
@ -65,12 +65,12 @@ If you don't have a factory function for application creation but a singleton
|
|||
instance you can directly import that one as `application`.
|
||||
|
||||
Store that file somewhere that you will find it again (e.g.:
|
||||
`/var/www/yourapplication`) and make sure that `yourapplication` and all
|
||||
:file:`/var/www/yourapplication`) and make sure that `yourapplication` and all
|
||||
the libraries that are in use are on the python load path. If you don't
|
||||
want to install it system wide consider using a `virtual python`_
|
||||
instance. Keep in mind that you will have to actually install your
|
||||
application into the virtualenv as well. Alternatively there is the
|
||||
option to just patch the path in the `.wsgi` file before the import::
|
||||
option to just patch the path in the ``.wsgi`` file before the import::
|
||||
|
||||
import sys
|
||||
sys.path.insert(0, '/path/to/the/application')
|
||||
|
|
@ -132,7 +132,7 @@ If your application does not run, follow this guide to troubleshoot:
|
|||
You have a ``app.run()`` call in your application file that is not
|
||||
guarded by an ``if __name__ == '__main__':`` condition. Either
|
||||
remove that :meth:`~flask.Flask.run` call from the file and move it
|
||||
into a separate `run.py` file or put it into such an if block.
|
||||
into a separate :file:`run.py` file or put it into such an if block.
|
||||
|
||||
**Problem:** application gives permission errors
|
||||
Probably caused by your application running as the wrong user. Make
|
||||
|
|
@ -171,7 +171,7 @@ Support for Automatic Reloading
|
|||
-------------------------------
|
||||
|
||||
To help deployment tools you can activate support for automatic
|
||||
reloading. Whenever something changes the `.wsgi` file, `mod_wsgi` will
|
||||
reloading. Whenever something changes the ``.wsgi`` file, `mod_wsgi` will
|
||||
reload all the daemon processes for us.
|
||||
|
||||
For that, just add the following directive to your `Directory` section:
|
||||
|
|
@ -186,9 +186,9 @@ Working with Virtual Environments
|
|||
Virtual environments have the advantage that they never install the
|
||||
required dependencies system wide so you have a better control over what
|
||||
is used where. If you want to use a virtual environment with mod_wsgi
|
||||
you have to modify your `.wsgi` file slightly.
|
||||
you have to modify your ``.wsgi`` file slightly.
|
||||
|
||||
Add the following lines to the top of your `.wsgi` file::
|
||||
Add the following lines to the top of your ``.wsgi`` file::
|
||||
|
||||
activate_this = '/path/to/env/bin/activate_this.py'
|
||||
execfile(activate_this, dict(__file__=activate_this))
|
||||
|
|
|
|||
|
|
@ -51,9 +51,9 @@ A basic flask uWSGI configuration for nginx looks like this::
|
|||
uwsgi_pass unix:/tmp/uwsgi.sock;
|
||||
}
|
||||
|
||||
This configuration binds the application to `/yourapplication`. If you want
|
||||
This configuration binds the application to ``/yourapplication``. If you want
|
||||
to have it in the URL root it's a bit simpler because you don't have to tell
|
||||
it the WSGI `SCRIPT_NAME` or set the uwsgi modifier to make use of it::
|
||||
it the WSGI ``SCRIPT_NAME`` or set the uwsgi modifier to make use of it::
|
||||
|
||||
location / { try_files $uri @yourapplication; }
|
||||
location @yourapplication {
|
||||
|
|
|
|||
|
|
@ -74,8 +74,8 @@ Proxy Setups
|
|||
|
||||
If you deploy your application using one of these servers behind an HTTP proxy
|
||||
you will need to rewrite a few headers in order for the application to work.
|
||||
The two problematic values in the WSGI environment usually are `REMOTE_ADDR`
|
||||
and `HTTP_HOST`. You can configure your httpd to pass these headers, or you
|
||||
The two problematic values in the WSGI environment usually are ``REMOTE_ADDR``
|
||||
and ``HTTP_HOST``. You can configure your httpd to pass these headers, or you
|
||||
can fix them in middleware. Werkzeug ships a fixer that will solve some common
|
||||
setups, but you might want to write your own WSGI middleware for specific
|
||||
setups.
|
||||
|
|
@ -104,8 +104,8 @@ localhost at port 8000, setting appropriate headers:
|
|||
}
|
||||
|
||||
If your httpd is not providing these headers, the most common setup invokes the
|
||||
host being set from `X-Forwarded-Host` and the remote address from
|
||||
`X-Forwarded-For`::
|
||||
host being set from ``X-Forwarded-Host`` and the remote address from
|
||||
``X-Forwarded-For``::
|
||||
|
||||
from werkzeug.contrib.fixers import ProxyFix
|
||||
app.wsgi_app = ProxyFix(app.wsgi_app)
|
||||
|
|
|
|||
|
|
@ -27,7 +27,7 @@ The name of the actual extension (the human readable name) however would
|
|||
be something like "Flask-SimpleXML". Make sure to include the name
|
||||
"Flask" somewhere in that name and that you check the capitalization.
|
||||
This is how users can then register dependencies to your extension in
|
||||
their `setup.py` files.
|
||||
their :file:`setup.py` files.
|
||||
|
||||
Flask sets up a redirect package called :data:`flask.ext` where users
|
||||
should import the extensions from. If you for instance have a package
|
||||
|
|
@ -42,7 +42,7 @@ a requirement because many people will use patterns like the
|
|||
unittests and to support multiple configurations. Because of that it is
|
||||
crucial that your application supports that kind of behavior.
|
||||
|
||||
Most importantly the extension must be shipped with a `setup.py` file and
|
||||
Most importantly the extension must be shipped with a :file:`setup.py` file and
|
||||
registered on PyPI. Also the development checkout link should work so
|
||||
that people can easily install the development version into their
|
||||
virtualenv without having to download the library by hand.
|
||||
|
|
@ -70,7 +70,7 @@ Here's the contents of the most important files:
|
|||
setup.py
|
||||
````````
|
||||
|
||||
The next file that is absolutely required is the `setup.py` file which is
|
||||
The next file that is absolutely required is the :file:`setup.py` file which is
|
||||
used to install your Flask extension. The following contents are
|
||||
something you can work with::
|
||||
|
||||
|
|
@ -259,7 +259,7 @@ way::
|
|||
cur = db.connection.cursor()
|
||||
cur.execute(...)
|
||||
|
||||
At the end of the `with` block the teardown handles will be executed
|
||||
At the end of the ``with`` block the teardown handles will be executed
|
||||
automatically.
|
||||
|
||||
Additionally, the ``init_app`` method is used to support the factory pattern
|
||||
|
|
@ -366,7 +366,7 @@ extension to be approved you have to follow these guidelines:
|
|||
or ``python setup.py test``. For test suites invoked with ``make
|
||||
test`` the extension has to ensure that all dependencies for the test
|
||||
are installed automatically. If tests are invoked with ``python setup.py
|
||||
test``, test dependencies can be specified in the `setup.py` file. The
|
||||
test``, test dependencies can be specified in the :file:`setup.py` file. The
|
||||
test suite also has to be part of the distribution.
|
||||
3. APIs of approved extensions will be checked for the following
|
||||
characteristics:
|
||||
|
|
@ -380,7 +380,7 @@ extension to be approved you have to follow these guidelines:
|
|||
5. The naming scheme for official extensions is *Flask-ExtensionName* or
|
||||
*ExtensionName-Flask*.
|
||||
6. Approved extensions must define all their dependencies in the
|
||||
`setup.py` file unless a dependency cannot be met because it is not
|
||||
:file:`setup.py` file unless a dependency cannot be met because it is not
|
||||
available on PyPI.
|
||||
7. The extension must have documentation that uses one of the two Flask
|
||||
themes for Sphinx documentation.
|
||||
|
|
|
|||
|
|
@ -8,8 +8,8 @@ Finding Extensions
|
|||
------------------
|
||||
|
||||
Flask extensions are listed on the `Flask Extension Registry`_ and can be
|
||||
downloaded with ``easy_install`` or ``pip``. If you add a Flask extension
|
||||
as dependency to your ``requirements.rst`` or ``setup.py`` file they are
|
||||
downloaded with :command:`easy_install` or :command:`pip`. If you add a Flask extension
|
||||
as dependency to your :file:`requirements.txt` or :file:`setup.py` file they are
|
||||
usually installed with a simple command or when your application installs.
|
||||
|
||||
Using Extensions
|
||||
|
|
|
|||
|
|
@ -30,7 +30,7 @@ Configuration and Conventions
|
|||
Flask has many configuration values, with sensible defaults, and a few
|
||||
conventions when getting started. By convention templates and static files are
|
||||
stored in subdirectories within the application's Python source tree, with the
|
||||
names `templates` and `static` respectively. While this can be changed you
|
||||
names :file:`templates` and :file:`static` respectively. While this can be changed you
|
||||
usually don't have to, especially when getting started.
|
||||
|
||||
Growing with Flask
|
||||
|
|
|
|||
|
|
@ -16,7 +16,7 @@ However, barely any websites on the Internet are actual XHTML (which is
|
|||
HTML processed using XML rules). There are a couple of major reasons
|
||||
why this is the case. One of them is Internet Explorer's lack of proper
|
||||
XHTML support. The XHTML spec states that XHTML must be served with the MIME
|
||||
type `application/xhtml+xml`, but Internet Explorer refuses to read files
|
||||
type :mimetype:`application/xhtml+xml`, but Internet Explorer refuses to read files
|
||||
with that MIME type.
|
||||
While it is relatively easy to configure Web servers to serve XHTML properly,
|
||||
few people do. This is likely because properly using XHTML can be quite
|
||||
|
|
|
|||
|
|
@ -54,13 +54,13 @@ in your package manager. If you use Ubuntu, try::
|
|||
|
||||
$ sudo apt-get install python-virtualenv
|
||||
|
||||
If you are on Windows and don't have the `easy_install` command, you must
|
||||
If you are on Windows and don't have the :command:`easy_install` command, you must
|
||||
install it first. Check the :ref:`windows-easy-install` section for more
|
||||
information about how to do that. Once you have it installed, run the same
|
||||
commands as above, but without the `sudo` prefix.
|
||||
commands as above, but without the :command:`sudo` prefix.
|
||||
|
||||
Once you have virtualenv installed, just fire up a shell and create
|
||||
your own environment. I usually create a project folder and a `venv`
|
||||
your own environment. I usually create a project folder and a :file:`venv`
|
||||
folder within::
|
||||
|
||||
$ mkdir myproject
|
||||
|
|
@ -99,19 +99,19 @@ System-Wide Installation
|
|||
------------------------
|
||||
|
||||
This is possible as well, though I do not recommend it. Just run
|
||||
`pip` with root privileges::
|
||||
:command:`pip` with root privileges::
|
||||
|
||||
$ sudo pip install Flask
|
||||
|
||||
(On Windows systems, run it in a command-prompt window with administrator
|
||||
privileges, and leave out `sudo`.)
|
||||
privileges, and leave out :command:`sudo`.)
|
||||
|
||||
|
||||
Living on the Edge
|
||||
------------------
|
||||
|
||||
If you want to work with the latest version of Flask, there are two ways: you
|
||||
can either let `pip` pull in the development version, or you can tell
|
||||
can either let :command:`pip` pull in the development version, or you can tell
|
||||
it to operate on a git checkout. Either way, virtualenv is recommended.
|
||||
|
||||
Get the git checkout in a new virtualenv and run in development mode::
|
||||
|
|
@ -157,14 +157,14 @@ you can upgrade them by running::
|
|||
|
||||
> pip install --upgrade pip setuptools
|
||||
|
||||
Most often, once you pull up a command prompt you want to be able to type ``pip``
|
||||
and ``python`` which will run those things, but this might not automatically happen
|
||||
Most often, once you pull up a command prompt you want to be able to type :command:`pip`
|
||||
and :command:`python` which will run those things, but this might not automatically happen
|
||||
on Windows, because it doesn't know where those executables are (give either a try!).
|
||||
|
||||
To fix this, you should be able to navigate to your Python install directory
|
||||
(e.g ``C:\Python27``), then go to ``Tools``, then ``Scripts``; then find the
|
||||
``win_add2path.py`` file and run that. Open a **new** Command Prompt and
|
||||
check that you can now just type ``python`` to bring up the interpreter.
|
||||
(e.g :file:`C:\Python27`), then go to :file:`Tools`, then :file:`Scripts`; then find the
|
||||
:file:`win_add2path.py` file and run that. Open a **new** Command Prompt and
|
||||
check that you can now just type :command:`python` to bring up the interpreter.
|
||||
|
||||
Finally, to install `virtualenv`_, you can simply run::
|
||||
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ Implementing API Exceptions
|
|||
It's very common to implement RESTful APIs on top of Flask. One of the
|
||||
first thing that developers run into is the realization that the builtin
|
||||
exceptions are not expressive enough for APIs and that the content type of
|
||||
``text/html`` they are emitting is not very useful for API consumers.
|
||||
:mimetype:`text/html` they are emitting is not very useful for API consumers.
|
||||
|
||||
The better solution than using ``abort`` to signal errors for invalid API
|
||||
usage is to implement your own exception type and install an error handler
|
||||
|
|
|
|||
|
|
@ -59,8 +59,8 @@ here is that each Flask application is a valid WSGI application and they
|
|||
are combined by the dispatcher middleware into a larger one that
|
||||
dispatched based on prefix.
|
||||
|
||||
For example you could have your main application run on `/` and your
|
||||
backend interface on `/backend`::
|
||||
For example you could have your main application run on ``/`` and your
|
||||
backend interface on ``/backend``::
|
||||
|
||||
from werkzeug.wsgi import DispatcherMiddleware
|
||||
from frontend_app import application as frontend
|
||||
|
|
@ -144,7 +144,7 @@ Dispatch by Path
|
|||
----------------
|
||||
|
||||
Dispatching by a path on the URL is very similar. Instead of looking at
|
||||
the `Host` header to figure out the subdomain one simply looks at the
|
||||
the ``Host`` header to figure out the subdomain one simply looks at the
|
||||
request path up to the first slash::
|
||||
|
||||
from threading import Lock
|
||||
|
|
@ -176,7 +176,7 @@ request path up to the first slash::
|
|||
return app(environ, start_response)
|
||||
|
||||
The big difference between this and the subdomain one is that this one
|
||||
falls back to another application if the creator function returns `None`::
|
||||
falls back to another application if the creator function returns ``None``::
|
||||
|
||||
from myapplication import create_app, default_app, get_user_for_prefix
|
||||
|
||||
|
|
|
|||
|
|
@ -60,9 +60,9 @@ Factories & Extensions
|
|||
It's preferable to create your extensions and app factories so that the
|
||||
extension object does not initially get bound to the application.
|
||||
|
||||
Using `Flask-SQLAlchemy <http://pythonhosted.org/Flask-SQLAlchemy/>`_,
|
||||
Using `Flask-SQLAlchemy <http://pythonhosted.org/Flask-SQLAlchemy/>`_,
|
||||
as an example, you should not do something along those lines::
|
||||
|
||||
|
||||
def create_app(config_filename):
|
||||
app = Flask(__name__)
|
||||
app.config.from_pyfile(config_filename)
|
||||
|
|
@ -72,7 +72,7 @@ as an example, you should not do something along those lines::
|
|||
But, rather, in model.py (or equivalent)::
|
||||
|
||||
db = SQLAlchemy()
|
||||
|
||||
|
||||
and in your application.py (or equivalent)::
|
||||
|
||||
def create_app(config_filename):
|
||||
|
|
@ -83,21 +83,21 @@ and in your application.py (or equivalent)::
|
|||
db.init_app(app)
|
||||
|
||||
Using this design pattern, no application-specific state is stored on the
|
||||
extension object, so one extension object can be used for multiple apps.
|
||||
extension object, so one extension object can be used for multiple apps.
|
||||
For more information about the design of extensions refer to :doc:`/extensiondev`.
|
||||
|
||||
Using Applications
|
||||
------------------
|
||||
|
||||
So to use such an application you then have to create the application
|
||||
first in a separate file otherwise the ``flask`` command won't be able
|
||||
to find it. Here an example `exampleapp.py` file that creates such
|
||||
first in a separate file otherwise the :command:`flask` command won't be able
|
||||
to find it. Here an example :file:`exampleapp.py` file that creates such
|
||||
an application::
|
||||
|
||||
from yourapplication import create_app
|
||||
app = create_app('/path/to/config.cfg')
|
||||
|
||||
It can then be used with the ``flask`` command::
|
||||
It can then be used with the :command:`flask` command::
|
||||
|
||||
flask --app=exampleapp run
|
||||
|
||||
|
|
|
|||
|
|
@ -50,7 +50,7 @@ operations: :meth:`~werkzeug.contrib.cache.BaseCache.get` and
|
|||
To get an item from the cache call
|
||||
:meth:`~werkzeug.contrib.cache.BaseCache.get` with a string as key name.
|
||||
If something is in the cache, it is returned. Otherwise that function
|
||||
will return `None`::
|
||||
will return ``None``::
|
||||
|
||||
rv = cache.get('my-item')
|
||||
|
||||
|
|
|
|||
|
|
@ -13,7 +13,7 @@ Installing Celery
|
|||
-----------------
|
||||
|
||||
Celery is on the Python Package Index (PyPI), so it can be installed with
|
||||
standard Python tools like ``pip`` or ``easy_install``::
|
||||
standard Python tools like :command:`pip` or :command:`easy_install`::
|
||||
|
||||
$ pip install celery
|
||||
|
||||
|
|
|
|||
|
|
@ -18,16 +18,16 @@ make larger applications easier to distribute:
|
|||
this system is the entry point support which allows one package to
|
||||
declare an "entry point" another package can hook into to extend the
|
||||
other package.
|
||||
- **installation manager**: `easy_install`, which comes with distribute
|
||||
- **installation manager**: :command:`easy_install`, which comes with distribute
|
||||
can install other libraries for you. You can also use `pip`_ which
|
||||
sooner or later will replace `easy_install` which does more than just
|
||||
sooner or later will replace :command:`easy_install` which does more than just
|
||||
installing packages for you.
|
||||
|
||||
Flask itself, and all the libraries you can find on the cheeseshop
|
||||
are distributed with either distribute, the older setuptools or distutils.
|
||||
|
||||
In this case we assume your application is called
|
||||
`yourapplication.py` and you are not using a module, but a :ref:`package
|
||||
:file:`yourapplication.py` and you are not using a module, but a :ref:`package
|
||||
<larger-applications>`. Distributing resources with standard modules is
|
||||
not supported by `distribute`_ so we will not bother with it. If you have
|
||||
not yet converted your application into a package, head over to the
|
||||
|
|
@ -48,7 +48,7 @@ run with your Python interpreter.
|
|||
Standard disclaimer applies: :ref:`you better use a virtualenv
|
||||
<virtualenv>`.
|
||||
|
||||
Your setup code always goes into a file named `setup.py` next to your
|
||||
Your setup code always goes into a file named :file:`setup.py` next to your
|
||||
application. The name of the file is only convention, but because
|
||||
everybody will look for a file with that name, you better not change it.
|
||||
|
||||
|
|
@ -56,7 +56,7 @@ Yes, even if you are using `distribute`, you are importing from a package
|
|||
called `setuptools`. `distribute` is fully backwards compatible with
|
||||
`setuptools`, so it also uses the same import name.
|
||||
|
||||
A basic `setup.py` file for a Flask application looks like this::
|
||||
A basic :file:`setup.py` file for a Flask application looks like this::
|
||||
|
||||
from setuptools import setup
|
||||
|
||||
|
|
@ -83,7 +83,7 @@ the `find_packages` function::
|
|||
|
||||
Most parameters to the `setup` function should be self explanatory,
|
||||
`include_package_data` and `zip_safe` might not be.
|
||||
`include_package_data` tells distribute to look for a `MANIFEST.in` file
|
||||
`include_package_data` tells distribute to look for a :file:`MANIFEST.in` file
|
||||
and install all the entries that match as package data. We will use this
|
||||
to distribute the static files and templates along with the Python module
|
||||
(see :ref:`distributing-resources`). The `zip_safe` flag can be used to
|
||||
|
|
@ -98,18 +98,18 @@ Distributing Resources
|
|||
----------------------
|
||||
|
||||
If you try to install the package you just created, you will notice that
|
||||
folders like `static` or `templates` are not installed for you. The
|
||||
folders like :file:`static` or :file:`templates` are not installed for you. The
|
||||
reason for this is that distribute does not know which files to add for
|
||||
you. What you should do, is to create a `MANIFEST.in` file next to your
|
||||
`setup.py` file. This file lists all the files that should be added to
|
||||
you. What you should do, is to create a :file:`MANIFEST.in` file next to your
|
||||
:file:`setup.py` file. This file lists all the files that should be added to
|
||||
your tarball::
|
||||
|
||||
recursive-include yourapplication/templates *
|
||||
recursive-include yourapplication/static *
|
||||
|
||||
Don't forget that even if you enlist them in your `MANIFEST.in` file, they
|
||||
Don't forget that even if you enlist them in your :file:`MANIFEST.in` file, they
|
||||
won't be installed for you unless you set the `include_package_data`
|
||||
parameter of the `setup` function to `True`!
|
||||
parameter of the `setup` function to ``True``!
|
||||
|
||||
|
||||
Declaring Dependencies
|
||||
|
|
@ -145,7 +145,7 @@ Installing / Developing
|
|||
-----------------------
|
||||
|
||||
To install your application (ideally into a virtualenv) just run the
|
||||
`setup.py` script with the `install` parameter. It will install your
|
||||
:file:`setup.py` script with the `install` parameter. It will install your
|
||||
application into the virtualenv's site-packages folder and also download
|
||||
and install all dependencies::
|
||||
|
||||
|
|
|
|||
|
|
@ -15,7 +15,7 @@ upfront:
|
|||
- Fabric 1.0 has to be installed locally. This tutorial assumes the
|
||||
latest version of Fabric.
|
||||
- The application already has to be a package and requires a working
|
||||
`setup.py` file (:ref:`distribute-deployment`).
|
||||
:file:`setup.py` file (:ref:`distribute-deployment`).
|
||||
- In the following example we are using `mod_wsgi` for the remote
|
||||
servers. You can of course use your own favourite server there, but
|
||||
for this example we chose Apache + `mod_wsgi` because it's very easy
|
||||
|
|
@ -25,7 +25,7 @@ upfront:
|
|||
Creating the first Fabfile
|
||||
--------------------------
|
||||
|
||||
A fabfile is what controls what Fabric executes. It is named `fabfile.py`
|
||||
A fabfile is what controls what Fabric executes. It is named :file:`fabfile.py`
|
||||
and executed by the `fab` command. All the functions defined in that file
|
||||
will show up as `fab` subcommands. They are executed on one or more
|
||||
hosts. These hosts can be defined either in the fabfile or on the command
|
||||
|
|
@ -72,7 +72,7 @@ a recap of the most common commands fabric provides:
|
|||
- `local` - executes a command on the local machine
|
||||
- `put` - uploads a file to the remote server
|
||||
- `cd` - changes the directory on the serverside. This has to be used
|
||||
in combination with the `with` statement.
|
||||
in combination with the ``with`` statement.
|
||||
|
||||
Running Fabfiles
|
||||
----------------
|
||||
|
|
@ -84,9 +84,9 @@ this command::
|
|||
$ fab pack deploy
|
||||
|
||||
However this requires that our server already has the
|
||||
``/var/www/yourapplication`` folder created and
|
||||
``/var/www/yourapplication/env`` to be a virtual environment. Furthermore
|
||||
are we not creating the configuration or `.wsgi` file on the server. So
|
||||
:file:`/var/www/yourapplication` folder created and
|
||||
:file:`/var/www/yourapplication/env` to be a virtual environment. Furthermore
|
||||
are we not creating the configuration or ``.wsgi`` file on the server. So
|
||||
how do we bootstrap a new server into our infrastructure?
|
||||
|
||||
This now depends on the number of servers we want to set up. If we just
|
||||
|
|
@ -100,22 +100,22 @@ command line::
|
|||
|
||||
To setup a new server you would roughly do these steps:
|
||||
|
||||
1. Create the directory structure in ``/var/www``::
|
||||
1. Create the directory structure in :file:`/var/www`::
|
||||
|
||||
$ mkdir /var/www/yourapplication
|
||||
$ cd /var/www/yourapplication
|
||||
$ virtualenv --distribute env
|
||||
|
||||
2. Upload a new `application.wsgi` file to the server and the
|
||||
configuration file for the application (eg: `application.cfg`)
|
||||
2. Upload a new :file:`application.wsgi` file to the server and the
|
||||
configuration file for the application (eg: :file:`application.cfg`)
|
||||
|
||||
3. Create a new Apache config for `yourapplication` and activate it.
|
||||
Make sure to activate watching for changes of the `.wsgi` file so
|
||||
3. Create a new Apache config for ``yourapplication`` and activate it.
|
||||
Make sure to activate watching for changes of the ``.wsgi`` file so
|
||||
that we can automatically reload the application by touching it.
|
||||
(See :ref:`mod_wsgi-deployment` for more information)
|
||||
|
||||
So now the question is, where do the `application.wsgi` and
|
||||
`application.cfg` files come from?
|
||||
So now the question is, where do the :file:`application.wsgi` and
|
||||
:file:`application.cfg` files come from?
|
||||
|
||||
The WSGI File
|
||||
-------------
|
||||
|
|
@ -142,7 +142,7 @@ The Configuration File
|
|||
----------------------
|
||||
|
||||
Now as mentioned above, the application will find the correct
|
||||
configuration file by looking up the `YOURAPPLICATION_CONFIG` environment
|
||||
configuration file by looking up the ``YOURAPPLICATION_CONFIG`` environment
|
||||
variable. So we have to put the configuration in a place where the
|
||||
application will able to find it. Configuration files have the unfriendly
|
||||
quality of being different on all computers, so you do not version them
|
||||
|
|
@ -151,7 +151,7 @@ usually.
|
|||
A popular approach is to store configuration files for different servers
|
||||
in a separate version control repository and check them out on all
|
||||
servers. Then symlink the file that is active for the server into the
|
||||
location where it's expected (eg: ``/var/www/yourapplication``).
|
||||
location where it's expected (eg: :file:`/var/www/yourapplication`).
|
||||
|
||||
Either way, in our case here we only expect one or two servers and we can
|
||||
upload them ahead of time by hand.
|
||||
|
|
@ -168,7 +168,7 @@ can pack up the application and deploy it::
|
|||
Fabric will now connect to all servers and run the commands as written
|
||||
down in the fabfile. First it will execute pack so that we have our
|
||||
tarball ready and then it will execute deploy and upload the source code
|
||||
to all servers and install it there. Thanks to the `setup.py` file we
|
||||
to all servers and install it there. Thanks to the :file:`setup.py` file we
|
||||
will automatically pull in the required libraries into our virtual
|
||||
environment.
|
||||
|
||||
|
|
|
|||
|
|
@ -32,8 +32,8 @@ bootstrapping code for our application::
|
|||
|
||||
So first we need a couple of imports. Most should be straightforward, the
|
||||
:func:`werkzeug.secure_filename` is explained a little bit later. The
|
||||
`UPLOAD_FOLDER` is where we will store the uploaded files and the
|
||||
`ALLOWED_EXTENSIONS` is the set of allowed file extensions. Then we add a
|
||||
``UPLOAD_FOLDER`` is where we will store the uploaded files and the
|
||||
``ALLOWED_EXTENSIONS`` is the set of allowed file extensions. Then we add a
|
||||
URL rule by hand to the application. Now usually we're not doing that, so
|
||||
why here? The reasons is that we want the webserver (or our development
|
||||
server) to serve these files for us and so we only need a rule to generate
|
||||
|
|
@ -43,7 +43,7 @@ Why do we limit the extensions that are allowed? You probably don't want
|
|||
your users to be able to upload everything there if the server is directly
|
||||
sending out the data to the client. That way you can make sure that users
|
||||
are not able to upload HTML files that would cause XSS problems (see
|
||||
:ref:`xss`). Also make sure to disallow `.php` files if the server
|
||||
:ref:`xss`). Also make sure to disallow ``.php`` files if the server
|
||||
executes them, but who has PHP installed on his server, right? :)
|
||||
|
||||
Next the functions that check if an extension is valid and that uploads
|
||||
|
|
@ -98,7 +98,7 @@ before storing it directly on the filesystem.
|
|||
filename = "../../../../home/username/.bashrc"
|
||||
|
||||
Assuming the number of ``../`` is correct and you would join this with
|
||||
the `UPLOAD_FOLDER` the user might have the ability to modify a file on
|
||||
the ``UPLOAD_FOLDER`` the user might have the ability to modify a file on
|
||||
the server's filesystem he or she should not modify. This does require some
|
||||
knowledge about how the application looks like, but trust me, hackers
|
||||
are patient :)
|
||||
|
|
|
|||
|
|
@ -38,7 +38,7 @@ So here is a full example::
|
|||
return redirect(url_for('index'))
|
||||
return render_template('login.html', error=error)
|
||||
|
||||
And here the ``layout.html`` template which does the magic:
|
||||
And here the :file:`layout.html` template which does the magic:
|
||||
|
||||
.. sourcecode:: html+jinja
|
||||
|
||||
|
|
|
|||
|
|
@ -19,7 +19,7 @@ Loading jQuery
|
|||
In order to use jQuery, you have to download it first and place it in the
|
||||
static folder of your application and then ensure it's loaded. Ideally
|
||||
you have a layout template that is used for all pages where you just have
|
||||
to add a script statement to the bottom of your `<body>` to load jQuery:
|
||||
to add a script statement to the bottom of your ``<body>`` to load jQuery:
|
||||
|
||||
.. sourcecode:: html
|
||||
|
||||
|
|
@ -65,12 +65,12 @@ like this:
|
|||
|
||||
The ``|safe`` is necessary in Flask before 0.10 so that Jinja does not
|
||||
escape the JSON encoded string with HTML rules. Usually this would be
|
||||
necessary, but we are inside a `script` block here where different rules
|
||||
necessary, but we are inside a ``script`` block here where different rules
|
||||
apply.
|
||||
|
||||
.. admonition:: Information for Pros
|
||||
|
||||
In HTML the `script` tag is declared `CDATA` which means that entities
|
||||
In HTML the ``script`` tag is declared ``CDATA`` which means that entities
|
||||
will not be parsed. Everything until ``</script>`` is handled as script.
|
||||
This also means that there must never be any ``</`` between the script
|
||||
tags. ``|tojson`` is kind enough to do the right thing here and
|
||||
|
|
@ -119,9 +119,9 @@ special error reporting in that case.
|
|||
The HTML
|
||||
--------
|
||||
|
||||
Your index.html template either has to extend a `layout.html` template with
|
||||
Your index.html template either has to extend a :file:`layout.html` template with
|
||||
jQuery loaded and the `$SCRIPT_ROOT` variable set, or do that on the top.
|
||||
Here's the HTML code needed for our little application (`index.html`).
|
||||
Here's the HTML code needed for our little application (:file:`index.html`).
|
||||
Notice that we also drop the script directly into the HTML here. It is
|
||||
usually a better idea to have that in a separate script file:
|
||||
|
||||
|
|
@ -156,7 +156,7 @@ explanation of the little bit of code above:
|
|||
when the user clicked on the element. If that function returns
|
||||
`false`, the default behavior will not kick in (in this case, navigate
|
||||
to the `#` URL).
|
||||
4. ``$.getJSON(url, data, func)`` sends a `GET` request to `url` and will
|
||||
4. ``$.getJSON(url, data, func)`` sends a ``GET`` request to `url` and will
|
||||
send the contents of the `data` object as query parameters. Once the
|
||||
data arrived, it will call the given function with the return value as
|
||||
argument. Note that we can use the `$SCRIPT_ROOT` variable here that
|
||||
|
|
|
|||
|
|
@ -33,7 +33,7 @@ Imagine the current application looks somewhat like this::
|
|||
pass
|
||||
|
||||
Then the centralized approach you would have one file with the views
|
||||
(`views.py`) but without any decorator::
|
||||
(:file:`views.py`) but without any decorator::
|
||||
|
||||
def index():
|
||||
pass
|
||||
|
|
|
|||
|
|
@ -20,7 +20,7 @@ Declarative
|
|||
The default behavior of MongoKit is the declarative one that is based on
|
||||
common ideas from Django or the SQLAlchemy declarative extension.
|
||||
|
||||
Here an example `app.py` module for your application::
|
||||
Here an example :file:`app.py` module for your application::
|
||||
|
||||
from flask import Flask
|
||||
from mongokit import Connection, Document
|
||||
|
|
@ -47,7 +47,7 @@ MongoDB is schemaless. This means you can modify the data structure from one
|
|||
insert query to the next without any problem. MongoKit is just schemaless
|
||||
too, but implements some validation to ensure data integrity.
|
||||
|
||||
Here is an example document (put this also into `app.py`, e.g.)::
|
||||
Here is an example document (put this also into :file:`app.py`, e.g.)::
|
||||
|
||||
def max_length(length):
|
||||
def validate(value):
|
||||
|
|
@ -76,7 +76,7 @@ Here is an example document (put this also into `app.py`, e.g.)::
|
|||
This example shows you how to define your schema (named structure), a
|
||||
validator for the maximum character length and uses a special MongoKit feature
|
||||
called `use_dot_notation`. Per default MongoKit behaves like a python
|
||||
dictionary but with `use_dot_notation` set to `True` you can use your
|
||||
dictionary but with `use_dot_notation` set to ``True`` you can use your
|
||||
documents like you use models in nearly any other ORM by using dots to
|
||||
separate between attributes.
|
||||
|
||||
|
|
|
|||
|
|
@ -21,9 +21,9 @@ Simple Packages
|
|||
---------------
|
||||
|
||||
To convert that into a larger one, just create a new folder
|
||||
`yourapplication` inside the existing one and move everything below it.
|
||||
Then rename `yourapplication.py` to `__init__.py`. (Make sure to delete
|
||||
all `.pyc` files first, otherwise things would most likely break)
|
||||
:file:`yourapplication` inside the existing one and move everything below it.
|
||||
Then rename :file:`yourapplication.py` to :file:`__init__.py`. (Make sure to delete
|
||||
all ``.pyc`` files first, otherwise things would most likely break)
|
||||
|
||||
You should then end up with something like that::
|
||||
|
||||
|
|
@ -41,8 +41,8 @@ You should then end up with something like that::
|
|||
But how do you run your application now? The naive ``python
|
||||
yourapplication/__init__.py`` will not work. Let's just say that Python
|
||||
does not want modules in packages to be the startup file. But that is not
|
||||
a big problem, just add a new file called `runserver.py` next to the inner
|
||||
`yourapplication` folder with the following contents::
|
||||
a big problem, just add a new file called :file:`runserver.py` next to the inner
|
||||
:file:`yourapplication` folder with the following contents::
|
||||
|
||||
from yourapplication import app
|
||||
app.run(debug=True)
|
||||
|
|
@ -52,21 +52,21 @@ into multiple modules. The only thing you have to remember is the
|
|||
following quick checklist:
|
||||
|
||||
1. the `Flask` application object creation has to be in the
|
||||
`__init__.py` file. That way each module can import it safely and the
|
||||
:file:`__init__.py` file. That way each module can import it safely and the
|
||||
`__name__` variable will resolve to the correct package.
|
||||
2. all the view functions (the ones with a :meth:`~flask.Flask.route`
|
||||
decorator on top) have to be imported in the `__init__.py` file.
|
||||
decorator on top) have to be imported in the :file:`__init__.py` file.
|
||||
Not the object itself, but the module it is in. Import the view module
|
||||
**after the application object is created**.
|
||||
|
||||
Here's an example `__init__.py`::
|
||||
Here's an example :file:`__init__.py`::
|
||||
|
||||
from flask import Flask
|
||||
app = Flask(__name__)
|
||||
|
||||
import yourapplication.views
|
||||
|
||||
And this is what `views.py` would look like::
|
||||
And this is what :file:`views.py` would look like::
|
||||
|
||||
from yourapplication import app
|
||||
|
||||
|
|
@ -93,9 +93,9 @@ You should then end up with something like that::
|
|||
|
||||
Every Python programmer hates them, and yet we just added some:
|
||||
circular imports (That's when two modules depend on each other. In this
|
||||
case `views.py` depends on `__init__.py`). Be advised that this is a
|
||||
case :file:`views.py` depends on :file:`__init__.py`). Be advised that this is a
|
||||
bad idea in general but here it is actually fine. The reason for this is
|
||||
that we are not actually using the views in `__init__.py` and just
|
||||
that we are not actually using the views in :file:`__init__.py` and just
|
||||
ensuring the module is imported and we are doing that at the bottom of
|
||||
the file.
|
||||
|
||||
|
|
|
|||
|
|
@ -33,7 +33,7 @@ SQLAlchemy. It allows you to define tables and models in one go, similar
|
|||
to how Django works. In addition to the following text I recommend the
|
||||
official documentation on the `declarative`_ extension.
|
||||
|
||||
Here the example `database.py` module for your application::
|
||||
Here the example :file:`database.py` module for your application::
|
||||
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import scoped_session, sessionmaker
|
||||
|
|
@ -70,7 +70,7 @@ when the application shuts down::
|
|||
def shutdown_session(exception=None):
|
||||
db_session.remove()
|
||||
|
||||
Here is an example model (put this into `models.py`, e.g.)::
|
||||
Here is an example model (put this into :file:`models.py`, e.g.)::
|
||||
|
||||
from sqlalchemy import Column, Integer, String
|
||||
from yourapplication.database import Base
|
||||
|
|
@ -122,7 +122,7 @@ flexible but a little more to type. In general it works like the
|
|||
declarative approach, so make sure to also split up your application into
|
||||
multiple modules in a package.
|
||||
|
||||
Here is an example `database.py` module for your application::
|
||||
Here is an example :file:`database.py` module for your application::
|
||||
|
||||
from sqlalchemy import create_engine, MetaData
|
||||
from sqlalchemy.orm import scoped_session, sessionmaker
|
||||
|
|
@ -145,7 +145,7 @@ application module::
|
|||
def shutdown_session(exception=None):
|
||||
db_session.remove()
|
||||
|
||||
Here is an example table and model (put this into `models.py`)::
|
||||
Here is an example table and model (put this into :file:`models.py`)::
|
||||
|
||||
from sqlalchemy import Table, Column, Integer, String
|
||||
from sqlalchemy.orm import mapper
|
||||
|
|
|
|||
|
|
@ -14,7 +14,7 @@ with an example.
|
|||
Base Template
|
||||
-------------
|
||||
|
||||
This template, which we'll call ``layout.html``, defines a simple HTML skeleton
|
||||
This template, which we'll call :file:`layout.html`, defines a simple HTML skeleton
|
||||
document that you might use for a simple two-column page. It's the job of
|
||||
"child" templates to fill the empty blocks with content:
|
||||
|
||||
|
|
|
|||
|
|
@ -23,7 +23,7 @@ often forgotten, but you don't have to do that by hand, there is a
|
|||
function for that that is used like a decorator (:func:`functools.wraps`).
|
||||
|
||||
This example assumes that the login page is called ``'login'`` and that
|
||||
the current user is stored as `g.user` and `None` if there is no-one
|
||||
the current user is stored as `g.user` and ``None`` if there is no-one
|
||||
logged in::
|
||||
|
||||
from functools import wraps
|
||||
|
|
@ -120,7 +120,7 @@ As you can see, if no template name is provided it will use the endpoint
|
|||
of the URL map with dots converted to slashes + ``'.html'``. Otherwise
|
||||
the provided template name is used. When the decorated function returns,
|
||||
the dictionary returned is passed to the template rendering function. If
|
||||
`None` is returned, an empty dictionary is assumed, if something else than
|
||||
``None`` is returned, an empty dictionary is assumed, if something else than
|
||||
a dictionary is returned we return it from the function unchanged. That
|
||||
way you can still use the redirect function or return simple strings.
|
||||
|
||||
|
|
@ -151,15 +151,15 @@ Endpoint Decorator
|
|||
------------------
|
||||
|
||||
When you want to use the werkzeug routing system for more flexibility you
|
||||
need to map the endpoint as defined in the :class:`~werkzeug.routing.Rule`
|
||||
to a view function. This is possible with this decorator. For example::
|
||||
need to map the endpoint as defined in the :class:`~werkzeug.routing.Rule`
|
||||
to a view function. This is possible with this decorator. For example::
|
||||
|
||||
from flask import Flask
|
||||
from werkzeug.routing import Rule
|
||||
|
||||
app = Flask(__name__)
|
||||
app.url_map.add(Rule('/', endpoint='index'))
|
||||
app = Flask(__name__)
|
||||
app.url_map.add(Rule('/', endpoint='index'))
|
||||
|
||||
@app.endpoint('index')
|
||||
def my_index():
|
||||
return "Hello world"
|
||||
@app.endpoint('index')
|
||||
def my_index():
|
||||
return "Hello world"
|
||||
|
|
|
|||
|
|
@ -61,10 +61,10 @@ the code as necessary.
|
|||
Things to remember:
|
||||
|
||||
1. create the form from the request :attr:`~flask.request.form` value if
|
||||
the data is submitted via the HTTP `POST` method and
|
||||
:attr:`~flask.request.args` if the data is submitted as `GET`.
|
||||
the data is submitted via the HTTP ``POST`` method and
|
||||
:attr:`~flask.request.args` if the data is submitted as ``GET``.
|
||||
2. to validate the data, call the :func:`~wtforms.form.Form.validate`
|
||||
method which will return `True` if the data validates, `False`
|
||||
method which will return ``True`` if the data validates, ``False``
|
||||
otherwise.
|
||||
3. to access individual values from the form, access `form.<NAME>.data`.
|
||||
|
||||
|
|
@ -77,7 +77,7 @@ how easy this is. WTForms does half the form generation for us already.
|
|||
To make it even nicer, we can write a macro that renders a field with
|
||||
label and a list of errors if there are any.
|
||||
|
||||
Here's an example `_formhelpers.html` template with such a macro:
|
||||
Here's an example :file:`_formhelpers.html` template with such a macro:
|
||||
|
||||
.. sourcecode:: html+jinja
|
||||
|
||||
|
|
@ -100,10 +100,10 @@ arguments will be inserted as HTML attributes. So for example you can
|
|||
call ``render_field(form.username, class='username')`` to add a class to
|
||||
the input element. Note that WTForms returns standard Python unicode
|
||||
strings, so we have to tell Jinja2 that this data is already HTML escaped
|
||||
with the `|safe` filter.
|
||||
with the ``|safe`` filter.
|
||||
|
||||
Here the `register.html` template for the function we used above which
|
||||
takes advantage of the `_formhelpers.html` template:
|
||||
Here the :file:`register.html` template for the function we used above which
|
||||
takes advantage of the :file:`_formhelpers.html` template:
|
||||
|
||||
.. sourcecode:: html+jinja
|
||||
|
||||
|
|
|
|||
|
|
@ -20,12 +20,12 @@ A minimal Flask application looks something like this::
|
|||
def hello_world():
|
||||
return 'Hello World!'
|
||||
|
||||
Just save it as `hello.py` (or something similar) and run it with your Python
|
||||
interpreter. Make sure to not call your application `flask.py` because this
|
||||
Just save it as :file:`hello.py` (or something similar) and run it with your Python
|
||||
interpreter. Make sure to not call your application :file:`flask.py` because this
|
||||
would conflict with Flask itself.
|
||||
|
||||
To run the application you can either use the ``flask`` command or
|
||||
python's ``-m`` switch with Flask::
|
||||
To run the application you can either use the :command:`flask` command or
|
||||
python's :option:`-m` switch with Flask::
|
||||
|
||||
$ flask -a hello run
|
||||
* Running on http://127.0.0.1:5000/
|
||||
|
|
@ -79,7 +79,7 @@ To stop the server, hit control-C.
|
|||
What to do if the Server does not Start
|
||||
---------------------------------------
|
||||
|
||||
In case the ``python -m flask`` fails or ``flask`` does not exist,
|
||||
In case the ``python -m flask`` fails or :command:`flask` does not exist,
|
||||
there are multiple reasons this might be the case. First of all you need
|
||||
to look at the error message.
|
||||
|
||||
|
|
@ -87,7 +87,7 @@ Old Version of Flask
|
|||
````````````````````
|
||||
|
||||
Versions of Flask older than 1.0 use to have different ways to start the
|
||||
application. In short, the ``flask`` command did not exist, and
|
||||
application. In short, the :command:`flask` command did not exist, and
|
||||
neither did ``python -m flask``. In that case you have two options:
|
||||
either upgrade to newer Flask versions or have a look at the :ref:`server`
|
||||
docs to see the alternative method for running a server.
|
||||
|
|
@ -96,7 +96,7 @@ Python older 2.7
|
|||
````````````````
|
||||
|
||||
In case you have a version of Python older than 2.7 ``python -m flask``
|
||||
does not work. You can either use ``flask`` or ``python -m
|
||||
does not work. You can either use :command:`flask` or ``python -m
|
||||
flask.cli`` as an alternative. This is because Python before 2.7 does no
|
||||
permit packages to act as executable modules. For more information see
|
||||
:ref:`cli`.
|
||||
|
|
@ -104,7 +104,7 @@ permit packages to act as executable modules. For more information see
|
|||
Invalid Import Name
|
||||
```````````````````
|
||||
|
||||
The ``-a`` argument to ``flask`` is the name of the module to import. In
|
||||
The :option:`-a` argument to :command:`flask` is the name of the module to import. In
|
||||
case that module is incorrectly named you will get an import error upon
|
||||
start (or if debug is enabled when you navigate to the application). It
|
||||
will tell you what it tried to import and why it failed.
|
||||
|
|
@ -117,14 +117,14 @@ The most common reason is a typo or because you did not actually create an
|
|||
Debug Mode
|
||||
----------
|
||||
|
||||
The ``flask`` script is nice to start a local development server, but
|
||||
The :command:`flask` script is nice to start a local development server, but
|
||||
you would have to restart it manually after each change to your code.
|
||||
That is not very nice and Flask can do better. If you enable debug
|
||||
support the server will reload itself on code changes, and it will also
|
||||
provide you with a helpful debugger if things go wrong.
|
||||
|
||||
There are different ways to enable the debug mode. The most obvious one
|
||||
is the ``--debug`` parameter to the ``flask`` command::
|
||||
is the :option:`--debug` parameter to the :command:`flask` command::
|
||||
|
||||
flask --debug -a hello run
|
||||
|
||||
|
|
@ -292,7 +292,7 @@ HTTP Methods
|
|||
````````````
|
||||
|
||||
HTTP (the protocol web applications are speaking) knows different methods for
|
||||
accessing URLs. By default, a route only answers to `GET` requests, but that
|
||||
accessing URLs. By default, a route only answers to ``GET`` requests, but that
|
||||
can be changed by providing the `methods` argument to the
|
||||
:meth:`~flask.Flask.route` decorator. Here are some examples::
|
||||
|
||||
|
|
@ -305,11 +305,11 @@ can be changed by providing the `methods` argument to the
|
|||
else:
|
||||
show_the_login_form()
|
||||
|
||||
If `GET` is present, `HEAD` will be added automatically for you. You
|
||||
don't have to deal with that. It will also make sure that `HEAD` requests
|
||||
If ``GET`` is present, ``HEAD`` will be added automatically for you. You
|
||||
don't have to deal with that. It will also make sure that ``HEAD`` requests
|
||||
are handled as the `HTTP RFC`_ (the document describing the HTTP
|
||||
protocol) demands, so you can completely ignore that part of the HTTP
|
||||
specification. Likewise, as of Flask 0.6, `OPTIONS` is implemented for you
|
||||
specification. Likewise, as of Flask 0.6, ``OPTIONS`` is implemented for you
|
||||
automatically as well.
|
||||
|
||||
You have no idea what an HTTP method is? Worry not, here is a quick
|
||||
|
|
@ -319,44 +319,44 @@ The HTTP method (also often called "the verb") tells the server what the
|
|||
clients wants to *do* with the requested page. The following methods are
|
||||
very common:
|
||||
|
||||
`GET`
|
||||
``GET``
|
||||
The browser tells the server to just *get* the information stored on
|
||||
that page and send it. This is probably the most common method.
|
||||
|
||||
`HEAD`
|
||||
``HEAD``
|
||||
The browser tells the server to get the information, but it is only
|
||||
interested in the *headers*, not the content of the page. An
|
||||
application is supposed to handle that as if a `GET` request was
|
||||
application is supposed to handle that as if a ``GET`` request was
|
||||
received but to not deliver the actual content. In Flask you don't
|
||||
have to deal with that at all, the underlying Werkzeug library handles
|
||||
that for you.
|
||||
|
||||
`POST`
|
||||
``POST``
|
||||
The browser tells the server that it wants to *post* some new
|
||||
information to that URL and that the server must ensure the data is
|
||||
stored and only stored once. This is how HTML forms usually
|
||||
transmit data to the server.
|
||||
|
||||
`PUT`
|
||||
Similar to `POST` but the server might trigger the store procedure
|
||||
``PUT``
|
||||
Similar to ``POST`` but the server might trigger the store procedure
|
||||
multiple times by overwriting the old values more than once. Now you
|
||||
might be asking why this is useful, but there are some good reasons
|
||||
to do it this way. Consider that the connection is lost during
|
||||
transmission: in this situation a system between the browser and the
|
||||
server might receive the request safely a second time without breaking
|
||||
things. With `POST` that would not be possible because it must only
|
||||
things. With ``POST`` that would not be possible because it must only
|
||||
be triggered once.
|
||||
|
||||
`DELETE`
|
||||
``DELETE``
|
||||
Remove the information at the given location.
|
||||
|
||||
`OPTIONS`
|
||||
``OPTIONS``
|
||||
Provides a quick way for a client to figure out which methods are
|
||||
supported by this URL. Starting with Flask 0.6, this is implemented
|
||||
for you automatically.
|
||||
|
||||
Now the interesting part is that in HTML4 and XHTML1, the only methods a
|
||||
form can submit to the server are `GET` and `POST`. But with JavaScript
|
||||
form can submit to the server are ``GET`` and ``POST``. But with JavaScript
|
||||
and future HTML standards you can use the other methods as well. Furthermore
|
||||
HTTP has become quite popular lately and browsers are no longer the only
|
||||
clients that are using HTTP. For instance, many revision control systems
|
||||
|
|
@ -370,14 +370,14 @@ Static Files
|
|||
Dynamic web applications also need static files. That's usually where
|
||||
the CSS and JavaScript files are coming from. Ideally your web server is
|
||||
configured to serve them for you, but during development Flask can do that
|
||||
as well. Just create a folder called `static` in your package or next to
|
||||
your module and it will be available at `/static` on the application.
|
||||
as well. Just create a folder called :file:`static` in your package or next to
|
||||
your module and it will be available at ``/static`` on the application.
|
||||
|
||||
To generate URLs for static files, use the special ``'static'`` endpoint name::
|
||||
|
||||
url_for('static', filename='style.css')
|
||||
|
||||
The file has to be stored on the filesystem as ``static/style.css``.
|
||||
The file has to be stored on the filesystem as :file:`static/style.css`.
|
||||
|
||||
Rendering Templates
|
||||
-------------------
|
||||
|
|
@ -399,7 +399,7 @@ Here's a simple example of how to render a template::
|
|||
def hello(name=None):
|
||||
return render_template('hello.html', name=name)
|
||||
|
||||
Flask will look for templates in the `templates` folder. So if your
|
||||
Flask will look for templates in the :file:`templates` folder. So if your
|
||||
application is a module, this folder is next to that module, if it's a
|
||||
package it's actually inside your package:
|
||||
|
||||
|
|
@ -510,7 +510,7 @@ will notice that code which depends on a request object will suddenly break
|
|||
because there is no request object. The solution is creating a request
|
||||
object yourself and binding it to the context. The easiest solution for
|
||||
unit testing is to use the :meth:`~flask.Flask.test_request_context`
|
||||
context manager. In combination with the `with` statement it will bind a
|
||||
context manager. In combination with the ``with`` statement it will bind a
|
||||
test request so that you can interact with it. Here is an example::
|
||||
|
||||
from flask import request
|
||||
|
|
@ -541,7 +541,7 @@ the `flask` module::
|
|||
|
||||
The current request method is available by using the
|
||||
:attr:`~flask.request.method` attribute. To access form data (data
|
||||
transmitted in a `POST` or `PUT` request) you can use the
|
||||
transmitted in a ``POST`` or ``PUT`` request) you can use the
|
||||
:attr:`~flask.request.form` attribute. Here is a full example of the two
|
||||
attributes mentioned above::
|
||||
|
||||
|
|
@ -570,7 +570,7 @@ To access parameters submitted in the URL (``?key=value``) you can use the
|
|||
searchword = request.args.get('key', '')
|
||||
|
||||
We recommend accessing URL parameters with `get` or by catching the
|
||||
`KeyError` because users might change the URL and presenting them a 400
|
||||
:exc:`KeyError` because users might change the URL and presenting them a 400
|
||||
bad request page in that case is not user friendly.
|
||||
|
||||
For a full list of methods and attributes of the request object, head over
|
||||
|
|
@ -708,7 +708,7 @@ About Responses
|
|||
The return value from a view function is automatically converted into a
|
||||
response object for you. If the return value is a string it's converted
|
||||
into a response object with the string as response body, a ``200 OK``
|
||||
status code and a ``text/html`` mimetype. The logic that Flask applies to
|
||||
status code and a :mimetype:`text/html` mimetype. The logic that Flask applies to
|
||||
converting return values into response objects is as follows:
|
||||
|
||||
1. If a response object of the correct type is returned it's directly
|
||||
|
|
|
|||
|
|
@ -37,7 +37,7 @@ us a :class:`~flask.ctx.RequestContext`:
|
|||
|
||||
>>> ctx = app.test_request_context('/?next=http://example.com/')
|
||||
|
||||
This context can be used in two ways. Either with the `with` statement
|
||||
This context can be used in two ways. Either with the ``with`` statement
|
||||
or by calling the :meth:`~flask.ctx.RequestContext.push` and
|
||||
:meth:`~flask.ctx.RequestContext.pop` methods:
|
||||
|
||||
|
|
@ -75,8 +75,8 @@ find a piece of code that looks very much like this::
|
|||
|
||||
The method :meth:`~Flask.request_context` returns a new
|
||||
:class:`~flask.ctx.RequestContext` object and uses it in combination with
|
||||
the `with` statement to bind the context. Everything that is called from
|
||||
the same thread from this point onwards until the end of the `with`
|
||||
the ``with`` statement to bind the context. Everything that is called from
|
||||
the same thread from this point onwards until the end of the ``with``
|
||||
statement will have access to the request globals (:data:`flask.request`
|
||||
and others).
|
||||
|
||||
|
|
|
|||
|
|
@ -25,7 +25,7 @@ careful:
|
|||
- generating HTML without the help of Jinja2
|
||||
- calling :class:`~flask.Markup` on data submitted by users
|
||||
- sending out HTML from uploaded files, never do that, use the
|
||||
`Content-Disposition: attachment` header to prevent that problem.
|
||||
``Content-Disposition: attachment`` header to prevent that problem.
|
||||
- sending out textfiles from uploaded files. Some browsers are using
|
||||
content-type guessing based on the first few bytes so users could
|
||||
trick a browser to execute HTML.
|
||||
|
|
@ -70,8 +70,8 @@ don't keep that in mind, some people might be able to trick your
|
|||
application's users with social engineering to do stupid things without
|
||||
them knowing.
|
||||
|
||||
Say you have a specific URL that, when you sent `POST` requests to will
|
||||
delete a user's profile (say `http://example.com/user/delete`). If an
|
||||
Say you have a specific URL that, when you sent ``POST`` requests to will
|
||||
delete a user's profile (say ``http://example.com/user/delete``). If an
|
||||
attacker now creates a page that sends a post request to that page with
|
||||
some JavaScript they just has to trick some users to load that page and
|
||||
their profiles will end up being deleted.
|
||||
|
|
@ -130,7 +130,7 @@ Not very uncommon:
|
|||
]
|
||||
|
||||
And it is doing that of course only as long as you are logged in and only
|
||||
for you. And it is doing that for all `GET` requests to a certain URL,
|
||||
for you. And it is doing that for all ``GET`` requests to a certain URL,
|
||||
say the URL for that request is
|
||||
``http://example.com/api/get_friends.json``.
|
||||
|
||||
|
|
@ -161,8 +161,8 @@ and social engineers a victim to visiting his site:
|
|||
If you know a bit of JavaScript internals you might know that it's
|
||||
possible to patch constructors and register callbacks for setters. An
|
||||
attacker can use this (like above) to get all the data you exported in
|
||||
your JSON file. The browser will totally ignore the ``application/json``
|
||||
mimetype if ``text/javascript`` is defined as content type in the script
|
||||
your JSON file. The browser will totally ignore the :mimetype:`application/json`
|
||||
mimetype if :mimetype:`text/javascript` is defined as content type in the script
|
||||
tag and evaluate that as JavaScript. Because top-level array elements are
|
||||
allowed (albeit useless) and we hooked in our own constructor, after that
|
||||
page loaded the data from the JSON response is in the `captured` array.
|
||||
|
|
|
|||
|
|
@ -6,19 +6,19 @@ Development Server
|
|||
.. currentmodule:: flask
|
||||
|
||||
Starting with Flask 1.0 there are multiple built-in ways to run a
|
||||
development server. The best one is the ``flask`` command line utility
|
||||
development server. The best one is the :command:`flask` command line utility
|
||||
but you can also continue using the :meth:`Flask.run` method.
|
||||
|
||||
Command Line
|
||||
------------
|
||||
|
||||
The ``flask`` command line script (:ref:`cli`) is strongly recommende for
|
||||
The :command:`flask` command line script (:ref:`cli`) is strongly recommende for
|
||||
development because it provides a superior reload experience due to how it
|
||||
loads the application. The basic usage is like this::
|
||||
|
||||
$ flask -a my_application --debug run
|
||||
|
||||
This will enable the debugger, the reloader and then start the server on
|
||||
This will enable the debugger, the reloader and then start the server on
|
||||
*http://localhost:5000/*.
|
||||
|
||||
The individual features of the server can be controlled by passing more
|
||||
|
|
@ -32,7 +32,7 @@ In Code
|
|||
|
||||
The alternative way to start the application is through the
|
||||
:meth:`Flask.run` method. This will immediately launch a local server
|
||||
exactly the same way the ``flask`` script does.
|
||||
exactly the same way the :command:`flask` script does.
|
||||
|
||||
Example::
|
||||
|
||||
|
|
@ -40,7 +40,7 @@ Example::
|
|||
app.run()
|
||||
|
||||
This works well for the common case but it does not work well for
|
||||
development which is why from Flask 1.0 onwards the ``flask`` method is
|
||||
development which is why from Flask 1.0 onwards the :command:`flask` method is
|
||||
recommended. The reason for this is that due to how the reload mechanism
|
||||
works there are some bizarre side-effects (like executing certain code
|
||||
twice, sometimes crashing without message or dying when a syntax or
|
||||
|
|
|
|||
|
|
@ -45,7 +45,7 @@ us a :class:`~flask.ctx.RequestContext`:
|
|||
|
||||
>>> ctx = app.test_request_context()
|
||||
|
||||
Normally you would use the `with` statement to make this request object
|
||||
Normally you would use the ``with`` statement to make this request object
|
||||
active, but in the shell it's easier to use the
|
||||
:meth:`~flask.ctx.RequestContext.push` and
|
||||
:meth:`~flask.ctx.RequestContext.pop` methods by hand:
|
||||
|
|
|
|||
|
|
@ -77,7 +77,7 @@ Make sure to subscribe with an extra ``**extra`` argument so that your
|
|||
calls don't fail if Flask introduces new arguments to the signals.
|
||||
|
||||
All the template rendering in the code issued by the application `app`
|
||||
in the body of the `with` block will now be recorded in the `templates`
|
||||
in the body of the ``with`` block will now be recorded in the `templates`
|
||||
variable. Whenever a template is rendered, the template object as well as
|
||||
context are appended to it.
|
||||
|
||||
|
|
@ -148,7 +148,7 @@ signal subscribers::
|
|||
model_saved.send(self)
|
||||
|
||||
Try to always pick a good sender. If you have a class that is emitting a
|
||||
signal, pass `self` as sender. If you are emitting a signal from a random
|
||||
signal, pass ``self`` as sender. If you are emitting a signal from a random
|
||||
function, you can pass ``current_app._get_current_object()`` as sender.
|
||||
|
||||
.. admonition:: Passing Proxies as Senders
|
||||
|
|
|
|||
|
|
@ -108,7 +108,7 @@ Comparisons:
|
|||
- against arbitrary types: ``==`` and ``!=``
|
||||
- against singletons with ``is`` and ``is not`` (eg: ``foo is not
|
||||
None``)
|
||||
- never compare something with `True` or `False` (for example never
|
||||
- never compare something with ``True`` or ``False`` (for example never
|
||||
do ``foo == False``, do ``not foo`` instead)
|
||||
|
||||
Negated containment checks:
|
||||
|
|
|
|||
|
|
@ -105,9 +105,9 @@ by Jinja2 itself:
|
|||
is for example very helpful if you try to generate JavaScript on the
|
||||
fly.
|
||||
|
||||
Note that inside `script` tags no escaping must take place, so make
|
||||
Note that inside ``script`` tags no escaping must take place, so make
|
||||
sure to disable escaping with ``|safe`` before Flask 0.10 if you intend
|
||||
to use it inside `script` tags:
|
||||
to use it inside ``script`` tags:
|
||||
|
||||
.. sourcecode:: html+jinja
|
||||
|
||||
|
|
|
|||
|
|
@ -30,7 +30,7 @@ The Testing Skeleton
|
|||
--------------------
|
||||
|
||||
In order to test the application, we add a second module
|
||||
(`flaskr_tests.py`) and create a unittest skeleton there::
|
||||
(:file:`flaskr_tests.py`) and create a unittest skeleton there::
|
||||
|
||||
import os
|
||||
import flaskr
|
||||
|
|
@ -112,7 +112,7 @@ test method to our class, like this::
|
|||
Notice that our test functions begin with the word `test`; this allows
|
||||
:mod:`unittest` to automatically identify the method as a test to run.
|
||||
|
||||
By using `self.app.get` we can send an HTTP `GET` request to the application with
|
||||
By using `self.app.get` we can send an HTTP ``GET`` request to the application with
|
||||
the given path. The return value will be a :class:`~flask.Flask.response_class` object.
|
||||
We can now use the :attr:`~werkzeug.wrappers.BaseResponse.data` attribute to inspect
|
||||
the return value (as string) from the application. In this case, we ensure that
|
||||
|
|
@ -202,7 +202,7 @@ Other Testing Tricks
|
|||
|
||||
Besides using the test client as shown above, there is also the
|
||||
:meth:`~flask.Flask.test_request_context` method that can be used
|
||||
in combination with the `with` statement to activate a request context
|
||||
in combination with the ``with`` statement to activate a request context
|
||||
temporarily. With this you can access the :class:`~flask.request`,
|
||||
:class:`~flask.g` and :class:`~flask.session` objects like in view
|
||||
functions. Here is a full example that demonstrates this approach::
|
||||
|
|
@ -224,7 +224,7 @@ Note however that if you are using a test request context, the
|
|||
:meth:`~flask.Flask.before_request` functions are not automatically called
|
||||
same for :meth:`~flask.Flask.after_request` functions. However
|
||||
:meth:`~flask.Flask.teardown_request` functions are indeed executed when
|
||||
the test request context leaves the `with` block. If you do want the
|
||||
the test request context leaves the ``with`` block. If you do want the
|
||||
:meth:`~flask.Flask.before_request` functions to be called as well, you
|
||||
need to call :meth:`~flask.Flask.preprocess_request` yourself::
|
||||
|
||||
|
|
@ -308,7 +308,7 @@ Keeping the Context Around
|
|||
Sometimes it is helpful to trigger a regular request but still keep the
|
||||
context around for a little longer so that additional introspection can
|
||||
happen. With Flask 0.4 this is possible by using the
|
||||
:meth:`~flask.Flask.test_client` with a `with` block::
|
||||
:meth:`~flask.Flask.test_client` with a ``with`` block::
|
||||
|
||||
app = flask.Flask(__name__)
|
||||
|
||||
|
|
@ -317,7 +317,7 @@ happen. With Flask 0.4 this is possible by using the
|
|||
assert request.args['tequila'] == '42'
|
||||
|
||||
If you were to use just the :meth:`~flask.Flask.test_client` without
|
||||
the `with` block, the `assert` would fail with an error because `request`
|
||||
the ``with`` block, the ``assert`` would fail with an error because `request`
|
||||
is no longer available (because you are trying to use it outside of the actual request).
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ Step 7: Adding Style
|
|||
====================
|
||||
|
||||
Now that everything else works, it's time to add some style to the
|
||||
application. Just create a stylesheet called `style.css` in the `static`
|
||||
application. Just create a stylesheet called :file:`style.css` in the :file:`static`
|
||||
folder we created before:
|
||||
|
||||
.. sourcecode:: css
|
||||
|
|
|
|||
|
|
@ -53,7 +53,7 @@ every time the app context tears down. So what does this mean?
|
|||
Essentially the app context is created before the request comes in and is
|
||||
destroyed (torn down) whenever the request finishes. A teardown can
|
||||
happen because of two reasons: either everything went well (the error
|
||||
parameter will be `None`) or an exception happened in which case the error
|
||||
parameter will be ``None``) or an exception happened in which case the error
|
||||
is passed to the teardown function.
|
||||
|
||||
Curious about what these contexts mean? Have a look at the
|
||||
|
|
|
|||
|
|
@ -20,9 +20,9 @@ requires that we provide the path to the database which can introduce
|
|||
errors. It's a good idea to add a function that initializes the database
|
||||
for you to the application.
|
||||
|
||||
To do this we can create a function and hook it into the ``flask`` command
|
||||
To do this we can create a function and hook it into the :command:`flask` command
|
||||
that initializes the database. Let me show you the code first. Just add
|
||||
this function below the `connect_db` function in `flaskr.py`::
|
||||
this function below the `connect_db` function in :file:`flaskr.py`::
|
||||
|
||||
def init_db():
|
||||
db = get_db()
|
||||
|
|
@ -37,7 +37,7 @@ this function below the `connect_db` function in `flaskr.py`::
|
|||
print 'Initialized the database.'
|
||||
|
||||
The ``app.cli.command()`` decorator registers a new command with the
|
||||
``flask`` script. When the command executes Flask will automatically
|
||||
:command:`flask` script. When the command executes Flask will automatically
|
||||
create a application context for us bound to the right application.
|
||||
Within the function we can then access :attr:`flask.g` and other things as
|
||||
we would expect. When the script ends, the application context tears down
|
||||
|
|
@ -58,7 +58,7 @@ On that cursor there is a method to execute a complete script. Finally we
|
|||
only have to commit the changes. SQLite 3 and other transactional
|
||||
databases will not commit unless you explicitly tell it to.
|
||||
|
||||
Now it is possible to create a database with the ``flask`` script::
|
||||
Now it is possible to create a database with the :command:`flask` script::
|
||||
|
||||
flask --app=flaskr initdb
|
||||
Initialized the database.
|
||||
|
|
|
|||
|
|
@ -13,9 +13,9 @@ application::
|
|||
The `flaskr` folder is not a python package, but just something where we
|
||||
drop our files. We will then put our database schema as well as main module
|
||||
into this folder. It is done in the following way. The files inside
|
||||
the `static` folder are available to users of the application via `HTTP`.
|
||||
the :file:`static` folder are available to users of the application via HTTP.
|
||||
This is the place where css and javascript files go. Inside the
|
||||
`templates` folder Flask will look for `Jinja2`_ templates. The
|
||||
:file:`templates` folder Flask will look for `Jinja2`_ templates. The
|
||||
templates you create later in the tutorial will go in this directory.
|
||||
|
||||
Continue with :ref:`tutorial-schema`.
|
||||
|
|
|
|||
|
|
@ -8,10 +8,10 @@ Let's call it flaskr.py. We will place this file inside the flaskr folder.
|
|||
We will begin by adding the imports we need and by adding the config
|
||||
section. For small applications, it is possible to drop the configuration
|
||||
directly into the module, and this is what we will be doing here. However
|
||||
a cleaner solution would be to create a separate `.ini` or `.py` file and
|
||||
a cleaner solution would be to create a separate ``.ini`` or ``.py`` file and
|
||||
load that or import the values from there.
|
||||
|
||||
First we add the imports in `flaskr.py`::
|
||||
First we add the imports in :file:`flaskr.py`::
|
||||
|
||||
# all the imports
|
||||
import os
|
||||
|
|
@ -20,7 +20,7 @@ First we add the imports in `flaskr.py`::
|
|||
render_template, flash
|
||||
|
||||
Next we can create our actual application and initialize it with the
|
||||
config from the same file, in `flaskr.py`::
|
||||
config from the same file, in :file:`flaskr.py`::
|
||||
|
||||
# create our little application :)
|
||||
app = Flask(__name__)
|
||||
|
|
@ -54,14 +54,14 @@ can update it with new values.
|
|||
:ref:`instance-folders` instead.
|
||||
|
||||
Usually, it is a good idea to load a separate, environment specific
|
||||
configuration file. Flask allows you to import multiple configurations and it
|
||||
will use the setting defined in the last import. This enables robust
|
||||
configuration setups. :meth:`~flask.Config.from_envvar` can help achieve this.
|
||||
|
||||
configuration file. Flask allows you to import multiple configurations and it
|
||||
will use the setting defined in the last import. This enables robust
|
||||
configuration setups. :meth:`~flask.Config.from_envvar` can help achieve this.
|
||||
|
||||
app.config.from_envvar('FLASKR_SETTINGS', silent=True)
|
||||
|
||||
Simply define the environment variable :envvar:`FLASKR_SETTINGS` that points to
|
||||
a config file to be loaded. The silent switch just tells Flask to not complain
|
||||
Simply define the environment variable :envvar:`FLASKR_SETTINGS` that points to
|
||||
a config file to be loaded. The silent switch just tells Flask to not complain
|
||||
if no such environment key is set.
|
||||
|
||||
In addition to that you can use the :meth:`~flask.Config.from_object`
|
||||
|
|
@ -93,7 +93,7 @@ without problems. Do this with the following command::
|
|||
|
||||
flask --app=flaskr --debug run
|
||||
|
||||
The ``--debug`` flag enables or disables the interactive debugger. *Never
|
||||
The :option:`--debug` flag enables or disables the interactive debugger. *Never
|
||||
leave debug mode activated in a production system*, because it will allow
|
||||
users to execute code on the server!
|
||||
|
||||
|
|
|
|||
|
|
@ -14,7 +14,7 @@ escaped with their XML equivalents.
|
|||
We are also using template inheritance which makes it possible to reuse
|
||||
the layout of the website in all pages.
|
||||
|
||||
Put the following templates into the `templates` folder:
|
||||
Put the following templates into the :file:`templates` folder:
|
||||
|
||||
.. _Jinja2: http://jinja.pocoo.org/docs/templates
|
||||
|
||||
|
|
@ -55,10 +55,10 @@ the session:
|
|||
show_entries.html
|
||||
-----------------
|
||||
|
||||
This template extends the `layout.html` template from above to display the
|
||||
messages. Note that the `for` loop iterates over the messages we passed
|
||||
This template extends the :file:`layout.html` template from above to display the
|
||||
messages. Note that the ``for`` loop iterates over the messages we passed
|
||||
in with the :func:`~flask.render_template` function. We also tell the
|
||||
form to submit to your `add_entry` function and use `POST` as `HTTP`
|
||||
form to submit to your `add_entry` function and use ``POST`` as HTTP
|
||||
method:
|
||||
|
||||
.. sourcecode:: html+jinja
|
||||
|
|
|
|||
|
|
@ -16,7 +16,7 @@ returned from the cursor look a bit like tuples because we are using
|
|||
the :class:`sqlite3.Row` row factory.
|
||||
|
||||
The view function will pass the entries as dicts to the
|
||||
`show_entries.html` template and return the rendered one::
|
||||
:file:`show_entries.html` template and return the rendered one::
|
||||
|
||||
@app.route('/')
|
||||
def show_entries():
|
||||
|
|
@ -29,7 +29,7 @@ Add New Entry
|
|||
-------------
|
||||
|
||||
This view lets the user add new entries if they are logged in. This only
|
||||
responds to `POST` requests, the actual form is shown on the
|
||||
responds to ``POST`` requests, the actual form is shown on the
|
||||
`show_entries` page. If everything worked out well we will
|
||||
:func:`~flask.flash` an information message to the next request and
|
||||
redirect back to the `show_entries` page::
|
||||
|
|
@ -46,7 +46,7 @@ redirect back to the `show_entries` page::
|
|||
return redirect(url_for('show_entries'))
|
||||
|
||||
Note that we check that the user is logged in here (the `logged_in` key is
|
||||
present in the session and `True`).
|
||||
present in the session and ``True``).
|
||||
|
||||
.. admonition:: Security Note
|
||||
|
||||
|
|
@ -61,7 +61,7 @@ Login and Logout
|
|||
These functions are used to sign the user in and out. Login checks the
|
||||
username and password against the ones from the configuration and sets the
|
||||
`logged_in` key in the session. If the user logged in successfully, that
|
||||
key is set to `True`, and the user is redirected back to the `show_entries`
|
||||
key is set to ``True``, and the user is redirected back to the `show_entries`
|
||||
page. In addition, a message is flashed that informs the user that he or
|
||||
she was logged in successfully. If an error occurred, the template is
|
||||
notified about that, and the user is asked again::
|
||||
|
|
|
|||
|
|
@ -14,8 +14,8 @@ This section of the documentation enumerates all the changes in Flask from
|
|||
release to release and how you can change your code to have a painless
|
||||
updating experience.
|
||||
|
||||
If you want to use the `easy_install` command to upgrade your Flask
|
||||
installation, make sure to pass it the ``-U`` parameter::
|
||||
If you want to use the :command:`easy_install` command to upgrade your Flask
|
||||
installation, make sure to pass it the :option:`-U` parameter::
|
||||
|
||||
$ easy_install -U Flask
|
||||
|
||||
|
|
@ -92,7 +92,7 @@ If invalid JSON data was submitted Flask will now raise a
|
|||
default :exc:`ValueError` bubble up. This has the advantage that you no
|
||||
longer have to handle that error to avoid an internal server error showing
|
||||
up for the user. If you were catching this down explicitly in the past
|
||||
as `ValueError` you will need to change this.
|
||||
as :exc:`ValueError` you will need to change this.
|
||||
|
||||
Due to a bug in the test client Flask 0.7 did not trigger teardown
|
||||
handlers when the test client was used in a with statement. This was
|
||||
|
|
@ -136,11 +136,11 @@ To apply the upgrade script do the following:
|
|||
patch -p1 < patchfile.diff
|
||||
|
||||
5. If you were using per-module template folders you need to move some
|
||||
templates around. Previously if you had a folder named ``templates``
|
||||
templates around. Previously if you had a folder named :file:`templates`
|
||||
next to a blueprint named ``admin`` the implicit template path
|
||||
automatically was ``admin/index.html`` for a template file called
|
||||
``templates/index.html``. This no longer is the case. Now you need
|
||||
to name the template ``templates/admin/index.html``. The tool will
|
||||
automatically was :file:`admin/index.html` for a template file called
|
||||
:file:`templates/index.html`. This no longer is the case. Now you need
|
||||
to name the template :file:`templates/admin/index.html`. The tool will
|
||||
not detect this so you will have to do that on your own.
|
||||
|
||||
Please note that deprecation warnings are disabled by default starting
|
||||
|
|
@ -271,7 +271,7 @@ to upgrade. What changed?
|
|||
modules.
|
||||
- Blueprints do not automatically provide static folders. They will
|
||||
also no longer automatically export templates from a folder called
|
||||
`templates` next to their location however but it can be enabled from
|
||||
:file:`templates` next to their location however but it can be enabled from
|
||||
the constructor. Same with static files: if you want to continue
|
||||
serving static files you need to tell the constructor explicitly the
|
||||
path to the static folder (which can be relative to the blueprint's
|
||||
|
|
@ -279,7 +279,7 @@ to upgrade. What changed?
|
|||
- Rendering templates was simplified. Now the blueprints can provide
|
||||
template folders which are added to a general template searchpath.
|
||||
This means that you need to add another subfolder with the blueprint's
|
||||
name into that folder if you want ``blueprintname/template.html`` as
|
||||
name into that folder if you want :file:`blueprintname/template.html` as
|
||||
the template name.
|
||||
|
||||
If you continue to use the `Module` object which is deprecated, Flask will
|
||||
|
|
|
|||
|
|
@ -46,7 +46,7 @@ class into an actual view function by using the
|
|||
that function is the name of the endpoint that view will then have. But
|
||||
this by itself is not helpful, so let's refactor the code a bit::
|
||||
|
||||
|
||||
|
||||
from flask.views import View
|
||||
|
||||
class ListView(View):
|
||||
|
|
@ -71,7 +71,7 @@ this by itself is not helpful, so let's refactor the code a bit::
|
|||
|
||||
This of course is not that helpful for such a small example, but it's good
|
||||
enough to explain the basic principle. When you have a class-based view
|
||||
the question comes up what `self` points to. The way this works is that
|
||||
the question comes up what ``self`` points to. The way this works is that
|
||||
whenever the request is dispatched a new instance of the class is created
|
||||
and the :meth:`~flask.views.View.dispatch_request` method is called with
|
||||
the parameters from the URL rule. The class itself is instantiated with
|
||||
|
|
|
|||
|
|
@ -23,7 +23,7 @@
|
|||
|
||||
the application will greet you on
|
||||
http://localhost:5000/
|
||||
|
||||
|
||||
~ Is it tested?
|
||||
|
||||
You betcha. Run the `test_flaskr.py` file to see
|
||||
|
|
|
|||
|
|
@ -24,7 +24,7 @@
|
|||
|
||||
the application will greet you on
|
||||
http://localhost:5000/
|
||||
|
||||
|
||||
~ Is it tested?
|
||||
|
||||
You betcha. Run the `test_minitwit.py` file to
|
||||
|
|
|
|||
106
flask/app.py
106
flask/app.py
|
|
@ -71,12 +71,12 @@ class Flask(_PackageBoundObject):
|
|||
The name of the package is used to resolve resources from inside the
|
||||
package or the folder the module is contained in depending on if the
|
||||
package parameter resolves to an actual python package (a folder with
|
||||
an `__init__.py` file inside) or a standard module (just a `.py` file).
|
||||
an :file:`__init__.py` file inside) or a standard module (just a ``.py`` file).
|
||||
|
||||
For more information about resource loading, see :func:`open_resource`.
|
||||
|
||||
Usually you create a :class:`Flask` instance in your main module or
|
||||
in the `__init__.py` file of your package like this::
|
||||
in the :file:`__init__.py` file of your package like this::
|
||||
|
||||
from flask import Flask
|
||||
app = Flask(__name__)
|
||||
|
|
@ -93,7 +93,7 @@ class Flask(_PackageBoundObject):
|
|||
using a package, it's usually recommended to hardcode the name of
|
||||
your package there.
|
||||
|
||||
For example if your application is defined in `yourapplication/app.py`
|
||||
For example if your application is defined in :file:`yourapplication/app.py`
|
||||
you should create it with one of the two versions below::
|
||||
|
||||
app = Flask('yourapplication')
|
||||
|
|
@ -135,7 +135,7 @@ class Flask(_PackageBoundObject):
|
|||
By default the folder ``'instance'`` next to the
|
||||
package or module is assumed to be the instance
|
||||
path.
|
||||
:param instance_relative_config: if set to `True` relative filenames
|
||||
:param instance_relative_config: if set to ``True`` relative filenames
|
||||
for loading the config are assumed to
|
||||
be relative to the instance path instead
|
||||
of the application root.
|
||||
|
|
@ -193,16 +193,16 @@ class Flask(_PackageBoundObject):
|
|||
#: .. versionadded:: 1.0
|
||||
config_class = Config
|
||||
|
||||
#: The debug flag. Set this to `True` to enable debugging of the
|
||||
#: The debug flag. Set this to ``True`` to enable debugging of the
|
||||
#: application. In debug mode the debugger will kick in when an unhandled
|
||||
#: exception occurs and the integrated server will automatically reload
|
||||
#: the application if changes in the code are detected.
|
||||
#:
|
||||
#: This attribute can also be configured from the config with the `DEBUG`
|
||||
#: configuration key. Defaults to `False`.
|
||||
#: This attribute can also be configured from the config with the ``DEBUG``
|
||||
#: configuration key. Defaults to ``False``.
|
||||
debug = ConfigAttribute('DEBUG')
|
||||
|
||||
#: The testing flag. Set this to `True` to enable the test mode of
|
||||
#: The testing flag. Set this to ``True`` to enable the test mode of
|
||||
#: Flask extensions (and in the future probably also Flask itself).
|
||||
#: For example this might activate unittest helpers that have an
|
||||
#: additional runtime cost which should not be enabled by default.
|
||||
|
|
@ -211,7 +211,7 @@ class Flask(_PackageBoundObject):
|
|||
#: default it's implicitly enabled.
|
||||
#:
|
||||
#: This attribute can also be configured from the config with the
|
||||
#: `TESTING` configuration key. Defaults to `False`.
|
||||
#: ``TESTING`` configuration key. Defaults to ``False``.
|
||||
testing = ConfigAttribute('TESTING')
|
||||
|
||||
#: If a secret key is set, cryptographic components can use this to
|
||||
|
|
@ -219,13 +219,13 @@ class Flask(_PackageBoundObject):
|
|||
#: when you want to use the secure cookie for instance.
|
||||
#:
|
||||
#: This attribute can also be configured from the config with the
|
||||
#: `SECRET_KEY` configuration key. Defaults to `None`.
|
||||
#: ``SECRET_KEY`` configuration key. Defaults to ``None``.
|
||||
secret_key = ConfigAttribute('SECRET_KEY')
|
||||
|
||||
#: The secure cookie uses this for the name of the session cookie.
|
||||
#:
|
||||
#: This attribute can also be configured from the config with the
|
||||
#: `SESSION_COOKIE_NAME` configuration key. Defaults to ``'session'``
|
||||
#: ``SESSION_COOKIE_NAME`` configuration key. Defaults to ``'session'``
|
||||
session_cookie_name = ConfigAttribute('SESSION_COOKIE_NAME')
|
||||
|
||||
#: A :class:`~datetime.timedelta` which is used to set the expiration
|
||||
|
|
@ -233,7 +233,7 @@ class Flask(_PackageBoundObject):
|
|||
#: permanent session survive for roughly one month.
|
||||
#:
|
||||
#: This attribute can also be configured from the config with the
|
||||
#: `PERMANENT_SESSION_LIFETIME` configuration key. Defaults to
|
||||
#: ``PERMANENT_SESSION_LIFETIME`` configuration key. Defaults to
|
||||
#: ``timedelta(days=31)``
|
||||
permanent_session_lifetime = ConfigAttribute('PERMANENT_SESSION_LIFETIME',
|
||||
get_converter=_make_timedelta)
|
||||
|
|
@ -245,7 +245,7 @@ class Flask(_PackageBoundObject):
|
|||
#: .. versionadded:: 0.2
|
||||
#:
|
||||
#: This attribute can also be configured from the config with the
|
||||
#: `USE_X_SENDFILE` configuration key. Defaults to `False`.
|
||||
#: ``USE_X_SENDFILE`` configuration key. Defaults to ``False``.
|
||||
use_x_sendfile = ConfigAttribute('USE_X_SENDFILE')
|
||||
|
||||
#: The name of the logger to use. By default the logger name is the
|
||||
|
|
@ -364,11 +364,11 @@ class Flask(_PackageBoundObject):
|
|||
# :attr:`error_handler_spec` shall be used now.
|
||||
self._error_handlers = {}
|
||||
|
||||
#: A dictionary of all registered error handlers. The key is `None`
|
||||
#: A dictionary of all registered error handlers. The key is ``None``
|
||||
#: for error handlers active on the application, otherwise the key is
|
||||
#: the name of the blueprint. Each key points to another dictionary
|
||||
#: where the key is the status code of the http exception. The
|
||||
#: special key `None` points to a list of tuples where the first item
|
||||
#: special key ``None`` points to a list of tuples where the first item
|
||||
#: is the class for the instance check and the second the error handler
|
||||
#: function.
|
||||
#:
|
||||
|
|
@ -379,7 +379,7 @@ class Flask(_PackageBoundObject):
|
|||
#: A list of functions that are called when :meth:`url_for` raises a
|
||||
#: :exc:`~werkzeug.routing.BuildError`. Each function registered here
|
||||
#: is called with `error`, `endpoint` and `values`. If a function
|
||||
#: returns `None` or raises a `BuildError` the next function is
|
||||
#: returns ``None`` or raises a :exc:`BuildError` the next function is
|
||||
#: tried.
|
||||
#:
|
||||
#: .. versionadded:: 0.9
|
||||
|
|
@ -387,7 +387,7 @@ class Flask(_PackageBoundObject):
|
|||
|
||||
#: A dictionary with lists of functions that should be called at the
|
||||
#: beginning of the request. The key of the dictionary is the name of
|
||||
#: the blueprint this function is active for, `None` for all requests.
|
||||
#: the blueprint this function is active for, ``None`` for all requests.
|
||||
#: This can for example be used to open database connections or
|
||||
#: getting hold of the currently logged in user. To register a
|
||||
#: function here, use the :meth:`before_request` decorator.
|
||||
|
|
@ -402,7 +402,7 @@ class Flask(_PackageBoundObject):
|
|||
|
||||
#: A dictionary with lists of functions that should be called after
|
||||
#: each request. The key of the dictionary is the name of the blueprint
|
||||
#: this function is active for, `None` for all requests. This can for
|
||||
#: this function is active for, ``None`` for all requests. This can for
|
||||
#: example be used to open database connections or getting hold of the
|
||||
#: currently logged in user. To register a function here, use the
|
||||
#: :meth:`after_request` decorator.
|
||||
|
|
@ -411,7 +411,7 @@ class Flask(_PackageBoundObject):
|
|||
#: A dictionary with lists of functions that are called after
|
||||
#: each request, even if an exception has occurred. The key of the
|
||||
#: dictionary is the name of the blueprint this function is active for,
|
||||
#: `None` for all requests. These functions are not allowed to modify
|
||||
#: ``None`` for all requests. These functions are not allowed to modify
|
||||
#: the request, and their return values are ignored. If an exception
|
||||
#: occurred while processing the request, it gets passed to each
|
||||
#: teardown_request function. To register a function here, use the
|
||||
|
|
@ -431,7 +431,7 @@ class Flask(_PackageBoundObject):
|
|||
#: A dictionary with lists of functions that can be used as URL
|
||||
#: value processor functions. Whenever a URL is built these functions
|
||||
#: are called to modify the dictionary of values in place. The key
|
||||
#: `None` here is used for application wide
|
||||
#: ``None`` here is used for application wide
|
||||
#: callbacks, otherwise the key is the name of the blueprint.
|
||||
#: Each of these functions has the chance to modify the dictionary
|
||||
#:
|
||||
|
|
@ -439,7 +439,7 @@ class Flask(_PackageBoundObject):
|
|||
self.url_value_preprocessors = {}
|
||||
|
||||
#: A dictionary with lists of functions that can be used as URL value
|
||||
#: preprocessors. The key `None` here is used for application wide
|
||||
#: preprocessors. The key ``None`` here is used for application wide
|
||||
#: callbacks, otherwise the key is the name of the blueprint.
|
||||
#: Each of these functions has the chance to modify the dictionary
|
||||
#: of URL values before they are used as the keyword arguments of the
|
||||
|
|
@ -452,7 +452,7 @@ class Flask(_PackageBoundObject):
|
|||
|
||||
#: A dictionary with list of functions that are called without argument
|
||||
#: to populate the template context. The key of the dictionary is the
|
||||
#: name of the blueprint this function is active for, `None` for all
|
||||
#: name of the blueprint this function is active for, ``None`` for all
|
||||
#: requests. Each returns a dictionary that the template context is
|
||||
#: updated with. To register a function here, use the
|
||||
#: :meth:`context_processor` decorator.
|
||||
|
|
@ -523,7 +523,7 @@ class Flask(_PackageBoundObject):
|
|||
view_func=self.send_static_file)
|
||||
|
||||
#: The click command line context for this application. Commands
|
||||
#: registered here show up in the ``flask`` command once the
|
||||
#: registered here show up in the :command:`flask` command once the
|
||||
#: application has been discovered. The default commands are
|
||||
#: provided by Flask itself and can be overridden.
|
||||
#:
|
||||
|
|
@ -560,7 +560,7 @@ class Flask(_PackageBoundObject):
|
|||
|
||||
@property
|
||||
def propagate_exceptions(self):
|
||||
"""Returns the value of the `PROPAGATE_EXCEPTIONS` configuration
|
||||
"""Returns the value of the ``PROPAGATE_EXCEPTIONS`` configuration
|
||||
value in case it's set, otherwise a sensible default is returned.
|
||||
|
||||
.. versionadded:: 0.7
|
||||
|
|
@ -572,7 +572,7 @@ class Flask(_PackageBoundObject):
|
|||
|
||||
@property
|
||||
def preserve_context_on_exception(self):
|
||||
"""Returns the value of the `PRESERVE_CONTEXT_ON_EXCEPTION`
|
||||
"""Returns the value of the ``PRESERVE_CONTEXT_ON_EXCEPTION``
|
||||
configuration value in case it's set, otherwise a sensible default
|
||||
is returned.
|
||||
|
||||
|
|
@ -612,7 +612,7 @@ class Flask(_PackageBoundObject):
|
|||
|
||||
@property
|
||||
def got_first_request(self):
|
||||
"""This attribute is set to `True` if the application started
|
||||
"""This attribute is set to ``True`` if the application started
|
||||
handling the first request.
|
||||
|
||||
.. versionadded:: 0.8
|
||||
|
|
@ -715,7 +715,7 @@ class Flask(_PackageBoundObject):
|
|||
"""
|
||||
|
||||
def select_jinja_autoescape(self, filename):
|
||||
"""Returns `True` if autoescaping should be active for the given
|
||||
"""Returns ``True`` if autoescaping should be active for the given
|
||||
template name.
|
||||
|
||||
.. versionadded:: 0.5
|
||||
|
|
@ -773,7 +773,7 @@ class Flask(_PackageBoundObject):
|
|||
|
||||
It is not recommended to use this function for development with
|
||||
automatic reloading as this is badly supported. Instead you should
|
||||
be using the ``flask`` command line script's ``runserver``
|
||||
be using the :command:`flask` command line script's ``runserver``
|
||||
support.
|
||||
|
||||
.. admonition:: Keep in Mind
|
||||
|
|
@ -782,7 +782,7 @@ class Flask(_PackageBoundObject):
|
|||
unless it is in debug mode. As such to enable just the
|
||||
interactive debugger without the code reloading, you have to
|
||||
invoke :meth:`run` with ``debug=True`` and ``use_reloader=False``.
|
||||
Setting ``use_debugger`` to `True` without being in debug mode
|
||||
Setting ``use_debugger`` to ``True`` without being in debug mode
|
||||
won't catch any exceptions because there won't be any to
|
||||
catch.
|
||||
|
||||
|
|
@ -838,8 +838,8 @@ class Flask(_PackageBoundObject):
|
|||
app.testing = True
|
||||
client = app.test_client()
|
||||
|
||||
The test client can be used in a `with` block to defer the closing down
|
||||
of the context until the end of the `with` block. This is useful if
|
||||
The test client can be used in a ``with`` block to defer the closing down
|
||||
of the context until the end of the ``with`` block. This is useful if
|
||||
you want to access the context locals for testing::
|
||||
|
||||
with app.test_client() as c:
|
||||
|
|
@ -863,7 +863,7 @@ class Flask(_PackageBoundObject):
|
|||
See :class:`~flask.testing.FlaskClient` for more information.
|
||||
|
||||
.. versionchanged:: 0.4
|
||||
added support for `with` block usage for the client.
|
||||
added support for ``with`` block usage for the client.
|
||||
|
||||
.. versionadded:: 0.7
|
||||
The `use_cookies` parameter was added as well as the ability
|
||||
|
|
@ -968,7 +968,7 @@ class Flask(_PackageBoundObject):
|
|||
`view_func` parameter added.
|
||||
|
||||
.. versionchanged:: 0.6
|
||||
`OPTIONS` is added automatically as method.
|
||||
``OPTIONS`` is added automatically as method.
|
||||
|
||||
:param rule: the URL rule as string
|
||||
:param endpoint: the endpoint for the registered URL rule. Flask
|
||||
|
|
@ -980,9 +980,9 @@ class Flask(_PackageBoundObject):
|
|||
:class:`~werkzeug.routing.Rule` object. A change
|
||||
to Werkzeug is handling of method options. methods
|
||||
is a list of methods this rule should be limited
|
||||
to (`GET`, `POST` etc.). By default a rule
|
||||
just listens for `GET` (and implicitly `HEAD`).
|
||||
Starting with Flask 0.6, `OPTIONS` is implicitly
|
||||
to (``GET``, ``POST`` etc.). By default a rule
|
||||
just listens for ``GET`` (and implicitly ``HEAD``).
|
||||
Starting with Flask 0.6, ``OPTIONS`` is implicitly
|
||||
added and handled by the standard request handling.
|
||||
"""
|
||||
if endpoint is None:
|
||||
|
|
@ -992,7 +992,7 @@ class Flask(_PackageBoundObject):
|
|||
|
||||
# if the methods are not given and the view_func object knows its
|
||||
# methods we can use that instead. If neither exists, we go with
|
||||
# a tuple of only `GET` as default.
|
||||
# a tuple of only ``GET`` as default.
|
||||
if methods is None:
|
||||
methods = getattr(view_func, 'methods', None) or ('GET',)
|
||||
if isinstance(methods, string_types):
|
||||
|
|
@ -1048,9 +1048,9 @@ class Flask(_PackageBoundObject):
|
|||
:class:`~werkzeug.routing.Rule` object. A change
|
||||
to Werkzeug is handling of method options. methods
|
||||
is a list of methods this rule should be limited
|
||||
to (`GET`, `POST` etc.). By default a rule
|
||||
just listens for `GET` (and implicitly `HEAD`).
|
||||
Starting with Flask 0.6, `OPTIONS` is implicitly
|
||||
to (``GET``, ``POST`` etc.). By default a rule
|
||||
just listens for ``GET`` (and implicitly ``HEAD``).
|
||||
Starting with Flask 0.6, ``OPTIONS`` is implicitly
|
||||
added and handled by the standard request handling.
|
||||
"""
|
||||
def decorator(f):
|
||||
|
|
@ -1102,8 +1102,8 @@ class Flask(_PackageBoundObject):
|
|||
however is discouraged as it requires fiddling with nested dictionaries
|
||||
and the special case for arbitrary exception types.
|
||||
|
||||
The first `None` refers to the active blueprint. If the error
|
||||
handler should be application wide `None` shall be used.
|
||||
The first ``None`` refers to the active blueprint. If the error
|
||||
handler should be application wide ``None`` shall be used.
|
||||
|
||||
.. versionadded:: 0.7
|
||||
Use :meth:`register_error_handler` instead of modifying
|
||||
|
|
@ -1392,12 +1392,12 @@ class Flask(_PackageBoundObject):
|
|||
|
||||
def trap_http_exception(self, e):
|
||||
"""Checks if an HTTP exception should be trapped or not. By default
|
||||
this will return `False` for all exceptions except for a bad request
|
||||
key error if ``TRAP_BAD_REQUEST_ERRORS`` is set to `True`. It
|
||||
also returns `True` if ``TRAP_HTTP_EXCEPTIONS`` is set to `True`.
|
||||
this will return ``False`` for all exceptions except for a bad request
|
||||
key error if ``TRAP_BAD_REQUEST_ERRORS`` is set to ``True``. It
|
||||
also returns ``True`` if ``TRAP_HTTP_EXCEPTIONS`` is set to ``True``.
|
||||
|
||||
This is called for all HTTP exceptions raised by a view function.
|
||||
If it returns `True` for any exception the error handler for this
|
||||
If it returns ``True`` for any exception the error handler for this
|
||||
exception is not called and it shows up as regular exception in the
|
||||
traceback. This is helpful for debugging implicitly raised HTTP
|
||||
exceptions.
|
||||
|
|
@ -1559,9 +1559,9 @@ class Flask(_PackageBoundObject):
|
|||
self._got_first_request = True
|
||||
|
||||
def make_default_options_response(self):
|
||||
"""This method is called to create the default `OPTIONS` response.
|
||||
"""This method is called to create the default ``OPTIONS`` response.
|
||||
This can be changed through subclassing to change the default
|
||||
behavior of `OPTIONS` responses.
|
||||
behavior of ``OPTIONS`` responses.
|
||||
|
||||
.. versionadded:: 0.7
|
||||
"""
|
||||
|
|
@ -1584,7 +1584,7 @@ class Flask(_PackageBoundObject):
|
|||
def should_ignore_error(self, error):
|
||||
"""This is called to figure out if an error should be ignored
|
||||
or not as far as the teardown system is concerned. If this
|
||||
function returns `True` then the teardown handlers will not be
|
||||
function returns ``True`` then the teardown handlers will not be
|
||||
passed the error.
|
||||
|
||||
.. versionadded:: 0.10
|
||||
|
|
@ -1812,15 +1812,15 @@ class Flask(_PackageBoundObject):
|
|||
def request_context(self, environ):
|
||||
"""Creates a :class:`~flask.ctx.RequestContext` from the given
|
||||
environment and binds it to the current context. This must be used in
|
||||
combination with the `with` statement because the request is only bound
|
||||
to the current context for the duration of the `with` block.
|
||||
combination with the ``with`` statement because the request is only bound
|
||||
to the current context for the duration of the ``with`` block.
|
||||
|
||||
Example usage::
|
||||
|
||||
with app.request_context(environ):
|
||||
do_something_with(request)
|
||||
|
||||
The object returned can also be used without the `with` statement
|
||||
The object returned can also be used without the ``with`` statement
|
||||
which is useful for working in the shell. The example above is
|
||||
doing exactly the same as this code::
|
||||
|
||||
|
|
@ -1832,7 +1832,7 @@ class Flask(_PackageBoundObject):
|
|||
ctx.pop()
|
||||
|
||||
.. versionchanged:: 0.3
|
||||
Added support for non-with statement usage and `with` statement
|
||||
Added support for non-with statement usage and ``with`` statement
|
||||
is now passed the ctx object.
|
||||
|
||||
:param environ: a WSGI environment
|
||||
|
|
|
|||
|
|
@ -42,7 +42,7 @@ class BlueprintSetupState(object):
|
|||
if subdomain is None:
|
||||
subdomain = self.blueprint.subdomain
|
||||
|
||||
#: The subdomain that the blueprint should be active for, `None`
|
||||
#: The subdomain that the blueprint should be active for, ``None``
|
||||
#: otherwise.
|
||||
self.subdomain = subdomain
|
||||
|
||||
|
|
|
|||
|
|
@ -267,10 +267,10 @@ class FlaskGroup(AppGroup):
|
|||
|
||||
:param add_default_commands: if this is True then the default run and
|
||||
shell commands wil be added.
|
||||
:param add_app_option: adds the default ``--app`` option. This gets
|
||||
:param add_app_option: adds the default :option:`--app` option. This gets
|
||||
automatically disabled if a `create_app`
|
||||
callback is defined.
|
||||
:param add_debug_option: adds the default ``--debug`` option.
|
||||
:param add_debug_option: adds the default :option:`--debug` option.
|
||||
:param create_app: an optional callback that is passed the script info
|
||||
and returns the loaded app.
|
||||
"""
|
||||
|
|
|
|||
|
|
@ -93,9 +93,9 @@ class Config(dict):
|
|||
app.config.from_pyfile(os.environ['YOURAPPLICATION_SETTINGS'])
|
||||
|
||||
:param variable_name: name of the environment variable
|
||||
:param silent: set to `True` if you want silent failure for missing
|
||||
:param silent: set to ``True`` if you want silent failure for missing
|
||||
files.
|
||||
:return: bool. `True` if able to load config, `False` otherwise.
|
||||
:return: bool. ``True`` if able to load config, ``False`` otherwise.
|
||||
"""
|
||||
rv = os.environ.get(variable_name)
|
||||
if not rv:
|
||||
|
|
@ -116,7 +116,7 @@ class Config(dict):
|
|||
:param filename: the filename of the config. This can either be an
|
||||
absolute filename or a filename relative to the
|
||||
root path.
|
||||
:param silent: set to `True` if you want silent failure for missing
|
||||
:param silent: set to ``True`` if you want silent failure for missing
|
||||
files.
|
||||
|
||||
.. versionadded:: 0.7
|
||||
|
|
@ -173,7 +173,7 @@ class Config(dict):
|
|||
:param filename: the filename of the JSON file. This can either be an
|
||||
absolute filename or a filename relative to the
|
||||
root path.
|
||||
:param silent: set to `True` if you want silent failure for missing
|
||||
:param silent: set to ``True`` if you want silent failure for missing
|
||||
files.
|
||||
|
||||
.. versionadded:: 1.0
|
||||
|
|
|
|||
|
|
@ -209,8 +209,8 @@ class RequestContext(object):
|
|||
for you. In debug mode the request context is kept around if
|
||||
exceptions happen so that interactive debuggers have a chance to
|
||||
introspect the data. With 0.4 this can also be forced for requests
|
||||
that did not fail and outside of `DEBUG` mode. By setting
|
||||
``'flask._preserve_context'`` to `True` on the WSGI environment the
|
||||
that did not fail and outside of ``DEBUG`` mode. By setting
|
||||
``'flask._preserve_context'`` to ``True`` on the WSGI environment the
|
||||
context will not pop itself at the end of the request. This is used by
|
||||
the :meth:`~flask.Flask.test_client` for example to implement the
|
||||
deferred cleanup functionality.
|
||||
|
|
|
|||
|
|
@ -188,7 +188,7 @@ def url_for(endpoint, **values):
|
|||
|
||||
Variable arguments that are unknown to the target endpoint are appended
|
||||
to the generated URL as query arguments. If the value of a query argument
|
||||
is `None`, the whole pair is skipped. In case blueprints are active
|
||||
is ``None``, the whole pair is skipped. In case blueprints are active
|
||||
you can shortcut references to the same blueprint by prefixing the
|
||||
local endpoint with a dot (``.``).
|
||||
|
||||
|
|
@ -203,7 +203,7 @@ def url_for(endpoint, **values):
|
|||
function results in a :exc:`~werkzeug.routing.BuildError` when the current
|
||||
app does not have a URL for the given endpoint and values. When it does, the
|
||||
:data:`~flask.current_app` calls its :attr:`~Flask.url_build_error_handlers` if
|
||||
it is not `None`, which can return a string to use as the result of
|
||||
it is not ``None``, which can return a string to use as the result of
|
||||
`url_for` (instead of `url_for`'s default to raise the
|
||||
:exc:`~werkzeug.routing.BuildError` exception) or re-raise the exception.
|
||||
An example::
|
||||
|
|
@ -244,11 +244,11 @@ def url_for(endpoint, **values):
|
|||
|
||||
:param endpoint: the endpoint of the URL (name of the function)
|
||||
:param values: the variable arguments of the URL rule
|
||||
:param _external: if set to `True`, an absolute URL is generated. Server
|
||||
address can be changed via `SERVER_NAME` configuration variable which
|
||||
:param _external: if set to ``True``, an absolute URL is generated. Server
|
||||
address can be changed via ``SERVER_NAME`` configuration variable which
|
||||
defaults to `localhost`.
|
||||
:param _scheme: a string specifying the desired URL scheme. The `_external`
|
||||
parameter must be set to `True` or a `ValueError` is raised. The default
|
||||
parameter must be set to ``True`` or a :exc:`ValueError` is raised. The default
|
||||
behavior uses the same scheme as the current request, or
|
||||
``PREFERRED_URL_SCHEME`` from the :ref:`app configuration <config>` if no
|
||||
request context is available. As of Werkzeug 0.10, this also can be set
|
||||
|
|
@ -323,7 +323,7 @@ def url_for(endpoint, **values):
|
|||
def get_template_attribute(template_name, attribute):
|
||||
"""Loads a macro (or variable) a template exports. This can be used to
|
||||
invoke a macro from within Python code. If you for example have a
|
||||
template named `_cider.html` with the following contents:
|
||||
template named :file:`_cider.html` with the following contents:
|
||||
|
||||
.. sourcecode:: html+jinja
|
||||
|
||||
|
|
@ -376,7 +376,7 @@ def get_flashed_messages(with_categories=False, category_filter=[]):
|
|||
"""Pulls all flashed messages from the session and returns them.
|
||||
Further calls in the same request to the function will return
|
||||
the same messages. By default just the messages are returned,
|
||||
but when `with_categories` is set to `True`, the return value will
|
||||
but when `with_categories` is set to ``True``, the return value will
|
||||
be a list of tuples in the form ``(category, message)`` instead.
|
||||
|
||||
Filter the flashed messages to one or more categories by providing those
|
||||
|
|
@ -385,7 +385,7 @@ def get_flashed_messages(with_categories=False, category_filter=[]):
|
|||
arguments are distinct:
|
||||
|
||||
* `with_categories` controls whether categories are returned with message
|
||||
text (`True` gives a tuple, where `False` gives just the message text).
|
||||
text (``True`` gives a tuple, where ``False`` gives just the message text).
|
||||
* `category_filter` filters the messages down to only those matching the
|
||||
provided categories.
|
||||
|
||||
|
|
@ -397,7 +397,7 @@ def get_flashed_messages(with_categories=False, category_filter=[]):
|
|||
.. versionchanged:: 0.9
|
||||
`category_filter` parameter added.
|
||||
|
||||
:param with_categories: set to `True` to also receive categories.
|
||||
:param with_categories: set to ``True`` to also receive categories.
|
||||
:param category_filter: whitelist of categories to limit return values
|
||||
"""
|
||||
flashes = _request_ctx_stack.top.flashes
|
||||
|
|
@ -418,8 +418,8 @@ def send_file(filename_or_fp, mimetype=None, as_attachment=False,
|
|||
most efficient method available and configured. By default it will
|
||||
try to use the WSGI server's file_wrapper support. Alternatively
|
||||
you can set the application's :attr:`~Flask.use_x_sendfile` attribute
|
||||
to ``True`` to directly emit an `X-Sendfile` header. This however
|
||||
requires support of the underlying webserver for `X-Sendfile`.
|
||||
to ``True`` to directly emit an ``X-Sendfile`` header. This however
|
||||
requires support of the underlying webserver for ``X-Sendfile``.
|
||||
|
||||
By default it will try to guess the mimetype for you, but you can
|
||||
also explicitly provide one. For extra security you probably want
|
||||
|
|
@ -453,20 +453,20 @@ def send_file(filename_or_fp, mimetype=None, as_attachment=False,
|
|||
relative to the :attr:`~Flask.root_path` if a
|
||||
relative path is specified.
|
||||
Alternatively a file object might be provided
|
||||
in which case `X-Sendfile` might not work and
|
||||
in which case ``X-Sendfile`` might not work and
|
||||
fall back to the traditional method. Make sure
|
||||
that the file pointer is positioned at the start
|
||||
of data to send before calling :func:`send_file`.
|
||||
:param mimetype: the mimetype of the file if provided, otherwise
|
||||
auto detection happens.
|
||||
:param as_attachment: set to `True` if you want to send this file with
|
||||
:param as_attachment: set to ``True`` if you want to send this file with
|
||||
a ``Content-Disposition: attachment`` header.
|
||||
:param attachment_filename: the filename for the attachment if it
|
||||
differs from the file's filename.
|
||||
:param add_etags: set to `False` to disable attaching of etags.
|
||||
:param conditional: set to `True` to enable conditional responses.
|
||||
:param add_etags: set to ``False`` to disable attaching of etags.
|
||||
:param conditional: set to ``True`` to enable conditional responses.
|
||||
|
||||
:param cache_timeout: the timeout in seconds for the headers. When `None`
|
||||
:param cache_timeout: the timeout in seconds for the headers. When ``None``
|
||||
(default), this value is set by
|
||||
:meth:`~Flask.get_send_file_max_age` of
|
||||
:data:`~flask.current_app`.
|
||||
|
|
@ -605,7 +605,7 @@ def send_from_directory(directory, filename, **options):
|
|||
|
||||
.. admonition:: Sending files and Performance
|
||||
|
||||
It is strongly recommended to activate either `X-Sendfile` support in
|
||||
It is strongly recommended to activate either ``X-Sendfile`` support in
|
||||
your webserver or (if no authentication happens) to tell the webserver
|
||||
to serve files for the given path on its own without calling into the
|
||||
web application for improved performance.
|
||||
|
|
@ -784,7 +784,7 @@ class _PackageBoundObject(object):
|
|||
#: it was set by the constructor.
|
||||
self.import_name = import_name
|
||||
|
||||
#: location of the templates. `None` if templates should not be
|
||||
#: location of the templates. ``None`` if templates should not be
|
||||
#: exposed.
|
||||
self.template_folder = template_folder
|
||||
|
||||
|
|
@ -818,7 +818,7 @@ class _PackageBoundObject(object):
|
|||
|
||||
@property
|
||||
def has_static_folder(self):
|
||||
"""This is `True` if the package bound object's container has a
|
||||
"""This is ``True`` if the package bound object's container has a
|
||||
folder named ``'static'``.
|
||||
|
||||
.. versionadded:: 0.5
|
||||
|
|
@ -843,7 +843,7 @@ class _PackageBoundObject(object):
|
|||
|
||||
Static file functions such as :func:`send_from_directory` use this
|
||||
function, and :func:`send_file` calls this function on
|
||||
:data:`~flask.current_app` when the given cache_timeout is `None`. If a
|
||||
:data:`~flask.current_app` when the given cache_timeout is ``None``. If a
|
||||
cache_timeout is given in :func:`send_file`, that timeout is used;
|
||||
otherwise, this method is called.
|
||||
|
||||
|
|
@ -887,7 +887,7 @@ class _PackageBoundObject(object):
|
|||
/layout.html
|
||||
/index.html
|
||||
|
||||
If you want to open the `schema.sql` file you would do the
|
||||
If you want to open the :file:`schema.sql` file you would do the
|
||||
following::
|
||||
|
||||
with app.open_resource('schema.sql') as f:
|
||||
|
|
|
|||
|
|
@ -60,7 +60,7 @@ class JSONEncoder(_json.JSONEncoder):
|
|||
def default(self, o):
|
||||
"""Implement this method in a subclass such that it returns a
|
||||
serializable object for ``o``, or calls the base implementation (to
|
||||
raise a ``TypeError``).
|
||||
raise a :exc:`TypeError`).
|
||||
|
||||
For example, to support arbitrary iterators, you could implement
|
||||
default like this::
|
||||
|
|
@ -200,7 +200,7 @@ def htmlsafe_dump(obj, fp, **kwargs):
|
|||
|
||||
def jsonify(*args, **kwargs):
|
||||
"""Creates a :class:`~flask.Response` with the JSON representation of
|
||||
the given arguments with an `application/json` mimetype. The arguments
|
||||
the given arguments with an :mimetype:`application/json` mimetype. The arguments
|
||||
to this function are the same as to the :class:`dict` constructor.
|
||||
|
||||
Example usage::
|
||||
|
|
|
|||
|
|
@ -42,13 +42,13 @@ class SessionMixin(object):
|
|||
|
||||
#: some session backends can tell you if a session is new, but that is
|
||||
#: not necessarily guaranteed. Use with caution. The default mixin
|
||||
#: implementation just hardcodes `False` in.
|
||||
#: implementation just hardcodes ``False`` in.
|
||||
new = False
|
||||
|
||||
#: for some backends this will always be `True`, but some backends will
|
||||
#: for some backends this will always be ``True``, but some backends will
|
||||
#: default this to false and detect changes in the dictionary for as
|
||||
#: long as changes do not happen on mutable structures in the session.
|
||||
#: The default mixin implementation just hardcodes `True` in.
|
||||
#: The default mixin implementation just hardcodes ``True`` in.
|
||||
modified = True
|
||||
|
||||
|
||||
|
|
@ -149,7 +149,7 @@ class SessionInterface(object):
|
|||
class Session(dict, SessionMixin):
|
||||
pass
|
||||
|
||||
If :meth:`open_session` returns `None` Flask will call into
|
||||
If :meth:`open_session` returns ``None`` Flask will call into
|
||||
:meth:`make_null_session` to create a session that acts as replacement
|
||||
if the session support cannot work because some requirement is not
|
||||
fulfilled. The default :class:`NullSession` class that is created
|
||||
|
|
@ -228,7 +228,7 @@ class SessionInterface(object):
|
|||
"""Returns the path for which the cookie should be valid. The
|
||||
default implementation uses the value from the ``SESSION_COOKIE_PATH``
|
||||
config var if it's set, and falls back to ``APPLICATION_ROOT`` or
|
||||
uses ``/`` if it's `None`.
|
||||
uses ``/`` if it's ``None``.
|
||||
"""
|
||||
return app.config['SESSION_COOKIE_PATH'] or \
|
||||
app.config['APPLICATION_ROOT'] or '/'
|
||||
|
|
@ -248,7 +248,7 @@ class SessionInterface(object):
|
|||
|
||||
def get_expiration_time(self, app, session):
|
||||
"""A helper method that returns an expiration date for the session
|
||||
or `None` if the session is linked to the browser session. The
|
||||
or ``None`` if the session is linked to the browser session. The
|
||||
default implementation returns now + the permanent session
|
||||
lifetime configured on the application.
|
||||
"""
|
||||
|
|
@ -260,8 +260,8 @@ class SessionInterface(object):
|
|||
used by session backends to figure out if they should emit a
|
||||
set-cookie header or not. The default behavior is controlled by
|
||||
the ``SESSION_REFRESH_EACH_REQUEST`` config variable. If
|
||||
it's set to `False` then a cookie is only set if the session is
|
||||
modified, if set to `True` it's always set if the session is
|
||||
it's set to ``False`` then a cookie is only set if the session is
|
||||
modified, if set to ``True`` it's always set if the session is
|
||||
permanent.
|
||||
|
||||
This check is usually skipped if sessions get deleted.
|
||||
|
|
@ -274,7 +274,7 @@ class SessionInterface(object):
|
|||
return save_each and session.permanent
|
||||
|
||||
def open_session(self, app, request):
|
||||
"""This method has to be implemented and must either return `None`
|
||||
"""This method has to be implemented and must either return ``None``
|
||||
in case the loading failed because of a configuration error or an
|
||||
instance of a session object which implements a dictionary like
|
||||
interface + the methods and attributes on :class:`SessionMixin`.
|
||||
|
|
|
|||
|
|
@ -47,7 +47,7 @@ class Request(RequestBase):
|
|||
url_rule = None
|
||||
|
||||
#: A dict of view arguments that matched the request. If an exception
|
||||
#: happened when matching, this will be `None`.
|
||||
#: happened when matching, this will be ``None``.
|
||||
view_args = None
|
||||
|
||||
#: If matching the URL failed, this is the exception that will be
|
||||
|
|
@ -62,7 +62,7 @@ class Request(RequestBase):
|
|||
|
||||
@property
|
||||
def max_content_length(self):
|
||||
"""Read-only view of the `MAX_CONTENT_LENGTH` config key."""
|
||||
"""Read-only view of the ``MAX_CONTENT_LENGTH`` config key."""
|
||||
ctx = _request_ctx_stack.top
|
||||
if ctx is not None:
|
||||
return ctx.app.config['MAX_CONTENT_LENGTH']
|
||||
|
|
@ -72,7 +72,7 @@ class Request(RequestBase):
|
|||
"""The endpoint that matched the request. This in combination with
|
||||
:attr:`view_args` can be used to reconstruct the same or a
|
||||
modified URL. If an exception happened when matching, this will
|
||||
be `None`.
|
||||
be ``None``.
|
||||
"""
|
||||
if self.url_rule is not None:
|
||||
return self.url_rule.endpoint
|
||||
|
|
@ -98,8 +98,8 @@ class Request(RequestBase):
|
|||
|
||||
@property
|
||||
def json(self):
|
||||
"""If the mimetype is `application/json` this will contain the
|
||||
parsed JSON data. Otherwise this will be `None`.
|
||||
"""If the mimetype is :mimetype:`application/json` this will contain the
|
||||
parsed JSON data. Otherwise this will be ``None``.
|
||||
|
||||
The :meth:`get_json` method should be used instead.
|
||||
"""
|
||||
|
|
@ -112,7 +112,7 @@ class Request(RequestBase):
|
|||
def is_json(self):
|
||||
"""Indicates if this request is JSON or not. By default a request
|
||||
is considered to include JSON data if the mimetype is
|
||||
``application/json`` or ``application/*+json``.
|
||||
:mimetype:`application/json` or :mimetype:`application/*+json`.
|
||||
|
||||
.. versionadded:: 0.11
|
||||
"""
|
||||
|
|
@ -127,13 +127,13 @@ class Request(RequestBase):
|
|||
"""Parses the incoming JSON request data and returns it. If
|
||||
parsing fails the :meth:`on_json_loading_failed` method on the
|
||||
request object will be invoked. By default this function will
|
||||
only load the json data if the mimetype is ``application/json``
|
||||
only load the json data if the mimetype is :mimetype:`application/json`
|
||||
but this can be overridden by the `force` parameter.
|
||||
|
||||
:param force: if set to `True` the mimetype is ignored.
|
||||
:param silent: if set to `True` this method will fail silently
|
||||
and return `None`.
|
||||
:param cache: if set to `True` the parsed JSON data is remembered
|
||||
:param force: if set to ``True`` the mimetype is ignored.
|
||||
:param silent: if set to ``True`` this method will fail silently
|
||||
and return ``None``.
|
||||
:param cache: if set to ``True`` the parsed JSON data is remembered
|
||||
on the request.
|
||||
"""
|
||||
rv = getattr(self, '_cached_json', _missing)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue