Skip to content
Myr

Merge pull request #1240 from defuz/docs-style-fix-2

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Docs style fixes: ``FOO`` vs `FOO` (reloaded)

authored by Markus Unterwaditzer · committed by Markus Unterwaditzer · parents 2ab9144, 7e157ee · Browse files · 61 files+396 added−396 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

61 files+396 added−396 removed

  • other:+396 added−396 removed

61 files+396 added−396 removed

modified:docs/deploying/cgi.rst+4 added-4 removed
22 unmodified lines
23Creating a `.cgi` file24----------------------2526First you need to create the CGI application file. Let's call it27`yourapplication.cgi`::27:file:`yourapplication.cgi`::2829 #!/usr/bin/python30 from wsgiref.handlers import CGIHandler31 from yourapplication import app
3 unmodified lines
35Server Setup36------------3738Usually there are two ways to configure the server. Either just copy the39`.cgi` into a `cgi-bin` (and use `mod_rewrite` or something similar to39``.cgi`` into a :file:`cgi-bin` (and use `mod_rewrite` or something similar to40rewrite the URL) or let the server point to the file directly.4142In Apache for example you can put something like this into the config:43
1 unmodified line
4546 ScriptAlias /app /path/to/the/application.cgi4748On shared webhosting, though, you might not have access to your Apache config.49In this case, a file called `.htaccess`, sitting in the public directory you want50your app to be available, works too but the `ScriptAlias` directive won't49In this case, a file called ``.htaccess``, sitting in the public directory you want50your app to be available, works too but the ``ScriptAlias`` directive won't51work in that case:5253.. sourcecode:: apache54
7 unmodified lines
modified:docs/deploying/fastcgi.rst+6 added-6 removed
38 unmodified lines
3940The path has to be the exact same path you define in the server41config.4243Save the `yourapplication.fcgi` file somewhere you will find it again.44It makes sense to have that in `/var/www/yourapplication` or something43Save the :file:`yourapplication.fcgi` file somewhere you will find it again.44It makes sense to have that in :file:`/var/www/yourapplication` or something45similar.4647Make sure to set the executable bit on that file so that the servers48can execute it:
6 unmodified lines
55------------------5657The example above is good enough for a basic Apache deployment but your58`.fcgi` file will appear in your application URL e.g.59example.com/yourapplication.fcgi/news/. There are few ways to configure59``example.com/yourapplication.fcgi/news/``. There are few ways to configure60your application so that yourapplication.fcgi does not appear in the URL.61A preferable way is to use the ScriptAlias and SetHandler configuration62directives to route requests to the FastCGI server. The following example63uses FastCgiServer to start 5 instances of the application which will
88 unmodified lines
152 "^(/.*)$" => "/yourapplication.fcgi$1"153 )154155Remember to enable the FastCGI, alias and rewrite modules. This configuration156binds the application to `/yourapplication`. If you want the application to156binds the application to ``/yourapplication``. If you want the application to157work in the URL root you have to work around a lighttpd bug with the158:class:`~werkzeug.contrib.fixers.LighttpdCGIRootFix` middleware.159160Make sure to apply it only if you are mounting the application the URL
18 unmodified lines
179 fastcgi_param SCRIPT_NAME $fastcgi_script_name;180 fastcgi_pass unix:/tmp/yourapplication-fcgi.sock;181 }182183This configuration binds the application to `/yourapplication`. If you183This configuration binds the application to ``/yourapplication``. If you184want to have it in the URL root it's a bit simpler because you don't185have to figure out how to calculate `PATH_INFO` and `SCRIPT_NAME`::185have to figure out how to calculate ``PATH_INFO`` and ``SCRIPT_NAME``::186187 location / { try_files $uri @yourapplication; }188 location @yourapplication {189 include fastcgi_params;
51 unmodified lines
modified:docs/deploying/mod_wsgi.rst+7 added-7 removed
50 unmodified lines
5152Creating a `.wsgi` file53-----------------------5455To run your application you need a `yourapplication.wsgi` file. This file55To run your application you need a :file:`yourapplication.wsgi` file. This file56contains the code `mod_wsgi` is executing on startup to get the application57object. The object called `application` in that file is then used as58application.59
4 unmodified lines
64If you don't have a factory function for application creation but a singleton65instance you can directly import that one as `application`.6667Store that file somewhere that you will find it again (e.g.:68`/var/www/yourapplication`) and make sure that `yourapplication` and all68:file:`/var/www/yourapplication`) and make sure that `yourapplication` and all69the libraries that are in use are on the python load path. If you don't70want to install it system wide consider using a `virtual python`_71instance. Keep in mind that you will have to actually install your72application into the virtualenv as well. Alternatively there is the73option to just patch the path in the `.wsgi` file before the import::73option to just patch the path in the ``.wsgi`` file before the import::7475 import sys76 sys.path.insert(0, '/path/to/the/application')77
53 unmodified lines
131**Problem:** application does not run, errorlog shows SystemExit ignored132 You have a ``app.run()`` call in your application file that is not133 guarded by an ``if __name__ == '__main__':`` condition. Either134 remove that :meth:`~flask.Flask.run` call from the file and move it135 into a separate `run.py` file or put it into such an if block.135 into a separate :file:`run.py` file or put it into such an if block.136137**Problem:** application gives permission errors138 Probably caused by your application running as the wrong user. Make139 sure the folders the application needs access to have the proper
30 unmodified lines
170Support for Automatic Reloading171-------------------------------172173To help deployment tools you can activate support for automatic174reloading. Whenever something changes the `.wsgi` file, `mod_wsgi` will174reloading. Whenever something changes the ``.wsgi`` file, `mod_wsgi` will175reload all the daemon processes for us.176177For that, just add the following directive to your `Directory` section:178
6 unmodified lines
185186Virtual environments have the advantage that they never install the187required dependencies system wide so you have a better control over what188is used where. If you want to use a virtual environment with mod_wsgi189you have to modify your `.wsgi` file slightly.189you have to modify your ``.wsgi`` file slightly.190191Add the following lines to the top of your `.wsgi` file::191Add the following lines to the top of your ``.wsgi`` file::192193 activate_this = '/path/to/env/bin/activate_this.py'194 execfile(activate_this, dict(__file__=activate_this))195
2 unmodified lines
modified:docs/deploying/uwsgi.rst+2 added-2 removed
49 unmodified lines
50 uwsgi_modifier1 30;51 uwsgi_pass unix:/tmp/uwsgi.sock;52 }5354This configuration binds the application to `/yourapplication`. If you want54This configuration binds the application to ``/yourapplication``. If you want55to have it in the URL root it's a bit simpler because you don't have to tell56it the WSGI `SCRIPT_NAME` or set the uwsgi modifier to make use of it::56it the WSGI ``SCRIPT_NAME`` or set the uwsgi modifier to make use of it::5758 location / { try_files $uri @yourapplication; }59 location @yourapplication {60 include uwsgi_params;
7 unmodified lines
modified:docs/deploying/wsgi-standalone.rst+4 added-4 removed
72 unmodified lines
73------------7475If you deploy your application using one of these servers behind an HTTP proxy76you will need to rewrite a few headers in order for the application to work.77The two problematic values in the WSGI environment usually are `REMOTE_ADDR`78and `HTTP_HOST`. You can configure your httpd to pass these headers, or you77The two problematic values in the WSGI environment usually are ``REMOTE_ADDR``78and ``HTTP_HOST``. You can configure your httpd to pass these headers, or you79can fix them in middleware. Werkzeug ships a fixer that will solve some common80setups, but you might want to write your own WSGI middleware for specific81setups.82
20 unmodified lines
103 }104 }105106If your httpd is not providing these headers, the most common setup invokes the107host being set from `X-Forwarded-Host` and the remote address from108`X-Forwarded-For`::107host being set from ``X-Forwarded-Host`` and the remote address from108``X-Forwarded-For``::109110 from werkzeug.contrib.fixers import ProxyFix111 app.wsgi_app = ProxyFix(app.wsgi_app)112
21 unmodified lines
modified:docs/patterns/apierrors.rst+1 added-1 removed
2 unmodified lines
34It's very common to implement RESTful APIs on top of Flask. One of the5first thing that developers run into is the realization that the builtin6exceptions are not expressive enough for APIs and that the content type of7``text/html`` they are emitting is not very useful for API consumers.7:mimetype:`text/html` they are emitting is not very useful for API consumers.89The better solution than using ``abort`` to signal errors for invalid API10usage is to implement your own exception type and install an error handler11for it that produces the errors in the format the user is expecting.
52 unmodified lines
modified:docs/patterns/appdispatch.rst+4 added-4 removed
57 unmodified lines
58here is that each Flask application is a valid WSGI application and they59are combined by the dispatcher middleware into a larger one that60dispatched based on prefix.6162For example you could have your main application run on `/` and your63backend interface on `/backend`::62For example you could have your main application run on ``/`` and your63backend interface on ``/backend``::6465 from werkzeug.wsgi import DispatcherMiddleware66 from frontend_app import application as frontend67 from backend_app import application as backend
75 unmodified lines
143Dispatch by Path144----------------145146Dispatching by a path on the URL is very similar. Instead of looking at147the `Host` header to figure out the subdomain one simply looks at the147the ``Host`` header to figure out the subdomain one simply looks at the148request path up to the first slash::149150 from threading import Lock151 from werkzeug.wsgi import pop_path_info, peek_path_info
23 unmodified lines
175 app = self.default_app176 return app(environ, start_response)177178The big difference between this and the subdomain one is that this one179falls back to another application if the creator function returns `None`::179falls back to another application if the creator function returns ``None``::180181 from myapplication import create_app, default_app, get_user_for_prefix182183 def make_app(prefix):
5 unmodified lines
modified:docs/patterns/appfactories.rst+7 added-7 removed
58 unmodified lines
5960It's preferable to create your extensions and app factories so that the61extension object does not initially get bound to the application.6263Using `Flask-SQLAlchemy <http://pythonhosted.org/Flask-SQLAlchemy/>`_, 63Using `Flask-SQLAlchemy <http://pythonhosted.org/Flask-SQLAlchemy/>`_,64as an example, you should not do something along those lines::65 6566 def create_app(config_filename):67 app = Flask(__name__)68 app.config.from_pyfile(config_filename)69
1 unmodified line
7172But, rather, in model.py (or equivalent)::7374 db = SQLAlchemy()75 7576and in your application.py (or equivalent)::7778 def create_app(config_filename):79 app = Flask(__name__)
2 unmodified lines
82 from yourapplication.model import db83 db.init_app(app)8485Using this design pattern, no application-specific state is stored on the86extension object, so one extension object can be used for multiple apps. 86extension object, so one extension object can be used for multiple apps.87For more information about the design of extensions refer to :doc:`/extensiondev`.8889Using Applications90------------------9192So to use such an application you then have to create the application93first in a separate file otherwise the ``flask`` command won't be able94to find it. Here an example `exampleapp.py` file that creates such93first in a separate file otherwise the :command:`flask` command won't be able94to find it. Here an example :file:`exampleapp.py` file that creates such95an application::9697 from yourapplication import create_app98 app = create_app('/path/to/config.cfg')99100It can then be used with the ``flask`` command::100It can then be used with the :command:`flask` command::101102 flask --app=exampleapp run103104Factory Improvements
11 unmodified lines
modified:docs/patterns/caching.rst+1 added-1 removed
48 unmodified lines
4950To get an item from the cache call51:meth:`~werkzeug.contrib.cache.BaseCache.get` with a string as key name.52If something is in the cache, it is returned. Otherwise that function53will return `None`::53will return ``None``::5455 rv = cache.get('my-item')5657To add items to the cache, use the :meth:`~werkzeug.contrib.cache.BaseCache.set`
12 unmodified lines
modified:docs/patterns/celery.rst+1 added-1 removed
11 unmodified lines
12Installing Celery13-----------------1415Celery is on the Python Package Index (PyPI), so it can be installed with16standard Python tools like ``pip`` or ``easy_install``::16standard Python tools like :command:`pip` or :command:`easy_install`::1718 $ pip install celery1920Configuring Celery
72 unmodified lines
modified:docs/patterns/distribute.rst+12 added-12 removed
16 unmodified lines
17 provided by one package from another package. The best known feature of18 this system is the entry point support which allows one package to19 declare an "entry point" another package can hook into to extend the20 other package.21- **installation manager**: `easy_install`, which comes with distribute21- **installation manager**: :command:`easy_install`, which comes with distribute22 can install other libraries for you. You can also use `pip`_ which23 sooner or later will replace `easy_install` which does more than just23 sooner or later will replace :command:`easy_install` which does more than just24 installing packages for you.2526Flask itself, and all the libraries you can find on the cheeseshop27are distributed with either distribute, the older setuptools or distutils.2829In this case we assume your application is called30`yourapplication.py` and you are not using a module, but a :ref:`package30:file:`yourapplication.py` and you are not using a module, but a :ref:`package31<larger-applications>`. Distributing resources with standard modules is32not supported by `distribute`_ so we will not bother with it. If you have33not yet converted your application into a package, head over to the34:ref:`larger-applications` pattern to see how this can be done.
12 unmodified lines
4748Standard disclaimer applies: :ref:`you better use a virtualenv49<virtualenv>`.5051Your setup code always goes into a file named `setup.py` next to your51Your setup code always goes into a file named :file:`setup.py` next to your52application. The name of the file is only convention, but because53everybody will look for a file with that name, you better not change it.5455Yes, even if you are using `distribute`, you are importing from a package56called `setuptools`. `distribute` is fully backwards compatible with57`setuptools`, so it also uses the same import name.5859A basic `setup.py` file for a Flask application looks like this::59A basic :file:`setup.py` file for a Flask application looks like this::6061 from setuptools import setup6263 setup(
18 unmodified lines
82 )8384Most parameters to the `setup` function should be self explanatory,85`include_package_data` and `zip_safe` might not be.86`include_package_data` tells distribute to look for a `MANIFEST.in` file86`include_package_data` tells distribute to look for a :file:`MANIFEST.in` file87and install all the entries that match as package data. We will use this88to distribute the static files and templates along with the Python module89(see :ref:`distributing-resources`). The `zip_safe` flag can be used to90force or prevent zip Archive creation. In general you probably don't want
6 unmodified lines
97Distributing Resources98----------------------99100If you try to install the package you just created, you will notice that101folders like `static` or `templates` are not installed for you. The101folders like :file:`static` or :file:`templates` are not installed for you. The102reason for this is that distribute does not know which files to add for103you. What you should do, is to create a `MANIFEST.in` file next to your104`setup.py` file. This file lists all the files that should be added to103you. What you should do, is to create a :file:`MANIFEST.in` file next to your104:file:`setup.py` file. This file lists all the files that should be added to105your tarball::106107 recursive-include yourapplication/templates *108 recursive-include yourapplication/static *109110Don't forget that even if you enlist them in your `MANIFEST.in` file, they110Don't forget that even if you enlist them in your :file:`MANIFEST.in` file, they111won't be installed for you unless you set the `include_package_data`112parameter of the `setup` function to `True`!112parameter of the `setup` function to ``True``!113114115Declaring Dependencies116----------------------
27 unmodified lines
144Installing / Developing145-----------------------146147To install your application (ideally into a virtualenv) just run the148`setup.py` script with the `install` parameter. It will install your148:file:`setup.py` script with the `install` parameter. It will install your149application into the virtualenv's site-packages folder and also download150and install all dependencies::151152 $ python setup.py install
14 unmodified lines
modified:docs/patterns/fabric.rst+16 added-16 removed
13 unmodified lines
1415- Fabric 1.0 has to be installed locally. This tutorial assumes the16 latest version of Fabric.17- The application already has to be a package and requires a working18 `setup.py` file (:ref:`distribute-deployment`).18 :file:`setup.py` file (:ref:`distribute-deployment`).19- In the following example we are using `mod_wsgi` for the remote20 servers. You can of course use your own favourite server there, but21 for this example we chose Apache + `mod_wsgi` because it's very easy22 to setup and has a simple way to reload applications without root
1 unmodified line
2425Creating the first Fabfile26--------------------------2728A fabfile is what controls what Fabric executes. It is named `fabfile.py`28A fabfile is what controls what Fabric executes. It is named :file:`fabfile.py`29and executed by the `fab` command. All the functions defined in that file30will show up as `fab` subcommands. They are executed on one or more31hosts. These hosts can be defined either in the fabfile or on the command32line. In this case we will add them to the fabfile.
38 unmodified lines
71- `run` - executes a command on a remote server72- `local` - executes a command on the local machine73- `put` - uploads a file to the remote server74- `cd` - changes the directory on the serverside. This has to be used75 in combination with the `with` statement.75 in combination with the ``with`` statement.7677Running Fabfiles78----------------79
3 unmodified lines
8384 $ fab pack deploy8586However this requires that our server already has the87``/var/www/yourapplication`` folder created and88``/var/www/yourapplication/env`` to be a virtual environment. Furthermore89are we not creating the configuration or `.wsgi` file on the server. So87:file:`/var/www/yourapplication` folder created and88:file:`/var/www/yourapplication/env` to be a virtual environment. Furthermore89are we not creating the configuration or ``.wsgi`` file on the server. So90how do we bootstrap a new server into our infrastructure?9192This now depends on the number of servers we want to set up. If we just93have one application server (which the majority of applications will
5 unmodified lines
99 $ fab -H newserver.example.com bootstrap100101To setup a new server you would roughly do these steps:1021031. Create the directory structure in ``/var/www``::1031. Create the directory structure in :file:`/var/www`::104105 $ mkdir /var/www/yourapplication106 $ cd /var/www/yourapplication107 $ virtualenv --distribute env1081092. Upload a new `application.wsgi` file to the server and the110 configuration file for the application (eg: `application.cfg`)1092. Upload a new :file:`application.wsgi` file to the server and the110 configuration file for the application (eg: :file:`application.cfg`)1111123. Create a new Apache config for `yourapplication` and activate it.113 Make sure to activate watching for changes of the `.wsgi` file so1123. Create a new Apache config for ``yourapplication`` and activate it.113 Make sure to activate watching for changes of the ``.wsgi`` file so114 that we can automatically reload the application by touching it.115 (See :ref:`mod_wsgi-deployment` for more information)116117So now the question is, where do the `application.wsgi` and118`application.cfg` files come from?117So now the question is, where do the :file:`application.wsgi` and118:file:`application.cfg` files come from?119120The WSGI File121-------------122
18 unmodified lines
141The Configuration File142----------------------143144Now as mentioned above, the application will find the correct145configuration file by looking up the `YOURAPPLICATION_CONFIG` environment145configuration file by looking up the ``YOURAPPLICATION_CONFIG`` environment146variable. So we have to put the configuration in a place where the147application will able to find it. Configuration files have the unfriendly148quality of being different on all computers, so you do not version them149usually.150151A popular approach is to store configuration files for different servers152in a separate version control repository and check them out on all153servers. Then symlink the file that is active for the server into the154location where it's expected (eg: ``/var/www/yourapplication``).154location where it's expected (eg: :file:`/var/www/yourapplication`).155156Either way, in our case here we only expect one or two servers and we can157upload them ahead of time by hand.158
8 unmodified lines
167168Fabric will now connect to all servers and run the commands as written169down in the fabfile. First it will execute pack so that we have our170tarball ready and then it will execute deploy and upload the source code171to all servers and install it there. Thanks to the `setup.py` file we171to all servers and install it there. Thanks to the :file:`setup.py` file we172will automatically pull in the required libraries into our virtual173environment.174175Next Steps
21 unmodified lines
modified:docs/patterns/fileuploads.rst+4 added-4 removed
30 unmodified lines
31 app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER3233So first we need a couple of imports. Most should be straightforward, the34:func:`werkzeug.secure_filename` is explained a little bit later. The35`UPLOAD_FOLDER` is where we will store the uploaded files and the36`ALLOWED_EXTENSIONS` is the set of allowed file extensions. Then we add a35``UPLOAD_FOLDER`` is where we will store the uploaded files and the36``ALLOWED_EXTENSIONS`` is the set of allowed file extensions. Then we add a37URL rule by hand to the application. Now usually we're not doing that, so38why here? The reasons is that we want the webserver (or our development39server) to serve these files for us and so we only need a rule to generate40the URL to these files.
1 unmodified line
42Why do we limit the extensions that are allowed? You probably don't want43your users to be able to upload everything there if the server is directly44sending out the data to the client. That way you can make sure that users45are not able to upload HTML files that would cause XSS problems (see46:ref:`xss`). Also make sure to disallow `.php` files if the server46:ref:`xss`). Also make sure to disallow ``.php`` files if the server47executes them, but who has PHP installed on his server, right? :)4849Next the functions that check if an extension is valid and that uploads50the file and redirects the user to the URL for the uploaded file::
46 unmodified lines
9798 filename = "../../../../home/username/.bashrc"99100 Assuming the number of ``../`` is correct and you would join this with101 the `UPLOAD_FOLDER` the user might have the ability to modify a file on101 the ``UPLOAD_FOLDER`` the user might have the ability to modify a file on102 the server's filesystem he or she should not modify. This does require some103 knowledge about how the application looks like, but trust me, hackers104 are patient :)105
85 unmodified lines
modified:docs/patterns/flashing.rst+1 added-1 removed
36 unmodified lines
37 flash('You were successfully logged in')38 return redirect(url_for('index'))39 return render_template('login.html', error=error)4041And here the ``layout.html`` template which does the magic:41And here the :file:`layout.html` template which does the magic:4243.. sourcecode:: html+jinja4445 <!doctype html>
102 unmodified lines
modified:docs/patterns/jquery.rst+6 added-6 removed
17 unmodified lines
1819In order to use jQuery, you have to download it first and place it in the20static folder of your application and then ensure it's loaded. Ideally21you have a layout template that is used for all pages where you just have22to add a script statement to the bottom of your `<body>` to load jQuery:22to add a script statement to the bottom of your ``<body>`` to load jQuery:2324.. sourcecode:: html2526 <script type=text/javascript src="{{
37 unmodified lines
64 </script>6566The ``|safe`` is necessary in Flask before 0.10 so that Jinja does not67escape the JSON encoded string with HTML rules. Usually this would be68necessary, but we are inside a `script` block here where different rules68necessary, but we are inside a ``script`` block here where different rules69apply.7071.. admonition:: Information for Pros7273 In HTML the `script` tag is declared `CDATA` which means that entities73 In HTML the ``script`` tag is declared ``CDATA`` which means that entities74 will not be parsed. Everything until ``</script>`` is handled as script.75 This also means that there must never be any ``</`` between the script76 tags. ``|tojson`` is kind enough to do the right thing here and77 escape slashes for you (``{{ "</script>"|tojson|safe }}`` is rendered as
40 unmodified lines
118119The HTML120--------121122Your index.html template either has to extend a `layout.html` template with122Your index.html template either has to extend a :file:`layout.html` template with123jQuery loaded and the `$SCRIPT_ROOT` variable set, or do that on the top.124Here's the HTML code needed for our little application (`index.html`).124Here's the HTML code needed for our little application (:file:`index.html`).125Notice that we also drop the script directly into the HTML here. It is126usually a better idea to have that in a separate script file:127128.. sourcecode:: html
26 unmodified lines
1553. ``element.bind('event', func)`` specifies a function that should run156 when the user clicked on the element. If that function returns157 `false`, the default behavior will not kick in (in this case, navigate158 to the `#` URL).1594. ``$.getJSON(url, data, func)`` sends a `GET` request to `url` and will1594. ``$.getJSON(url, data, func)`` sends a ``GET`` request to `url` and will160 send the contents of the `data` object as query parameters. Once the161 data arrived, it will call the given function with the return value as162 argument. Note that we can use the `$SCRIPT_ROOT` variable here that163 we set earlier.
5 unmodified lines
modified:docs/patterns/lazyloading.rst+1 added-1 removed
31 unmodified lines
32 def user(username):33 pass3435Then the centralized approach you would have one file with the views36(`views.py`) but without any decorator::36(:file:`views.py`) but without any decorator::3738 def index():39 pass40
64 unmodified lines
modified:docs/patterns/mongokit.rst+3 added-3 removed
18 unmodified lines
1920The default behavior of MongoKit is the declarative one that is based on21common ideas from Django or the SQLAlchemy declarative extension.2223Here an example `app.py` module for your application::23Here an example :file:`app.py` module for your application::2425 from flask import Flask26 from mongokit import Connection, Document27
18 unmodified lines
46MongoDB is schemaless. This means you can modify the data structure from one47insert query to the next without any problem. MongoKit is just schemaless48too, but implements some validation to ensure data integrity.4950Here is an example document (put this also into `app.py`, e.g.)::50Here is an example document (put this also into :file:`app.py`, e.g.)::5152 def max_length(length):53 def validate(value):54 if len(value) <= length:
20 unmodified lines
7576This example shows you how to define your schema (named structure), a77validator for the maximum character length and uses a special MongoKit feature78called `use_dot_notation`. Per default MongoKit behaves like a python79dictionary but with `use_dot_notation` set to `True` you can use your79dictionary but with `use_dot_notation` set to ``True`` you can use your80documents like you use models in nearly any other ORM by using dots to81separate between attributes.8283You can insert entries into the database like this:
58 unmodified lines
modified:docs/patterns/packages.rst+11 added-11 removed
19 unmodified lines
20Simple Packages21---------------2223To convert that into a larger one, just create a new folder24`yourapplication` inside the existing one and move everything below it.25Then rename `yourapplication.py` to `__init__.py`. (Make sure to delete26all `.pyc` files first, otherwise things would most likely break)24:file:`yourapplication` inside the existing one and move everything below it.25Then rename :file:`yourapplication.py` to :file:`__init__.py`. (Make sure to delete26all ``.pyc`` files first, otherwise things would most likely break)2728You should then end up with something like that::2930 /yourapplication
9 unmodified lines
4041But how do you run your application now? The naive ``python42yourapplication/__init__.py`` will not work. Let's just say that Python43does not want modules in packages to be the startup file. But that is not44a big problem, just add a new file called `runserver.py` next to the inner45`yourapplication` folder with the following contents::44a big problem, just add a new file called :file:`runserver.py` next to the inner45:file:`yourapplication` folder with the following contents::4647 from yourapplication import app48 app.run(debug=True)49
1 unmodified line
51into multiple modules. The only thing you have to remember is the52following quick checklist:53541. the `Flask` application object creation has to be in the55 `__init__.py` file. That way each module can import it safely and the55 :file:`__init__.py` file. That way each module can import it safely and the56 `__name__` variable will resolve to the correct package.572. all the view functions (the ones with a :meth:`~flask.Flask.route`58 decorator on top) have to be imported in the `__init__.py` file.58 decorator on top) have to be imported in the :file:`__init__.py` file.59 Not the object itself, but the module it is in. Import the view module60 **after the application object is created**.6162Here's an example `__init__.py`::62Here's an example :file:`__init__.py`::6364 from flask import Flask65 app = Flask(__name__)6667 import yourapplication.views6869And this is what `views.py` would look like::69And this is what :file:`views.py` would look like::7071 from yourapplication import app7273 @app.route('/')
18 unmodified lines
92.. admonition:: Circular Imports9394 Every Python programmer hates them, and yet we just added some:95 circular imports (That's when two modules depend on each other. In this96 case `views.py` depends on `__init__.py`). Be advised that this is a96 case :file:`views.py` depends on :file:`__init__.py`). Be advised that this is a97 bad idea in general but here it is actually fine. The reason for this is98 that we are not actually using the views in `__init__.py` and just98 that we are not actually using the views in :file:`__init__.py` and just99 ensuring the module is imported and we are doing that at the bottom of100 the file.101102 There are still some problems with that approach but if you want to use
13 unmodified lines
modified:docs/patterns/sqlalchemy.rst+4 added-4 removed
31 unmodified lines
32SQLAlchemy. It allows you to define tables and models in one go, similar33to how Django works. In addition to the following text I recommend the34official documentation on the `declarative`_ extension.3536Here the example `database.py` module for your application::36Here the example :file:`database.py` module for your application::3738 from sqlalchemy import create_engine39 from sqlalchemy.orm import scoped_session, sessionmaker40 from sqlalchemy.ext.declarative import declarative_base
28 unmodified lines
69 @app.teardown_appcontext70 def shutdown_session(exception=None):71 db_session.remove()7273Here is an example model (put this into `models.py`, e.g.)::73Here is an example model (put this into :file:`models.py`, e.g.)::7475 from sqlalchemy import Column, Integer, String76 from yourapplication.database import Base77
43 unmodified lines
121flexible but a little more to type. In general it works like the122declarative approach, so make sure to also split up your application into123multiple modules in a package.124125Here is an example `database.py` module for your application::125Here is an example :file:`database.py` module for your application::126127 from sqlalchemy import create_engine, MetaData128 from sqlalchemy.orm import scoped_session, sessionmaker129
14 unmodified lines
144 @app.teardown_appcontext145 def shutdown_session(exception=None):146 db_session.remove()147148Here is an example table and model (put this into `models.py`)::148Here is an example table and model (put this into :file:`models.py`)::149150 from sqlalchemy import Table, Column, Integer, String151 from sqlalchemy.orm import mapper152 from yourapplication.database import metadata, db_session
66 unmodified lines
modified:docs/patterns/templateinheritance.rst+1 added-1 removed
12 unmodified lines
1314Base Template15-------------1617This template, which we'll call ``layout.html``, defines a simple HTML skeleton17This template, which we'll call :file:`layout.html`, defines a simple HTML skeleton18document that you might use for a simple two-column page. It's the job of19"child" templates to fill the empty blocks with content:2021.. sourcecode:: html+jinja
49 unmodified lines
modified:docs/patterns/viewdecorators.rst+9 added-9 removed
21 unmodified lines
22often forgotten, but you don't have to do that by hand, there is a23function for that that is used like a decorator (:func:`functools.wraps`).2425This example assumes that the login page is called ``'login'`` and that26the current user is stored as `g.user` and `None` if there is no-one26the current user is stored as `g.user` and ``None`` if there is no-one27logged in::2829 from functools import wraps30 from flask import g, request, redirect, url_for
88 unmodified lines
119As you can see, if no template name is provided it will use the endpoint120of the URL map with dots converted to slashes + ``'.html'``. Otherwise121the provided template name is used. When the decorated function returns,122the dictionary returned is passed to the template rendering function. If123`None` is returned, an empty dictionary is assumed, if something else than123``None`` is returned, an empty dictionary is assumed, if something else than124a dictionary is returned we return it from the function unchanged. That125way you can still use the redirect function or return simple strings.126127Here is the code for that decorator::
22 unmodified lines
150Endpoint Decorator151------------------152153When you want to use the werkzeug routing system for more flexibility you154need to map the endpoint as defined in the :class:`~werkzeug.routing.Rule` 155to a view function. This is possible with this decorator. For example:: 154need to map the endpoint as defined in the :class:`~werkzeug.routing.Rule`155to a view function. This is possible with this decorator. For example::156157 from flask import Flask158 from werkzeug.routing import Rule159160 app = Flask(__name__) 161 app.url_map.add(Rule('/', endpoint='index')) 160 app = Flask(__name__)161 app.url_map.add(Rule('/', endpoint='index'))162163 @app.endpoint('index') 164 def my_index(): 165 return "Hello world" 163 @app.endpoint('index')164 def my_index():165 return "Hello world"
modified:docs/patterns/wtforms.rst+7 added-7 removed
59 unmodified lines
6061Things to remember:62631. create the form from the request :attr:`~flask.request.form` value if64 the data is submitted via the HTTP `POST` method and65 :attr:`~flask.request.args` if the data is submitted as `GET`.64 the data is submitted via the HTTP ``POST`` method and65 :attr:`~flask.request.args` if the data is submitted as ``GET``.662. to validate the data, call the :func:`~wtforms.form.Form.validate`67 method which will return `True` if the data validates, `False`67 method which will return ``True`` if the data validates, ``False``68 otherwise.693. to access individual values from the form, access `form.<NAME>.data`.7071Forms in Templates
4 unmodified lines
76how easy this is. WTForms does half the form generation for us already.77To make it even nicer, we can write a macro that renders a field with78label and a list of errors if there are any.7980Here's an example `_formhelpers.html` template with such a macro:80Here's an example :file:`_formhelpers.html` template with such a macro:8182.. sourcecode:: html+jinja8384 {% macro render_field(field) %}
14 unmodified lines
99arguments will be inserted as HTML attributes. So for example you can100call ``render_field(form.username, class='username')`` to add a class to101the input element. Note that WTForms returns standard Python unicode102strings, so we have to tell Jinja2 that this data is already HTML escaped103with the `|safe` filter.103with the ``|safe`` filter.104105Here the `register.html` template for the function we used above which106takes advantage of the `_formhelpers.html` template:105Here the :file:`register.html` template for the function we used above which106takes advantage of the :file:`_formhelpers.html` template:107108.. sourcecode:: html+jinja109110 {% from "_formhelpers.html" import render_field %}
16 unmodified lines
modified:docs/tutorial/css.rst+1 added-1 removed
2 unmodified lines
3Step 7: Adding Style4====================56Now that everything else works, it's time to add some style to the7application. Just create a stylesheet called `style.css` in the `static`7application. Just create a stylesheet called :file:`style.css` in the :file:`static`8folder we created before:910.. sourcecode:: css11
20 unmodified lines
modified:docs/tutorial/dbcon.rst+1 added-1 removed
51 unmodified lines
52every time the app context tears down. So what does this mean?53Essentially the app context is created before the request comes in and is54destroyed (torn down) whenever the request finishes. A teardown can55happen because of two reasons: either everything went well (the error56parameter will be `None`) or an exception happened in which case the error56parameter will be ``None``) or an exception happened in which case the error57is passed to the teardown function.5859Curious about what these contexts mean? Have a look at the60:ref:`app-context` documentation to learn more.
18 unmodified lines
modified:docs/tutorial/dbinit.rst+4 added-4 removed
18 unmodified lines
19requires that we provide the path to the database which can introduce20errors. It's a good idea to add a function that initializes the database21for you to the application.2223To do this we can create a function and hook it into the ``flask`` command23To do this we can create a function and hook it into the :command:`flask` command24that initializes the database. Let me show you the code first. Just add25this function below the `connect_db` function in `flaskr.py`::25this function below the `connect_db` function in :file:`flaskr.py`::2627 def init_db():28 db = get_db()29 with app.open_resource('schema.sql', mode='r') as f:
6 unmodified lines
36 init_db()37 print 'Initialized the database.'3839The ``app.cli.command()`` decorator registers a new command with the40``flask`` script. When the command executes Flask will automatically40:command:`flask` script. When the command executes Flask will automatically41create a application context for us bound to the right application.42Within the function we can then access :attr:`flask.g` and other things as43we would expect. When the script ends, the application context tears down44and the database connection is released.
12 unmodified lines
57On that cursor there is a method to execute a complete script. Finally we58only have to commit the changes. SQLite 3 and other transactional59databases will not commit unless you explicitly tell it to.6061Now it is possible to create a database with the ``flask`` script::61Now it is possible to create a database with the :command:`flask` script::6263 flask --app=flaskr initdb64 Initialized the database.65
7 unmodified lines
modified:docs/tutorial/folders.rst+2 added-2 removed
11 unmodified lines
1213The `flaskr` folder is not a python package, but just something where we14drop our files. We will then put our database schema as well as main module15into this folder. It is done in the following way. The files inside16the `static` folder are available to users of the application via `HTTP`.16the :file:`static` folder are available to users of the application via HTTP.17This is the place where css and javascript files go. Inside the18`templates` folder Flask will look for `Jinja2`_ templates. The18:file:`templates` folder Flask will look for `Jinja2`_ templates. The19templates you create later in the tutorial will go in this directory.2021Continue with :ref:`tutorial-schema`.22
1 unmodified line
modified:docs/tutorial/setup.rst+10 added-10 removed
6 unmodified lines
7Let's call it flaskr.py. We will place this file inside the flaskr folder.8We will begin by adding the imports we need and by adding the config9section. For small applications, it is possible to drop the configuration10directly into the module, and this is what we will be doing here. However11a cleaner solution would be to create a separate `.ini` or `.py` file and11a cleaner solution would be to create a separate ``.ini`` or ``.py`` file and12load that or import the values from there.1314First we add the imports in `flaskr.py`::14First we add the imports in :file:`flaskr.py`::1516 # all the imports17 import os18 import sqlite319 from flask import Flask, request, session, g, redirect, url_for, abort, \20 render_template, flash2122Next we can create our actual application and initialize it with the23config from the same file, in `flaskr.py`::23config from the same file, in :file:`flaskr.py`::2425 # create our little application :)26 app = Flask(__name__)27 app.config.from_object(__name__)
25 unmodified lines
53 For a real-work application it's recommended to use54 :ref:`instance-folders` instead.5556Usually, it is a good idea to load a separate, environment specific57configuration file. Flask allows you to import multiple configurations and it 58will use the setting defined in the last import. This enables robust 59configuration setups. :meth:`~flask.Config.from_envvar` can help achieve this. 60 57configuration file. Flask allows you to import multiple configurations and it58will use the setting defined in the last import. This enables robust59configuration setups. :meth:`~flask.Config.from_envvar` can help achieve this.6061 app.config.from_envvar('FLASKR_SETTINGS', silent=True)6263Simply define the environment variable :envvar:`FLASKR_SETTINGS` that points to 64a config file to be loaded. The silent switch just tells Flask to not complain 63Simply define the environment variable :envvar:`FLASKR_SETTINGS` that points to64a config file to be loaded. The silent switch just tells Flask to not complain65if no such environment key is set.6667In addition to that you can use the :meth:`~flask.Config.from_object`68method on the config object and provide it with an import name of a
23 unmodified lines
92without problems. Do this with the following command::9394 flask --app=flaskr --debug run9596The ``--debug`` flag enables or disables the interactive debugger. *Never96The :option:`--debug` flag enables or disables the interactive debugger. *Never97leave debug mode activated in a production system*, because it will allow98users to execute code on the server!99100You will see a message telling you that server has started along with
13 unmodified lines
modified:docs/tutorial/templates.rst+4 added-4 removed
12 unmodified lines
1314We are also using template inheritance which makes it possible to reuse15the layout of the website in all pages.1617Put the following templates into the `templates` folder:17Put the following templates into the :file:`templates` folder:1819.. _Jinja2: http://jinja.pocoo.org/docs/templates2021layout.html
32 unmodified lines
5455show_entries.html56-----------------5758This template extends the `layout.html` template from above to display the59messages. Note that the `for` loop iterates over the messages we passed58This template extends the :file:`layout.html` template from above to display the59messages. Note that the ``for`` loop iterates over the messages we passed60in with the :func:`~flask.render_template` function. We also tell the61form to submit to your `add_entry` function and use `POST` as `HTTP`61form to submit to your `add_entry` function and use ``POST`` as HTTP62method:6364.. sourcecode:: html+jinja65
46 unmodified lines
modified:docs/tutorial/views.rst+4 added-4 removed
14 unmodified lines
15returned from the cursor look a bit like tuples because we are using16the :class:`sqlite3.Row` row factory.1718The view function will pass the entries as dicts to the19`show_entries.html` template and return the rendered one::19:file:`show_entries.html` template and return the rendered one::2021 @app.route('/')22 def show_entries():23 db = get_db()
4 unmodified lines
28Add New Entry29-------------3031This view lets the user add new entries if they are logged in. This only32responds to `POST` requests, the actual form is shown on the32responds to ``POST`` requests, the actual form is shown on the33`show_entries` page. If everything worked out well we will34:func:`~flask.flash` an information message to the next request and35redirect back to the `show_entries` page::36
8 unmodified lines
45 flash('New entry was successfully posted')46 return redirect(url_for('show_entries'))4748Note that we check that the user is logged in here (the `logged_in` key is49present in the session and `True`).49present in the session and ``True``).5051.. admonition:: Security Note5253 Be sure to use question marks when building SQL statements, as done in the
6 unmodified lines
6061These functions are used to sign the user in and out. Login checks the62username and password against the ones from the configuration and sets the63`logged_in` key in the session. If the user logged in successfully, that64key is set to `True`, and the user is redirected back to the `show_entries`64key is set to ``True``, and the user is redirected back to the `show_entries`65page. In addition, a message is flashed that informs the user that he or66she was logged in successfully. If an error occurred, the template is67notified about that, and the user is asked again::68
30 unmodified lines
modified:docs/api.rst+19 added-19 removed
31 unmodified lines
32 :members:3334 .. attribute:: form3536 A :class:`~werkzeug.datastructures.MultiDict` with the parsed form data from `POST`37 or `PUT` requests. Please keep in mind that file uploads will not36 A :class:`~werkzeug.datastructures.MultiDict` with the parsed form data from ``POST``37 or ``PUT`` requests. Please keep in mind that file uploads will not38 end up here, but instead in the :attr:`files` attribute.3940 .. attribute:: args41
28 unmodified lines
7071 .. attribute:: files7273 A :class:`~werkzeug.datastructures.MultiDict` with files uploaded as part of a74 `POST` or `PUT` request. Each file is stored as74 ``POST`` or ``PUT`` request. Each file is stored as75 :class:`~werkzeug.datastructures.FileStorage` object. It basically behaves like a76 standard file object you know from Python, with the difference that77 it also has a :meth:`~werkzeug.datastructures.FileStorage.save` function that can78 store the file on the filesystem.
35 unmodified lines
114 ============= ======================================================115116 .. attribute:: is_xhr117118 `True` if the request was triggered via a JavaScript118 ``True`` if the request was triggered via a JavaScript119 `XMLHttpRequest`. This only works with libraries that support the120 ``X-Requested-With`` header and set it to `XMLHttpRequest`.121 Libraries that do that are prototype, jQuery and Mochikit and122 probably some more.
54 unmodified lines
177 The following attributes are interesting:178179 .. attribute:: new180181 `True` if the session is new, `False` otherwise.181 ``True`` if the session is new, ``False`` otherwise.182183 .. attribute:: modified184185 `True` if the session object detected a modification. Be advised185 ``True`` if the session object detected a modification. Be advised186 that modifications on mutable structures are not picked up187 automatically, in that situation you have to explicitly set the188 attribute to `True` yourself. Here an example::188 attribute to ``True`` yourself. Here an example::189190 # this change is not picked up because a mutable object (here191 # a list) is changed.192 session['objects'].append(42)
1 unmodified line
194 session.modified = True195196 .. attribute:: permanent197198 If set to `True` the session lives for198 If set to ``True`` the session lives for199 :attr:`~flask.Flask.permanent_session_lifetime` seconds. The200 default is 31 days. If set to `False` (which is the default) the200 default is 31 days. If set to ``False`` (which is the default) the201 session will be deleted when the user closes the browser.202203204Session Interface
73 unmodified lines
278 is especially useful when combined with the :ref:`faking-resources`279 pattern for testing.280281 Additionally as of 0.10 you can use the :meth:`get` method to282 get an attribute or `None` (or the second argument) if it's not set.282 get an attribute or ``None`` (or the second argument) if it's not set.283 These two usages are now equivalent::284285 user = getattr(flask.g, 'user', None)286 user = flask.g.get('user', None)
88 unmodified lines
375 will have that method called and then the return value is serialized376 as string.377378The :func:`~htmlsafe_dumps` function of this json module is also available379as filter called ``|tojson`` in Jinja2. Note that inside `script`379as filter called ``|tojson`` in Jinja2. Note that inside ``script``380tags no escaping must take place, so make sure to disable escaping381with ``|safe`` if you intend to use it inside `script` tags unless381with ``|safe`` if you intend to use it inside ``script`` tags unless382you are using Flask 0.10 which implies that:383384.. sourcecode:: html+jinja385
129 unmodified lines
515.. versionadded:: 0.6516517.. data:: signals_available518519 `True` if the signaling system is available. This is the case519 ``True`` if the signaling system is available. This is the case520 when `blinker`_ is installed.521522.. data:: template_rendered523
179 unmodified lines
703 subdomain is assumed.704`**options` the options to be forwarded to the underlying705 :class:`~werkzeug.routing.Rule` object. A change to706 Werkzeug is handling of method options. methods is a list707 of methods this rule should be limited to (`GET`, `POST`708 etc.). By default a rule just listens for `GET` (and709 implicitly `HEAD`). Starting with Flask 0.6, `OPTIONS` is707 of methods this rule should be limited to (``GET``, ``POST``708 etc.). By default a rule just listens for ``GET`` (and709 implicitly ``HEAD``). Starting with Flask 0.6, ``OPTIONS`` is710 implicitly added and handled by the standard request711 handling. They have to be specified as keyword arguments.712=============== ==========================================================713
18 unmodified lines
732 methods from there.733734- `provide_automatic_options`: if this attribute is set Flask will735 either force enable or disable the automatic implementation of the736 HTTP `OPTIONS` response. This can be useful when working with737 decorators that want to customize the `OPTIONS` response on a per-view736 HTTP ``OPTIONS`` response. This can be useful when working with737 decorators that want to customize the ``OPTIONS`` response on a per-view738 basis.739740- `required_methods`: if this attribute is set, Flask will always add741 these methods when registering a URL rule even if the methods were
39 unmodified lines
781782 A special decorator that informs a click callback to be passed the783 script info object as first argument. This is normally not useful784 unless you implement very special commands like the run command which785 does not want the application to be loaded yet. 785 does not want the application to be loaded yet.786787.. autodata:: run_command788789.. autodata:: shell_command
modified:docs/blueprints.rst+4 added-4 removed
157 unmodified lines
158159 admin = Blueprint('admin', __name__, static_folder='static')160161By default the rightmost part of the path is where it is exposed on the162web. Because the folder is called ``static`` here it will be available at162web. Because the folder is called :file:`static` here it will be available at163the location of the blueprint + ``/static``. Say the blueprint is164registered for ``/admin`` the static folder will be at ``/admin/static``.165166The endpoint is named `blueprint_name.static` so you can generate URLs to
17 unmodified lines
184185So if you have a blueprint in the folder ``yourapplication/admin`` and you186want to render the template ``'admin/index.html'`` and you have provided187``templates`` as a `template_folder` you will have to create a file like188this: ``yourapplication/admin/templates/admin/index.html``.188this: :file:`yourapplication/admin/templates/admin/index.html`.189190To further reiterate this: if you have a blueprint named ``admin`` and you191want to render a template called ``index.html`` which is specific to this191want to render a template called :file:`index.html` which is specific to this192blueprint, the best idea is to lay out your templates like this::193194 yourpackage/195 blueprints/
2 unmodified lines
198 admin/199 index.html200 __init__.py201202And then when you want to render the template, use ``admin/index.html`` as202And then when you want to render the template, use :file:`admin/index.html` as203the name to look up the template by. If you encounter problems loading204the correct templates enable the ``EXPLAIN_TEMPLATE_LOADING`` config205variable which will instruct Flask to print out the steps it goes through206to locate templates on every ``render_template`` call.
33 unmodified lines
modified:docs/cli.rst+13 added-13 removed
13 unmodified lines
1415Basic Usage16-----------1718After installation of Flask you will now find a ``flask`` script installed18After installation of Flask you will now find a :command:`flask` script installed19into your virtualenv. If you don't want to install Flask or you have a20special use-case you can also use ``python -m flask`` to accomplish exactly21the same.22
1 unmodified line
24your Flask application's :attr:`Flask.cli` instance as well as some25built-in commands that are always there. Flask extensions can also26register more commands there if they desire so.2728For the ``flask`` script to work, an application needs to be discovered.28For the :command:`flask` script to work, an application needs to be discovered.29The two most common ways are either an environment variable30(``FLASK_APP``) or the ``--app`` / ``-a`` parameter. It should be the30(``FLASK_APP``) or the :option:`--app` / :option:`-a` parameter. It should be the31import path for your application or the path to a Python file. In the32latter case Flask will attempt to setup the Python path for you33automatically and discover the module name but that might not always work.3435In that imported file the name of the app needs to be called ``app`` or36optionally be specified after a colon.3738Given a ``hello.py`` file with the application in it named ``app`` this is38Given a :file:`hello.py` file with the application in it named ``app`` this is39how it can be run.4041Environment variables (On Windows use ``set`` instead of ``export``)::42
18 unmodified lines
6162Debug Flag63----------6465The ``flask`` script can be run with ``--debug`` or ``--no-debug`` to65The :command:`flask` script can be run with :option:`--debug` or :option:`--no-debug` to66automatically flip the debug flag of the application. This can also be67configured by setting ``FLASK_DEBUG`` to ``1`` or ``0``.6869Running a Shell
51 unmodified lines
121Factory Functions122-----------------123124In case you are using factory functions to create your application (see125:ref:`app-factories`) you will discover that the ``flask`` command cannot125:ref:`app-factories`) you will discover that the :command:`flask` command cannot126work with them directly. Flask won't be able to figure out how to127instantiate your application properly by itself. Because of this reason128the recommendation is to create a separate file that instantiates129applications. This is by far not the only way to make this work. Another
2 unmodified lines
132For instance if you have a factory function that creates an application133from a filename you could make a separate file that creates such an134application from an environment variable.135136This could be a file named ``autoapp.py`` with these contents::136This could be a file named :file:`autoapp.py` with these contents::137138 import os139 from yourapplication import create_app140 app = create_app(os.environ['YOURAPPLICATION_CONFIG'])
3 unmodified lines
144145 export YOURAPPLICATION_CONFIG=/path/to/config.cfg146 export FLASK_APP=/path/to/autoapp.py147148From this point onwards ``flask`` will find your application.148From this point onwards :command:`flask` will find your application.149150.. _custom-scripts:151152Custom Scripts153--------------154155While the most common way is to use the ``flask`` command, you can also155While the most common way is to use the :command:`flask` command, you can also156make your own "driver scripts". Since Flask uses click for the scripts157there is no reason you cannot hook these scripts into any click158application. There is one big caveat and that is, that commands159registered to :attr:`Flask.cli` will expect to be (indirectly at least)
1 unmodified line
161necessary so that the commands know which Flask application they have to162work with.163164To understand why you might want custom scripts you need to understand how165click finds and executes the Flask application. If you use the ``flask``165click finds and executes the Flask application. If you use the :command:`flask`166script you specify the application to work with on the command line or167environment variable as an import name. This is simple but it has some168limitations. Primarily it does not work with application factory169functions (see :ref:`app-factories`).
8 unmodified lines
178We won't go into detail now about the differences but if you are curious179you can have a look at the :ref:`script-info-object` section to learn all180about it.181182To explain all of this, here is an example ``manage.py`` script that182To explain all of this, here is an example :file:`manage.py` script that183manages a hypothetical wiki application. We will go through the details184afterwards::185186 import click
35 unmodified lines
222 Whenever click now needs to operate on a Flask application it will223 call that function with the script info and ask for it to be created.2244. In step 2 you could see that the config is passed to the actual225 creation function. This config comes from the :func:`script_info_option`226 decorator for the main script. It accepts a ``--config`` option and226 decorator for the main script. It accepts a :option:`--config` option and227 then stores it in the script info so we can use it to create the228 application.2295. All is rounded up by invoking the script.230
7 unmodified lines
238both provide custom commands to click as well as not loading your239application unless it has to. The reason for this is added flexibility.240241This way an application can provide custom commands, but even in the242absence of an application the ``flask`` script is still operational on a242absence of an application the :command:`flask` script is still operational on a243basic level. In addition to that it means that the individual commands244have the option to avoid creating an instance of the Flask application245unless required. This is very useful as it allows the server commands for246instance to load the application on a first request instead of
13 unmodified lines
modified:docs/config.rst+10 added-10 removed
54 unmodified lines
55``DEBUG`` enable/disable debug mode56``TESTING`` enable/disable testing mode57``PROPAGATE_EXCEPTIONS`` explicitly enable or disable the58 propagation of exceptions. If not set or59 explicitly set to `None` this is60 implicitly true if either `TESTING` or61 `DEBUG` is true.59 explicitly set to ``None`` this is60 implicitly true if either ``TESTING`` or61 ``DEBUG`` is true.62``PRESERVE_CONTEXT_ON_EXCEPTION`` By default if the application is in63 debug mode the request context is not64 popped on exceptions to enable debuggers65 to introspect the data. This can be
13 unmodified lines
79 for all of ``APPLICATION_ROOT`` or if80 that is not set for ``'/'``.81``SESSION_COOKIE_HTTPONLY`` controls if the cookie should be set82 with the httponly flag. Defaults to83 `True`.83 ``True``.84``SESSION_COOKIE_SECURE`` controls if the cookie should be set85 with the secure flag. Defaults to86 `False`.86 ``False``.87``PERMANENT_SESSION_LIFETIME`` the lifetime of a permanent session as88 :class:`datetime.timedelta` object.89 Starting with Flask 0.8 this can also be90 an integer representing seconds.91``SESSION_REFRESH_EACH_REQUEST`` this flag controls how permanent92 sessions are refreshed. If set to `True`92 sessions are refreshed. If set to ``True``93 (which is the default) then the cookie94 is refreshed each request which95 automatically bumps the lifetime. If96 set to `False` a `set-cookie` header is96 set to ``False`` a `set-cookie` header is97 only sent if the session is modified.98 Non permanent sessions are not affected99 by this.100``USE_X_SENDFILE`` enable/disable x-sendfile
25 unmodified lines
126``MAX_CONTENT_LENGTH`` If set to a value in bytes, Flask will127 reject incoming requests with a128 content length greater than this by129 returning a 413 status code.130``SEND_FILE_MAX_AGE_DEFAULT``: Default cache control max age to use with130``SEND_FILE_MAX_AGE_DEFAULT`` Default cache control max age to use with131 :meth:`~flask.Flask.send_static_file` (the132 default static file handler) and133 :func:`~flask.send_file`, in134 seconds. Override this value on a per-file
124 unmodified lines
259 app.config.from_envvar('YOURAPPLICATION_SETTINGS')260261This first loads the configuration from the262`yourapplication.default_settings` module and then overrides the values263with the contents of the file the :envvar:`YOURAPPLICATION_SETTINGS`263with the contents of the file the :envvar:``YOURAPPLICATION_SETTINGS``264environment variable points to. This environment variable can be set on265Linux or OS X with the export command in the shell before starting the266server::267
54 unmodified lines
322 app = Flask(__name__)323 app.config.from_object('yourapplication.default_settings')324 app.config.from_envvar('YOURAPPLICATION_SETTINGS')325326Then you just have to add a separate `config.py` file and export326Then you just have to add a separate :file:`config.py` file and export327``YOURAPPLICATION_SETTINGS=/path/to/config.py`` and you are done. However328there are alternative ways as well. For example you could use imports or329subclassing.330
132 unmodified lines
modified:docs/extensiondev.rst+6 added-6 removed
25 unmodified lines
26The name of the actual extension (the human readable name) however would27be something like "Flask-SimpleXML". Make sure to include the name28"Flask" somewhere in that name and that you check the capitalization.29This is how users can then register dependencies to your extension in30their `setup.py` files.30their :file:`setup.py` files.3132Flask sets up a redirect package called :data:`flask.ext` where users33should import the extensions from. If you for instance have a package34called ``flask_something`` users would import it as
6 unmodified lines
41:ref:`app-factories` pattern to create their application as needed to aid42unittests and to support multiple configurations. Because of that it is43crucial that your application supports that kind of behavior.4445Most importantly the extension must be shipped with a `setup.py` file and45Most importantly the extension must be shipped with a :file:`setup.py` file and46registered on PyPI. Also the development checkout link should work so47that people can easily install the development version into their48virtualenv without having to download the library by hand.49
19 unmodified lines
6970setup.py71````````7273The next file that is absolutely required is the `setup.py` file which is73The next file that is absolutely required is the :file:`setup.py` file which is74used to install your Flask extension. The following contents are75something you can work with::7677 """
180 unmodified lines
258 with app.app_context():259 cur = db.connection.cursor()260 cur.execute(...)261262At the end of the `with` block the teardown handles will be executed262At the end of the ``with`` block the teardown handles will be executed263automatically.264265Additionally, the ``init_app`` method is used to support the factory pattern266for creating apps::
98 unmodified lines
3652. It must ship a testing suite that can either be invoked with ``make test``366 or ``python setup.py test``. For test suites invoked with ``make367 test`` the extension has to ensure that all dependencies for the test368 are installed automatically. If tests are invoked with ``python setup.py369 test``, test dependencies can be specified in the `setup.py` file. The369 test``, test dependencies can be specified in the :file:`setup.py` file. The370 test suite also has to be part of the distribution.3713. APIs of approved extensions will be checked for the following372 characteristics:373
5 unmodified lines
3794. The license must be BSD/MIT/WTFPL licensed.3805. The naming scheme for official extensions is *Flask-ExtensionName* or381 *ExtensionName-Flask*.3826. Approved extensions must define all their dependencies in the383 `setup.py` file unless a dependency cannot be met because it is not383 :file:`setup.py` file unless a dependency cannot be met because it is not384 available on PyPI.3857. The extension must have documentation that uses one of the two Flask386 themes for Sphinx documentation.3878. The setup.py description (and thus the PyPI description) has to
33 unmodified lines
modified:docs/extensions.rst+2 added-2 removed
6 unmodified lines
7Finding Extensions8------------------910Flask extensions are listed on the `Flask Extension Registry`_ and can be11downloaded with ``easy_install`` or ``pip``. If you add a Flask extension12as dependency to your ``requirements.rst`` or ``setup.py`` file they are11downloaded with :command:`easy_install` or :command:`pip`. If you add a Flask extension12as dependency to your :file:`requirements.txt` or :file:`setup.py` file they are13usually installed with a simple command or when your application installs.1415Using Extensions16----------------
32 unmodified lines
modified:docs/foreword.rst+1 added-1 removed
28 unmodified lines
2930Flask has many configuration values, with sensible defaults, and a few31conventions when getting started. By convention templates and static files are32stored in subdirectories within the application's Python source tree, with the33names `templates` and `static` respectively. While this can be changed you33names :file:`templates` and :file:`static` respectively. While this can be changed you34usually don't have to, especially when getting started.3536Growing with Flask37------------------
20 unmodified lines
modified:docs/htmlfaq.rst+1 added-1 removed
14 unmodified lines
15However, barely any websites on the Internet are actual XHTML (which is16HTML processed using XML rules). There are a couple of major reasons17why this is the case. One of them is Internet Explorer's lack of proper18XHTML support. The XHTML spec states that XHTML must be served with the MIME19type `application/xhtml+xml`, but Internet Explorer refuses to read files19type :mimetype:`application/xhtml+xml`, but Internet Explorer refuses to read files20with that MIME type.21While it is relatively easy to configure Web servers to serve XHTML properly,22few people do. This is likely because properly using XHTML can be quite23painful.
184 unmodified lines
modified:docs/installation.rst+11 added-11 removed
52 unmodified lines
53in your package manager. If you use Ubuntu, try::5455 $ sudo apt-get install python-virtualenv5657If you are on Windows and don't have the `easy_install` command, you must57If you are on Windows and don't have the :command:`easy_install` command, you must58install it first. Check the :ref:`windows-easy-install` section for more59information about how to do that. Once you have it installed, run the same60commands as above, but without the `sudo` prefix.60commands as above, but without the :command:`sudo` prefix.6162Once you have virtualenv installed, just fire up a shell and create63your own environment. I usually create a project folder and a `venv`63your own environment. I usually create a project folder and a :file:`venv`64folder within::6566 $ mkdir myproject67 $ cd myproject
30 unmodified lines
98System-Wide Installation99------------------------100101This is possible as well, though I do not recommend it. Just run102`pip` with root privileges::102:command:`pip` with root privileges::103104 $ sudo pip install Flask105106(On Windows systems, run it in a command-prompt window with administrator107privileges, and leave out `sudo`.)107privileges, and leave out :command:`sudo`.)108109110Living on the Edge111------------------112113If you want to work with the latest version of Flask, there are two ways: you114can either let `pip` pull in the development version, or you can tell114can either let :command:`pip` pull in the development version, or you can tell115it to operate on a git checkout. Either way, virtualenv is recommended.116117Get the git checkout in a new virtualenv and run in development mode::118
37 unmodified lines
156you can upgrade them by running::157158 > pip install --upgrade pip setuptools159160Most often, once you pull up a command prompt you want to be able to type ``pip``161and ``python`` which will run those things, but this might not automatically happen160Most often, once you pull up a command prompt you want to be able to type :command:`pip`161and :command:`python` which will run those things, but this might not automatically happen162on Windows, because it doesn't know where those executables are (give either a try!).163164To fix this, you should be able to navigate to your Python install directory165(e.g ``C:\Python27``), then go to ``Tools``, then ``Scripts``; then find the166``win_add2path.py`` file and run that. Open a **new** Command Prompt and167check that you can now just type ``python`` to bring up the interpreter.165(e.g :file:`C:\Python27`), then go to :file:`Tools`, then :file:`Scripts`; then find the166:file:`win_add2path.py` file and run that. Open a **new** Command Prompt and167check that you can now just type :command:`python` to bring up the interpreter.168169Finally, to install `virtualenv`_, you can simply run::170171 > pip install virtualenv
5 unmodified lines
modified:docs/quickstart.rst+32 added-32 removed
18 unmodified lines
19 @app.route('/')20 def hello_world():21 return 'Hello World!'2223Just save it as `hello.py` (or something similar) and run it with your Python24interpreter. Make sure to not call your application `flask.py` because this23Just save it as :file:`hello.py` (or something similar) and run it with your Python24interpreter. Make sure to not call your application :file:`flask.py` because this25would conflict with Flask itself.2627To run the application you can either use the ``flask`` command or28python's ``-m`` switch with Flask::27To run the application you can either use the :command:`flask` command or28python's :option:`-m` switch with Flask::2930 $ flask -a hello run31 * Running on http://127.0.0.1:5000/32
45 unmodified lines
7879What to do if the Server does not Start80---------------------------------------8182In case the ``python -m flask`` fails or ``flask`` does not exist,82In case the ``python -m flask`` fails or :command:`flask` does not exist,83there are multiple reasons this might be the case. First of all you need84to look at the error message.8586Old Version of Flask87````````````````````8889Versions of Flask older than 1.0 use to have different ways to start the90application. In short, the ``flask`` command did not exist, and90application. In short, the :command:`flask` command did not exist, and91neither did ``python -m flask``. In that case you have two options:92either upgrade to newer Flask versions or have a look at the :ref:`server`93docs to see the alternative method for running a server.9495Python older 2.796````````````````9798In case you have a version of Python older than 2.7 ``python -m flask``99does not work. You can either use ``flask`` or ``python -m99does not work. You can either use :command:`flask` or ``python -m100flask.cli`` as an alternative. This is because Python before 2.7 does no101permit packages to act as executable modules. For more information see102:ref:`cli`.103104Invalid Import Name105```````````````````106107The ``-a`` argument to ``flask`` is the name of the module to import. In107The :option:`-a` argument to :command:`flask` is the name of the module to import. In108case that module is incorrectly named you will get an import error upon109start (or if debug is enabled when you navigate to the application). It110will tell you what it tried to import and why it failed.111
4 unmodified lines
116117Debug Mode118----------119120The ``flask`` script is nice to start a local development server, but120The :command:`flask` script is nice to start a local development server, but121you would have to restart it manually after each change to your code.122That is not very nice and Flask can do better. If you enable debug123support the server will reload itself on code changes, and it will also124provide you with a helpful debugger if things go wrong.125126There are different ways to enable the debug mode. The most obvious one127is the ``--debug`` parameter to the ``flask`` command::127is the :option:`--debug` parameter to the :command:`flask` command::128129 flask --debug -a hello run130131This does the following things:
159 unmodified lines
291HTTP Methods292````````````293294HTTP (the protocol web applications are speaking) knows different methods for295accessing URLs. By default, a route only answers to `GET` requests, but that295accessing URLs. By default, a route only answers to ``GET`` requests, but that296can be changed by providing the `methods` argument to the297:meth:`~flask.Flask.route` decorator. Here are some examples::298299 from flask import request
4 unmodified lines
304 do_the_login()305 else:306 show_the_login_form()307308If `GET` is present, `HEAD` will be added automatically for you. You309don't have to deal with that. It will also make sure that `HEAD` requests308If ``GET`` is present, ``HEAD`` will be added automatically for you. You309don't have to deal with that. It will also make sure that ``HEAD`` requests310are handled as the `HTTP RFC`_ (the document describing the HTTP311protocol) demands, so you can completely ignore that part of the HTTP312specification. Likewise, as of Flask 0.6, `OPTIONS` is implemented for you312specification. Likewise, as of Flask 0.6, ``OPTIONS`` is implemented for you313automatically as well.314315You have no idea what an HTTP method is? Worry not, here is a quick316introduction to HTTP methods and why they matter:
1 unmodified line
318The HTTP method (also often called "the verb") tells the server what the319clients wants to *do* with the requested page. The following methods are320very common:321322`GET`322``GET``323 The browser tells the server to just *get* the information stored on324 that page and send it. This is probably the most common method.325326`HEAD`326``HEAD``327 The browser tells the server to get the information, but it is only328 interested in the *headers*, not the content of the page. An329 application is supposed to handle that as if a `GET` request was329 application is supposed to handle that as if a ``GET`` request was330 received but to not deliver the actual content. In Flask you don't331 have to deal with that at all, the underlying Werkzeug library handles332 that for you.333334`POST`334``POST``335 The browser tells the server that it wants to *post* some new336 information to that URL and that the server must ensure the data is337 stored and only stored once. This is how HTML forms usually338 transmit data to the server.339340`PUT`341 Similar to `POST` but the server might trigger the store procedure340``PUT``341 Similar to ``POST`` but the server might trigger the store procedure342 multiple times by overwriting the old values more than once. Now you343 might be asking why this is useful, but there are some good reasons344 to do it this way. Consider that the connection is lost during345 transmission: in this situation a system between the browser and the346 server might receive the request safely a second time without breaking347 things. With `POST` that would not be possible because it must only347 things. With ``POST`` that would not be possible because it must only348 be triggered once.349350`DELETE`350``DELETE``351 Remove the information at the given location.352353`OPTIONS`353``OPTIONS``354 Provides a quick way for a client to figure out which methods are355 supported by this URL. Starting with Flask 0.6, this is implemented356 for you automatically.357358Now the interesting part is that in HTML4 and XHTML1, the only methods a359form can submit to the server are `GET` and `POST`. But with JavaScript359form can submit to the server are ``GET`` and ``POST``. But with JavaScript360and future HTML standards you can use the other methods as well. Furthermore361HTTP has become quite popular lately and browsers are no longer the only362clients that are using HTTP. For instance, many revision control systems363use it.
5 unmodified lines
369370Dynamic web applications also need static files. That's usually where371the CSS and JavaScript files are coming from. Ideally your web server is372configured to serve them for you, but during development Flask can do that373as well. Just create a folder called `static` in your package or next to374your module and it will be available at `/static` on the application.373as well. Just create a folder called :file:`static` in your package or next to374your module and it will be available at ``/static`` on the application.375376To generate URLs for static files, use the special ``'static'`` endpoint name::377378 url_for('static', filename='style.css')379380The file has to be stored on the filesystem as ``static/style.css``.380The file has to be stored on the filesystem as :file:`static/style.css`.381382Rendering Templates383-------------------384
13 unmodified lines
398 @app.route('/hello/<name>')399 def hello(name=None):400 return render_template('hello.html', name=name)401402Flask will look for templates in the `templates` folder. So if your402Flask will look for templates in the :file:`templates` folder. So if your403application is a module, this folder is next to that module, if it's a404package it's actually inside your package:405406**Case 1**: a module::
102 unmodified lines
509will notice that code which depends on a request object will suddenly break510because there is no request object. The solution is creating a request511object yourself and binding it to the context. The easiest solution for512unit testing is to use the :meth:`~flask.Flask.test_request_context`513context manager. In combination with the `with` statement it will bind a513context manager. In combination with the ``with`` statement it will bind a514test request so that you can interact with it. Here is an example::515516 from flask import request517
22 unmodified lines
540 from flask import request541542The current request method is available by using the543:attr:`~flask.request.method` attribute. To access form data (data544transmitted in a `POST` or `PUT` request) you can use the544transmitted in a ``POST`` or ``PUT`` request) you can use the545:attr:`~flask.request.form` attribute. Here is a full example of the two546attributes mentioned above::547548 @app.route('/login', methods=['POST', 'GET'])
20 unmodified lines
569570 searchword = request.args.get('key', '')571572We recommend accessing URL parameters with `get` or by catching the573`KeyError` because users might change the URL and presenting them a 400573:exc:`KeyError` because users might change the URL and presenting them a 400574bad request page in that case is not user friendly.575576For a full list of methods and attributes of the request object, head over577to the :class:`~flask.request` documentation.
129 unmodified lines
707708The return value from a view function is automatically converted into a709response object for you. If the return value is a string it's converted710into a response object with the string as response body, a ``200 OK``711status code and a ``text/html`` mimetype. The logic that Flask applies to711status code and a :mimetype:`text/html` mimetype. The logic that Flask applies to712converting return values into response objects is as follows:7137141. If a response object of the correct type is returned it's directly715 returned from the view.
178 unmodified lines
modified:docs/reqcontext.rst+3 added-3 removed
35 unmodified lines
36us a :class:`~flask.ctx.RequestContext`:3738>>> ctx = app.test_request_context('/?next=http://example.com/')3940This context can be used in two ways. Either with the `with` statement40This context can be used in two ways. Either with the ``with`` statement41or by calling the :meth:`~flask.ctx.RequestContext.push` and42:meth:`~flask.ctx.RequestContext.pop` methods:4344>>> ctx.push()
29 unmodified lines
74 return response(environ, start_response)7576The method :meth:`~Flask.request_context` returns a new77:class:`~flask.ctx.RequestContext` object and uses it in combination with78the `with` statement to bind the context. Everything that is called from79the same thread from this point onwards until the end of the `with`78the ``with`` statement to bind the context. Everything that is called from79the same thread from this point onwards until the end of the ``with``80statement will have access to the request globals (:data:`flask.request`81and others).8283The request context internally works like a stack: The topmost level on
140 unmodified lines
modified:docs/security.rst+6 added-6 removed
23 unmodified lines
2425- generating HTML without the help of Jinja226- calling :class:`~flask.Markup` on data submitted by users27- sending out HTML from uploaded files, never do that, use the28 `Content-Disposition: attachment` header to prevent that problem.28 ``Content-Disposition: attachment`` header to prevent that problem.29- sending out textfiles from uploaded files. Some browsers are using30 content-type guessing based on the first few bytes so users could31 trick a browser to execute HTML.32
36 unmodified lines
69don't keep that in mind, some people might be able to trick your70application's users with social engineering to do stupid things without71them knowing.7273Say you have a specific URL that, when you sent `POST` requests to will74delete a user's profile (say `http://example.com/user/delete`). If an73Say you have a specific URL that, when you sent ``POST`` requests to will74delete a user's profile (say ``http://example.com/user/delete``). If an75attacker now creates a page that sends a post request to that page with76some JavaScript they just has to trick some users to load that page and77their profiles will end up being deleted.78
50 unmodified lines
129 "email": "admin@localhost"}130 ]131132And it is doing that of course only as long as you are logged in and only133for you. And it is doing that for all `GET` requests to a certain URL,133for you. And it is doing that for all ``GET`` requests to a certain URL,134say the URL for that request is135``http://example.com/api/get_friends.json``.136137So now what happens if a clever hacker is embedding this to his website
22 unmodified lines
160161If you know a bit of JavaScript internals you might know that it's162possible to patch constructors and register callbacks for setters. An163attacker can use this (like above) to get all the data you exported in164your JSON file. The browser will totally ignore the ``application/json``165mimetype if ``text/javascript`` is defined as content type in the script164your JSON file. The browser will totally ignore the :mimetype:`application/json`165mimetype if :mimetype:`text/javascript` is defined as content type in the script166tag and evaluate that as JavaScript. Because top-level array elements are167allowed (albeit useless) and we hooked in our own constructor, after that168page loaded the data from the JSON response is in the `captured` array.169
6 unmodified lines
modified:docs/server.rst+5 added-5 removed
4 unmodified lines
56.. currentmodule:: flask78Starting with Flask 1.0 there are multiple built-in ways to run a9development server. The best one is the ``flask`` command line utility9development server. The best one is the :command:`flask` command line utility10but you can also continue using the :meth:`Flask.run` method.1112Command Line13------------1415The ``flask`` command line script (:ref:`cli`) is strongly recommende for15The :command:`flask` command line script (:ref:`cli`) is strongly recommende for16development because it provides a superior reload experience due to how it17loads the application. The basic usage is like this::1819 $ flask -a my_application --debug run2021This will enable the debugger, the reloader and then start the server on 21This will enable the debugger, the reloader and then start the server on22*http://localhost:5000/*.2324The individual features of the server can be controlled by passing more25arguments to the ``run`` option. For instance the reloader can be
5 unmodified lines
31-------3233The alternative way to start the application is through the34:meth:`Flask.run` method. This will immediately launch a local server35exactly the same way the ``flask`` script does.35exactly the same way the :command:`flask` script does.3637Example::3839 if __name__ == '__main__':40 app.run()4142This works well for the common case but it does not work well for43development which is why from Flask 1.0 onwards the ``flask`` method is43development which is why from Flask 1.0 onwards the :command:`flask` method is44recommended. The reason for this is that due to how the reload mechanism45works there are some bizarre side-effects (like executing certain code46twice, sometimes crashing without message or dying when a syntax or47import error happens).
3 unmodified lines
modified:docs/shell.rst+1 added-1 removed
43 unmodified lines
44us a :class:`~flask.ctx.RequestContext`:4546>>> ctx = app.test_request_context()4748Normally you would use the `with` statement to make this request object48Normally you would use the ``with`` statement to make this request object49active, but in the shell it's easier to use the50:meth:`~flask.ctx.RequestContext.push` and51:meth:`~flask.ctx.RequestContext.pop` methods by hand:52
51 unmodified lines
modified:docs/signals.rst+2 added-2 removed
75 unmodified lines
76Make sure to subscribe with an extra ``**extra`` argument so that your77calls don't fail if Flask introduces new arguments to the signals.7879All the template rendering in the code issued by the application `app`80in the body of the `with` block will now be recorded in the `templates`80in the body of the ``with`` block will now be recorded in the `templates`81variable. Whenever a template is rendered, the template object as well as82context are appended to it.8384Additionally there is a convenient helper method
62 unmodified lines
147 def save(self):148 model_saved.send(self)149150Try to always pick a good sender. If you have a class that is emitting a151signal, pass `self` as sender. If you are emitting a signal from a random151signal, pass ``self`` as sender. If you are emitting a signal from a random152function, you can pass ``current_app._get_current_object()`` as sender.153154.. admonition:: Passing Proxies as Senders155
197 unmodified lines
modified:docs/styleguide.rst+1 added-1 removed
106 unmodified lines
107Comparisons:108 - against arbitrary types: ``==`` and ``!=``109 - against singletons with ``is`` and ``is not`` (eg: ``foo is not110 None``)111 - never compare something with `True` or `False` (for example never111 - never compare something with ``True`` or ``False`` (for example never112 do ``foo == False``, do ``not foo`` instead)113114Negated containment checks:115 use ``foo not in bar`` instead of ``not foo in bar``
85 unmodified lines
modified:docs/templating.rst+2 added-2 removed
103 unmodified lines
104 This function converts the given object into JSON representation. This105 is for example very helpful if you try to generate JavaScript on the106 fly.107108 Note that inside `script` tags no escaping must take place, so make108 Note that inside ``script`` tags no escaping must take place, so make109 sure to disable escaping with ``|safe`` before Flask 0.10 if you intend110 to use it inside `script` tags:110 to use it inside ``script`` tags:111112 .. sourcecode:: html+jinja113114 <script type=text/javascript>
108 unmodified lines
modified:docs/testing.rst+6 added-6 removed
28 unmodified lines
29The Testing Skeleton30--------------------3132In order to test the application, we add a second module33(`flaskr_tests.py`) and create a unittest skeleton there::33(:file:`flaskr_tests.py`) and create a unittest skeleton there::3435 import os36 import flaskr37 import unittest
73 unmodified lines
111112Notice that our test functions begin with the word `test`; this allows113:mod:`unittest` to automatically identify the method as a test to run.114115By using `self.app.get` we can send an HTTP `GET` request to the application with115By using `self.app.get` we can send an HTTP ``GET`` request to the application with116the given path. The return value will be a :class:`~flask.Flask.response_class` object.117We can now use the :attr:`~werkzeug.wrappers.BaseResponse.data` attribute to inspect118the return value (as string) from the application. In this case, we ensure that119``'No entries here so far'`` is part of the output.
81 unmodified lines
201--------------------202203Besides using the test client as shown above, there is also the204:meth:`~flask.Flask.test_request_context` method that can be used205in combination with the `with` statement to activate a request context205in combination with the ``with`` statement to activate a request context206temporarily. With this you can access the :class:`~flask.request`,207:class:`~flask.g` and :class:`~flask.session` objects like in view208functions. Here is a full example that demonstrates this approach::209
13 unmodified lines
223Note however that if you are using a test request context, the224:meth:`~flask.Flask.before_request` functions are not automatically called225same for :meth:`~flask.Flask.after_request` functions. However226:meth:`~flask.Flask.teardown_request` functions are indeed executed when227the test request context leaves the `with` block. If you do want the227the test request context leaves the ``with`` block. If you do want the228:meth:`~flask.Flask.before_request` functions to be called as well, you229need to call :meth:`~flask.Flask.preprocess_request` yourself::230231 app = flask.Flask(__name__)
75 unmodified lines
307308Sometimes it is helpful to trigger a regular request but still keep the309context around for a little longer so that additional introspection can310happen. With Flask 0.4 this is possible by using the311:meth:`~flask.Flask.test_client` with a `with` block::311:meth:`~flask.Flask.test_client` with a ``with`` block::312313 app = flask.Flask(__name__)314315 with app.test_client() as c:316 rv = c.get('/?tequila=42')317 assert request.args['tequila'] == '42'318319If you were to use just the :meth:`~flask.Flask.test_client` without320the `with` block, the `assert` would fail with an error because `request`320the ``with`` block, the ``assert`` would fail with an error because `request`321is no longer available (because you are trying to use it outside of the actual request).322323324Accessing and Modifying Sessions
29 unmodified lines
modified:docs/upgrading.rst+9 added-9 removed
12 unmodified lines
13This section of the documentation enumerates all the changes in Flask from14release to release and how you can change your code to have a painless15updating experience.1617If you want to use the `easy_install` command to upgrade your Flask18installation, make sure to pass it the ``-U`` parameter::17If you want to use the :command:`easy_install` command to upgrade your Flask18installation, make sure to pass it the :option:`-U` parameter::1920 $ easy_install -U Flask2122.. _upgrading-to-10:
68 unmodified lines
91:exc:`~werkzeug.exceptions.BadRequest` exception instead of letting the92default :exc:`ValueError` bubble up. This has the advantage that you no93longer have to handle that error to avoid an internal server error showing94up for the user. If you were catching this down explicitly in the past95as `ValueError` you will need to change this.95as :exc:`ValueError` you will need to change this.9697Due to a bug in the test client Flask 0.7 did not trigger teardown98handlers when the test client was used in a with statement. This was99since fixed but might require some changes in your test suites if you
35 unmodified lines
135136 patch -p1 < patchfile.diff1371385. If you were using per-module template folders you need to move some139 templates around. Previously if you had a folder named ``templates``139 templates around. Previously if you had a folder named :file:`templates`140 next to a blueprint named ``admin`` the implicit template path141 automatically was ``admin/index.html`` for a template file called142 ``templates/index.html``. This no longer is the case. Now you need143 to name the template ``templates/admin/index.html``. The tool will141 automatically was :file:`admin/index.html` for a template file called142 :file:`templates/index.html`. This no longer is the case. Now you need143 to name the template :file:`templates/admin/index.html`. The tool will144 not detect this so you will have to do that on your own.145146Please note that deprecation warnings are disabled by default starting147with Python 2.7. In order to see the deprecation warnings that might be
122 unmodified lines
270 some unnecessary leading dots in your code if you're not using271 modules.272- Blueprints do not automatically provide static folders. They will273 also no longer automatically export templates from a folder called274 `templates` next to their location however but it can be enabled from274 :file:`templates` next to their location however but it can be enabled from275 the constructor. Same with static files: if you want to continue276 serving static files you need to tell the constructor explicitly the277 path to the static folder (which can be relative to the blueprint's278 module path).279- Rendering templates was simplified. Now the blueprints can provide280 template folders which are added to a general template searchpath.281 This means that you need to add another subfolder with the blueprint's282 name into that folder if you want ``blueprintname/template.html`` as282 name into that folder if you want :file:`blueprintname/template.html` as283 the template name.284285If you continue to use the `Module` object which is deprecated, Flask will286restore the previous behavior as good as possible. However we strongly
96 unmodified lines
modified:docs/views.rst+2 added-2 removed
44 unmodified lines
45:meth:`~flask.views.View.as_view` class method. The string you pass to46that function is the name of the endpoint that view will then have. But47this by itself is not helpful, so let's refactor the code a bit::4849 4950 from flask.views import View5152 class ListView(View):53
16 unmodified lines
70 return User.query.all()7172This of course is not that helpful for such a small example, but it's good73enough to explain the basic principle. When you have a class-based view74the question comes up what `self` points to. The way this works is that74the question comes up what ``self`` points to. The way this works is that75whenever the request is dispatched a new instance of the class is created76and the :meth:`~flask.views.View.dispatch_request` method is called with77the parameters from the URL rule. The class itself is instantiated with78the parameters passed to the :meth:`~flask.views.View.as_view` function.
159 unmodified lines
modified:examples/flaskr/README+1 added-1 removed
21 unmodified lines
22 flask --app=flaskr run2324 the application will greet you on25 http://localhost:5000/26 2627 ~ Is it tested?2829 You betcha. Run the `test_flaskr.py` file to see30 the tests pass.
modified:examples/minitwit/README+1 added-1 removed
22 unmodified lines
23 flask --app=minitwit run2425 the application will greet you on26 http://localhost:5000/27 2728 ~ Is it tested?2930 You betcha. Run the `test_minitwit.py` file to31 see the tests pass.
modified:flask/app.py+53 added-53 removed
69 unmodified lines
7071 The name of the package is used to resolve resources from inside the72 package or the folder the module is contained in depending on if the73 package parameter resolves to an actual python package (a folder with74 an `__init__.py` file inside) or a standard module (just a `.py` file).74 an :file:`__init__.py` file inside) or a standard module (just a ``.py`` file).7576 For more information about resource loading, see :func:`open_resource`.7778 Usually you create a :class:`Flask` instance in your main module or79 in the `__init__.py` file of your package like this::79 in the :file:`__init__.py` file of your package like this::8081 from flask import Flask82 app = Flask(__name__)83
8 unmodified lines
92 module, `__name__` is always the correct value. If you however are93 using a package, it's usually recommended to hardcode the name of94 your package there.9596 For example if your application is defined in `yourapplication/app.py`96 For example if your application is defined in :file:`yourapplication/app.py`97 you should create it with one of the two versions below::9899 app = Flask('yourapplication')100 app = Flask(__name__.split('.')[0])
33 unmodified lines
134 :param instance_path: An alternative instance path for the application.135 By default the folder ``'instance'`` next to the136 package or module is assumed to be the instance137 path.138 :param instance_relative_config: if set to `True` relative filenames138 :param instance_relative_config: if set to ``True`` relative filenames139 for loading the config are assumed to140 be relative to the instance path instead141 of the application root.142 :param root_path: Flask by default will automatically calculate the path
49 unmodified lines
192 #:193 #: .. versionadded:: 1.0194 config_class = Config195196 #: The debug flag. Set this to `True` to enable debugging of the196 #: The debug flag. Set this to ``True`` to enable debugging of the197 #: application. In debug mode the debugger will kick in when an unhandled198 #: exception occurs and the integrated server will automatically reload199 #: the application if changes in the code are detected.200 #:201 #: This attribute can also be configured from the config with the `DEBUG`202 #: configuration key. Defaults to `False`.201 #: This attribute can also be configured from the config with the ``DEBUG``202 #: configuration key. Defaults to ``False``.203 debug = ConfigAttribute('DEBUG')204205 #: The testing flag. Set this to `True` to enable the test mode of205 #: The testing flag. Set this to ``True`` to enable the test mode of206 #: Flask extensions (and in the future probably also Flask itself).207 #: For example this might activate unittest helpers that have an208 #: additional runtime cost which should not be enabled by default.209 #:210 #: If this is enabled and PROPAGATE_EXCEPTIONS is not changed from the211 #: default it's implicitly enabled.212 #:213 #: This attribute can also be configured from the config with the214 #: `TESTING` configuration key. Defaults to `False`.214 #: ``TESTING`` configuration key. Defaults to ``False``.215 testing = ConfigAttribute('TESTING')216217 #: If a secret key is set, cryptographic components can use this to218 #: sign cookies and other things. Set this to a complex random value219 #: when you want to use the secure cookie for instance.220 #:221 #: This attribute can also be configured from the config with the222 #: `SECRET_KEY` configuration key. Defaults to `None`.222 #: ``SECRET_KEY`` configuration key. Defaults to ``None``.223 secret_key = ConfigAttribute('SECRET_KEY')224225 #: The secure cookie uses this for the name of the session cookie.226 #:227 #: This attribute can also be configured from the config with the228 #: `SESSION_COOKIE_NAME` configuration key. Defaults to ``'session'``228 #: ``SESSION_COOKIE_NAME`` configuration key. Defaults to ``'session'``229 session_cookie_name = ConfigAttribute('SESSION_COOKIE_NAME')230231 #: A :class:`~datetime.timedelta` which is used to set the expiration232 #: date of a permanent session. The default is 31 days which makes a233 #: permanent session survive for roughly one month.234 #:235 #: This attribute can also be configured from the config with the236 #: `PERMANENT_SESSION_LIFETIME` configuration key. Defaults to236 #: ``PERMANENT_SESSION_LIFETIME`` configuration key. Defaults to237 #: ``timedelta(days=31)``238 permanent_session_lifetime = ConfigAttribute('PERMANENT_SESSION_LIFETIME',239 get_converter=_make_timedelta)240
3 unmodified lines
244 #:245 #: .. versionadded:: 0.2246 #:247 #: This attribute can also be configured from the config with the248 #: `USE_X_SENDFILE` configuration key. Defaults to `False`.248 #: ``USE_X_SENDFILE`` configuration key. Defaults to ``False``.249 use_x_sendfile = ConfigAttribute('USE_X_SENDFILE')250251 #: The name of the logger to use. By default the logger name is the252 #: package name passed to the constructor.
110 unmodified lines
363 # support for the now deprecated `error_handlers` attribute. The364 # :attr:`error_handler_spec` shall be used now.365 self._error_handlers = {}366367 #: A dictionary of all registered error handlers. The key is `None`367 #: A dictionary of all registered error handlers. The key is ``None``368 #: for error handlers active on the application, otherwise the key is369 #: the name of the blueprint. Each key points to another dictionary370 #: where the key is the status code of the http exception. The371 #: special key `None` points to a list of tuples where the first item371 #: special key ``None`` points to a list of tuples where the first item372 #: is the class for the instance check and the second the error handler373 #: function.374 #:375 #: To register a error handler, use the :meth:`errorhandler`
2 unmodified lines
378379 #: A list of functions that are called when :meth:`url_for` raises a380 #: :exc:`~werkzeug.routing.BuildError`. Each function registered here381 #: is called with `error`, `endpoint` and `values`. If a function382 #: returns `None` or raises a `BuildError` the next function is382 #: returns ``None`` or raises a :exc:`BuildError` the next function is383 #: tried.384 #:385 #: .. versionadded:: 0.9386 self.url_build_error_handlers = []387388 #: A dictionary with lists of functions that should be called at the389 #: beginning of the request. The key of the dictionary is the name of390 #: the blueprint this function is active for, `None` for all requests.390 #: the blueprint this function is active for, ``None`` for all requests.391 #: This can for example be used to open database connections or392 #: getting hold of the currently logged in user. To register a393 #: function here, use the :meth:`before_request` decorator.394 self.before_request_funcs = {}
6 unmodified lines
401 self.before_first_request_funcs = []402403 #: A dictionary with lists of functions that should be called after404 #: each request. The key of the dictionary is the name of the blueprint405 #: this function is active for, `None` for all requests. This can for405 #: this function is active for, ``None`` for all requests. This can for406 #: example be used to open database connections or getting hold of the407 #: currently logged in user. To register a function here, use the408 #: :meth:`after_request` decorator.409 self.after_request_funcs = {}410411 #: A dictionary with lists of functions that are called after412 #: each request, even if an exception has occurred. The key of the413 #: dictionary is the name of the blueprint this function is active for,414 #: `None` for all requests. These functions are not allowed to modify414 #: ``None`` for all requests. These functions are not allowed to modify415 #: the request, and their return values are ignored. If an exception416 #: occurred while processing the request, it gets passed to each417 #: teardown_request function. To register a function here, use the418 #: :meth:`teardown_request` decorator.
11 unmodified lines
430431 #: A dictionary with lists of functions that can be used as URL432 #: value processor functions. Whenever a URL is built these functions433 #: are called to modify the dictionary of values in place. The key434 #: `None` here is used for application wide434 #: ``None`` here is used for application wide435 #: callbacks, otherwise the key is the name of the blueprint.436 #: Each of these functions has the chance to modify the dictionary437 #:438 #: .. versionadded:: 0.7439 self.url_value_preprocessors = {}440441 #: A dictionary with lists of functions that can be used as URL value442 #: preprocessors. The key `None` here is used for application wide442 #: preprocessors. The key ``None`` here is used for application wide443 #: callbacks, otherwise the key is the name of the blueprint.444 #: Each of these functions has the chance to modify the dictionary445 #: of URL values before they are used as the keyword arguments of the446 #: view function. For each function registered this one should also
4 unmodified lines
451 self.url_default_functions = {}452453 #: A dictionary with list of functions that are called without argument454 #: to populate the template context. The key of the dictionary is the455 #: name of the blueprint this function is active for, `None` for all455 #: name of the blueprint this function is active for, ``None`` for all456 #: requests. Each returns a dictionary that the template context is457 #: updated with. To register a function here, use the458 #: :meth:`context_processor` decorator.459 self.template_context_processors = {
62 unmodified lines
522 endpoint='static',523 view_func=self.send_static_file)524525 #: The click command line context for this application. Commands526 #: registered here show up in the ``flask`` command once the526 #: registered here show up in the :command:`flask` command once the527 #: application has been discovered. The default commands are528 #: provided by Flask itself and can be overridden.529 #:530 #: This is an instance of a :class:`click.Group` object.
28 unmodified lines
559 return self.import_name560561 @property562 def propagate_exceptions(self):563 """Returns the value of the `PROPAGATE_EXCEPTIONS` configuration563 """Returns the value of the ``PROPAGATE_EXCEPTIONS`` configuration564 value in case it's set, otherwise a sensible default is returned.565566 .. versionadded:: 0.7567 """
3 unmodified lines
571 return self.testing or self.debug572573 @property574 def preserve_context_on_exception(self):575 """Returns the value of the `PRESERVE_CONTEXT_ON_EXCEPTION`575 """Returns the value of the ``PRESERVE_CONTEXT_ON_EXCEPTION``576 configuration value in case it's set, otherwise a sensible default577 is returned.578579 .. versionadded:: 0.7
31 unmodified lines
611 return self.create_jinja_environment()612613 @property614 def got_first_request(self):615 """This attribute is set to `True` if the application started615 """This attribute is set to ``True`` if the application started616 handling the first request.617618 .. versionadded:: 0.8619 """
94 unmodified lines
714 :meth:`create_jinja_environment` instead.715 """716717 def select_jinja_autoescape(self, filename):718 """Returns `True` if autoescaping should be active for the given718 """Returns ``True`` if autoescaping should be active for the given719 template name.720721 .. versionadded:: 0.5722 """
49 unmodified lines
772 traceback screen active, but disable code execution.773774 It is not recommended to use this function for development with775 automatic reloading as this is badly supported. Instead you should776 be using the ``flask`` command line script's ``runserver``776 be using the :command:`flask` command line script's ``runserver``777 support.778779 .. admonition:: Keep in Mind780781 Flask will suppress any server error with a generic error page782 unless it is in debug mode. As such to enable just the783 interactive debugger without the code reloading, you have to784 invoke :meth:`run` with ``debug=True`` and ``use_reloader=False``.785 Setting ``use_debugger`` to `True` without being in debug mode785 Setting ``use_debugger`` to ``True`` without being in debug mode786 won't catch any exceptions because there won't be any to787 catch.788789 .. versionchanged:: 0.10
47 unmodified lines
837838 app.testing = True839 client = app.test_client()840841 The test client can be used in a `with` block to defer the closing down842 of the context until the end of the `with` block. This is useful if841 The test client can be used in a ``with`` block to defer the closing down842 of the context until the end of the ``with`` block. This is useful if843 you want to access the context locals for testing::844845 with app.test_client() as c:846 rv = c.get('/?vodka=42')
15 unmodified lines
862863 See :class:`~flask.testing.FlaskClient` for more information.864865 .. versionchanged:: 0.4866 added support for `with` block usage for the client.866 added support for ``with`` block usage for the client.867868 .. versionadded:: 0.7869 The `use_cookies` parameter was added as well as the ability870 to override the client to be used by setting the
96 unmodified lines
967 .. versionchanged:: 0.2968 `view_func` parameter added.969970 .. versionchanged:: 0.6971 `OPTIONS` is added automatically as method.971 ``OPTIONS`` is added automatically as method.972973 :param rule: the URL rule as string974 :param endpoint: the endpoint for the registered URL rule. Flask975 itself assumes the name of the view function as
3 unmodified lines
979 :param options: the options to be forwarded to the underlying980 :class:`~werkzeug.routing.Rule` object. A change981 to Werkzeug is handling of method options. methods982 is a list of methods this rule should be limited983 to (`GET`, `POST` etc.). By default a rule984 just listens for `GET` (and implicitly `HEAD`).985 Starting with Flask 0.6, `OPTIONS` is implicitly983 to (``GET``, ``POST`` etc.). By default a rule984 just listens for ``GET`` (and implicitly ``HEAD``).985 Starting with Flask 0.6, ``OPTIONS`` is implicitly986 added and handled by the standard request handling.987 """988 if endpoint is None:989 endpoint = _endpoint_from_view_func(view_func)
1 unmodified line
991 methods = options.pop('methods', None)992993 # if the methods are not given and the view_func object knows its994 # methods we can use that instead. If neither exists, we go with995 # a tuple of only `GET` as default.995 # a tuple of only ``GET`` as default.996 if methods is None:997 methods = getattr(view_func, 'methods', None) or ('GET',)998 if isinstance(methods, string_types):999 raise TypeError('Allowed methods have to be iterables of strings, '
47 unmodified lines
1047 :param options: the options to be forwarded to the underlying1048 :class:`~werkzeug.routing.Rule` object. A change1049 to Werkzeug is handling of method options. methods1050 is a list of methods this rule should be limited1051 to (`GET`, `POST` etc.). By default a rule1052 just listens for `GET` (and implicitly `HEAD`).1053 Starting with Flask 0.6, `OPTIONS` is implicitly1051 to (``GET``, ``POST`` etc.). By default a rule1052 just listens for ``GET`` (and implicitly ``HEAD``).1053 Starting with Flask 0.6, ``OPTIONS`` is implicitly1054 added and handled by the standard request handling.1055 """1056 def decorator(f):1057 endpoint = options.pop('endpoint', None)
43 unmodified lines
1101 Setting error handlers via assignments to :attr:`error_handler_spec`1102 however is discouraged as it requires fiddling with nested dictionaries1103 and the special case for arbitrary exception types.11041105 The first `None` refers to the active blueprint. If the error1106 handler should be application wide `None` shall be used.1105 The first ``None`` refers to the active blueprint. If the error1106 handler should be application wide ``None`` shall be used.11071108 .. versionadded:: 0.71109 Use :meth:`register_error_handler` instead of modifying1110 :attr:`error_handler_spec` directly, for application wide error
280 unmodified lines
1391 return handler(e)13921393 def trap_http_exception(self, e):1394 """Checks if an HTTP exception should be trapped or not. By default1395 this will return `False` for all exceptions except for a bad request1396 key error if ``TRAP_BAD_REQUEST_ERRORS`` is set to `True`. It1397 also returns `True` if ``TRAP_HTTP_EXCEPTIONS`` is set to `True`.1395 this will return ``False`` for all exceptions except for a bad request1396 key error if ``TRAP_BAD_REQUEST_ERRORS`` is set to ``True``. It1397 also returns ``True`` if ``TRAP_HTTP_EXCEPTIONS`` is set to ``True``.13981399 This is called for all HTTP exceptions raised by a view function.1400 If it returns `True` for any exception the error handler for this1400 If it returns ``True`` for any exception the error handler for this1401 exception is not called and it shows up as regular exception in the1402 traceback. This is helpful for debugging implicitly raised HTTP1403 exceptions.1404
153 unmodified lines
1558 func()1559 self._got_first_request = True15601561 def make_default_options_response(self):1562 """This method is called to create the default `OPTIONS` response.1562 """This method is called to create the default ``OPTIONS`` response.1563 This can be changed through subclassing to change the default1564 behavior of `OPTIONS` responses.1564 behavior of ``OPTIONS`` responses.15651566 .. versionadded:: 0.71567 """1568 adapter = _request_ctx_stack.top.url_adapter
14 unmodified lines
15831584 def should_ignore_error(self, error):1585 """This is called to figure out if an error should be ignored1586 or not as far as the teardown system is concerned. If this1587 function returns `True` then the teardown handlers will not be1587 function returns ``True`` then the teardown handlers will not be1588 passed the error.15891590 .. versionadded:: 0.101591 """
219 unmodified lines
18111812 def request_context(self, environ):1813 """Creates a :class:`~flask.ctx.RequestContext` from the given1814 environment and binds it to the current context. This must be used in1815 combination with the `with` statement because the request is only bound1816 to the current context for the duration of the `with` block.1815 combination with the ``with`` statement because the request is only bound1816 to the current context for the duration of the ``with`` block.18171818 Example usage::18191820 with app.request_context(environ):1821 do_something_with(request)18221823 The object returned can also be used without the `with` statement1823 The object returned can also be used without the ``with`` statement1824 which is useful for working in the shell. The example above is1825 doing exactly the same as this code::18261827 ctx = app.request_context(environ)
3 unmodified lines
1831 finally:1832 ctx.pop()18331834 .. versionchanged:: 0.31835 Added support for non-with statement usage and `with` statement1835 Added support for non-with statement usage and ``with`` statement1836 is now passed the ctx object.18371838 :param environ: a WSGI environment1839 """
70 unmodified lines
modified:flask/blueprints.py+1 added-1 removed
40 unmodified lines
41 subdomain = self.options.get('subdomain')42 if subdomain is None:43 subdomain = self.blueprint.subdomain4445 #: The subdomain that the blueprint should be active for, `None`45 #: The subdomain that the blueprint should be active for, ``None``46 #: otherwise.47 self.subdomain = subdomain4849 url_prefix = self.options.get('url_prefix')
365 unmodified lines
modified:flask/cli.py+2 added-2 removed
265 unmodified lines
266 For information as of why this is useful see :ref:`custom-scripts`.267268 :param add_default_commands: if this is True then the default run and269 shell commands wil be added.270 :param add_app_option: adds the default ``--app`` option. This gets270 :param add_app_option: adds the default :option:`--app` option. This gets271 automatically disabled if a `create_app`272 callback is defined.273 :param add_debug_option: adds the default ``--debug`` option.273 :param add_debug_option: adds the default :option:`--debug` option.274 :param create_app: an optional callback that is passed the script info275 and returns the loaded app.276 """277
215 unmodified lines
modified:flask/config.py+4 added-4 removed
91 unmodified lines
9293 app.config.from_pyfile(os.environ['YOURAPPLICATION_SETTINGS'])9495 :param variable_name: name of the environment variable96 :param silent: set to `True` if you want silent failure for missing96 :param silent: set to ``True`` if you want silent failure for missing97 files.98 :return: bool. `True` if able to load config, `False` otherwise.98 :return: bool. ``True`` if able to load config, ``False`` otherwise.99 """100 rv = os.environ.get(variable_name)101 if not rv:102 if silent:
12 unmodified lines
115116 :param filename: the filename of the config. This can either be an117 absolute filename or a filename relative to the118 root path.119 :param silent: set to `True` if you want silent failure for missing119 :param silent: set to ``True`` if you want silent failure for missing120 files.121122 .. versionadded:: 0.7123 `silent` parameter.
48 unmodified lines
172173 :param filename: the filename of the JSON file. This can either be an174 absolute filename or a filename relative to the175 root path.176 :param silent: set to `True` if you want silent failure for missing176 :param silent: set to ``True`` if you want silent failure for missing177 files.178179 .. versionadded:: 1.0180 """
78 unmodified lines
modified:flask/ctx.py+2 added-2 removed
207 unmodified lines
208 The request context is automatically popped at the end of the request209 for you. In debug mode the request context is kept around if210 exceptions happen so that interactive debuggers have a chance to211 introspect the data. With 0.4 this can also be forced for requests212 that did not fail and outside of `DEBUG` mode. By setting213 ``'flask._preserve_context'`` to `True` on the WSGI environment the212 that did not fail and outside of ``DEBUG`` mode. By setting213 ``'flask._preserve_context'`` to ``True`` on the WSGI environment the214 context will not pop itself at the end of the request. This is used by215 the :meth:`~flask.Flask.test_client` for example to implement the216 deferred cleanup functionality.217
178 unmodified lines
modified:flask/helpers.py+21 added-21 removed
186 unmodified lines
187 """Generates a URL to the given endpoint with the method provided.188189 Variable arguments that are unknown to the target endpoint are appended190 to the generated URL as query arguments. If the value of a query argument191 is `None`, the whole pair is skipped. In case blueprints are active191 is ``None``, the whole pair is skipped. In case blueprints are active192 you can shortcut references to the same blueprint by prefixing the193 local endpoint with a dot (``.``).194195 This will reference the index function local to the current blueprint::
6 unmodified lines
202 errors through :attr:`Flask.url_build_error_handlers`. The `url_for`203 function results in a :exc:`~werkzeug.routing.BuildError` when the current204 app does not have a URL for the given endpoint and values. When it does, the205 :data:`~flask.current_app` calls its :attr:`~Flask.url_build_error_handlers` if206 it is not `None`, which can return a string to use as the result of206 it is not ``None``, which can return a string to use as the result of207 `url_for` (instead of `url_for`'s default to raise the208 :exc:`~werkzeug.routing.BuildError` exception) or re-raise the exception.209 An example::210
32 unmodified lines
243 :exc:`~werkzeug.routing.BuildError`.244245 :param endpoint: the endpoint of the URL (name of the function)246 :param values: the variable arguments of the URL rule247 :param _external: if set to `True`, an absolute URL is generated. Server248 address can be changed via `SERVER_NAME` configuration variable which247 :param _external: if set to ``True``, an absolute URL is generated. Server248 address can be changed via ``SERVER_NAME`` configuration variable which249 defaults to `localhost`.250 :param _scheme: a string specifying the desired URL scheme. The `_external`251 parameter must be set to `True` or a `ValueError` is raised. The default251 parameter must be set to ``True`` or a :exc:`ValueError` is raised. The default252 behavior uses the same scheme as the current request, or253 ``PREFERRED_URL_SCHEME`` from the :ref:`app configuration <config>` if no254 request context is available. As of Werkzeug 0.10, this also can be set255 to an empty string to build protocol-relative URLs.
66 unmodified lines
322323def get_template_attribute(template_name, attribute):324 """Loads a macro (or variable) a template exports. This can be used to325 invoke a macro from within Python code. If you for example have a326 template named `_cider.html` with the following contents:326 template named :file:`_cider.html` with the following contents:327328 .. sourcecode:: html+jinja329330 {% macro hello(name) %}Hello {{ name }}!{% endmacro %}
44 unmodified lines
375def get_flashed_messages(with_categories=False, category_filter=[]):376 """Pulls all flashed messages from the session and returns them.377 Further calls in the same request to the function will return378 the same messages. By default just the messages are returned,379 but when `with_categories` is set to `True`, the return value will379 but when `with_categories` is set to ``True``, the return value will380 be a list of tuples in the form ``(category, message)`` instead.381382 Filter the flashed messages to one or more categories by providing those383 categories in `category_filter`. This allows rendering categories in384 separate html blocks. The `with_categories` and `category_filter`385 arguments are distinct:386387 * `with_categories` controls whether categories are returned with message388 text (`True` gives a tuple, where `False` gives just the message text).388 text (``True`` gives a tuple, where ``False`` gives just the message text).389 * `category_filter` filters the messages down to only those matching the390 provided categories.391392 See :ref:`message-flashing-pattern` for examples.
3 unmodified lines
396397 .. versionchanged:: 0.9398 `category_filter` parameter added.399400 :param with_categories: set to `True` to also receive categories.400 :param with_categories: set to ``True`` to also receive categories.401 :param category_filter: whitelist of categories to limit return values402 """403 flashes = _request_ctx_stack.top.flashes404 if flashes is None:
12 unmodified lines
417 """Sends the contents of a file to the client. This will use the418 most efficient method available and configured. By default it will419 try to use the WSGI server's file_wrapper support. Alternatively420 you can set the application's :attr:`~Flask.use_x_sendfile` attribute421 to ``True`` to directly emit an `X-Sendfile` header. This however422 requires support of the underlying webserver for `X-Sendfile`.421 to ``True`` to directly emit an ``X-Sendfile`` header. This however422 requires support of the underlying webserver for ``X-Sendfile``.423424 By default it will try to guess the mimetype for you, but you can425 also explicitly provide one. For extra security you probably want426 to send certain files as attachment (HTML for instance). The mimetype
25 unmodified lines
452 :param filename_or_fp: the filename of the file to send. This is453 relative to the :attr:`~Flask.root_path` if a454 relative path is specified.455 Alternatively a file object might be provided456 in which case `X-Sendfile` might not work and456 in which case ``X-Sendfile`` might not work and457 fall back to the traditional method. Make sure458 that the file pointer is positioned at the start459 of data to send before calling :func:`send_file`.460 :param mimetype: the mimetype of the file if provided, otherwise461 auto detection happens.462 :param as_attachment: set to `True` if you want to send this file with462 :param as_attachment: set to ``True`` if you want to send this file with463 a ``Content-Disposition: attachment`` header.464 :param attachment_filename: the filename for the attachment if it465 differs from the file's filename.466 :param add_etags: set to `False` to disable attaching of etags.467 :param conditional: set to `True` to enable conditional responses.466 :param add_etags: set to ``False`` to disable attaching of etags.467 :param conditional: set to ``True`` to enable conditional responses.468469 :param cache_timeout: the timeout in seconds for the headers. When `None`469 :param cache_timeout: the timeout in seconds for the headers. When ``None``470 (default), this value is set by471 :meth:`~Flask.get_send_file_max_age` of472 :data:`~flask.current_app`.473 """
130 unmodified lines
604 filename, as_attachment=True)605606 .. admonition:: Sending files and Performance607608 It is strongly recommended to activate either `X-Sendfile` support in608 It is strongly recommended to activate either ``X-Sendfile`` support in609 your webserver or (if no authentication happens) to tell the webserver610 to serve files for the given path on its own without calling into the611 web application for improved performance.612
170 unmodified lines
783 #: The name of the package or module. Do not change this once784 #: it was set by the constructor.785 self.import_name = import_name786787 #: location of the templates. `None` if templates should not be787 #: location of the templates. ``None`` if templates should not be788 #: exposed.789 self.template_folder = template_folder790791 if root_path is None:
25 unmodified lines
817 del _get_static_url_path, _set_static_url_path818819 @property820 def has_static_folder(self):821 """This is `True` if the package bound object's container has a821 """This is ``True`` if the package bound object's container has a822 folder named ``'static'``.823824 .. versionadded:: 0.5825 """
16 unmodified lines
842 the configuration of :data:`~flask.current_app`.843844 Static file functions such as :func:`send_from_directory` use this845 function, and :func:`send_file` calls this function on846 :data:`~flask.current_app` when the given cache_timeout is `None`. If a846 :data:`~flask.current_app` when the given cache_timeout is ``None``. If a847 cache_timeout is given in :func:`send_file`, that timeout is used;848 otherwise, this method is called.849850 This allows subclasses to change the behavior when sending files based
35 unmodified lines
886 /templates887 /layout.html888 /index.html889890 If you want to open the `schema.sql` file you would do the890 If you want to open the :file:`schema.sql` file you would do the891 following::892893 with app.open_resource('schema.sql') as f:894 contents = f.read()
9 unmodified lines
modified:flask/json.py+2 added-2 removed
58 unmodified lines
5960 def default(self, o):61 """Implement this method in a subclass such that it returns a62 serializable object for ``o``, or calls the base implementation (to63 raise a ``TypeError``).63 raise a :exc:`TypeError`).6465 For example, to support arbitrary iterators, you could implement66 default like this::67
131 unmodified lines
199200201def jsonify(*args, **kwargs):202 """Creates a :class:`~flask.Response` with the JSON representation of203 the given arguments with an `application/json` mimetype. The arguments203 the given arguments with an :mimetype:`application/json` mimetype. The arguments204 to this function are the same as to the :class:`dict` constructor.205206 Example usage::207
43 unmodified lines
modified:flask/sessions.py+9 added-9 removed
40 unmodified lines
41 del _get_permanent, _set_permanent4243 #: some session backends can tell you if a session is new, but that is44 #: not necessarily guaranteed. Use with caution. The default mixin45 #: implementation just hardcodes `False` in.45 #: implementation just hardcodes ``False`` in.46 new = False4748 #: for some backends this will always be `True`, but some backends will48 #: for some backends this will always be ``True``, but some backends will49 #: default this to false and detect changes in the dictionary for as50 #: long as changes do not happen on mutable structures in the session.51 #: The default mixin implementation just hardcodes `True` in.51 #: The default mixin implementation just hardcodes ``True`` in.52 modified = True535455def _tag(value):
92 unmodified lines
148149 class Session(dict, SessionMixin):150 pass151152 If :meth:`open_session` returns `None` Flask will call into152 If :meth:`open_session` returns ``None`` Flask will call into153 :meth:`make_null_session` to create a session that acts as replacement154 if the session support cannot work because some requirement is not155 fulfilled. The default :class:`NullSession` class that is created156 will complain that the secret key was not set.
70 unmodified lines
227 def get_cookie_path(self, app):228 """Returns the path for which the cookie should be valid. The229 default implementation uses the value from the ``SESSION_COOKIE_PATH``230 config var if it's set, and falls back to ``APPLICATION_ROOT`` or231 uses ``/`` if it's `None`.231 uses ``/`` if it's ``None``.232 """233 return app.config['SESSION_COOKIE_PATH'] or \234 app.config['APPLICATION_ROOT'] or '/'235
11 unmodified lines
247 return app.config['SESSION_COOKIE_SECURE']248249 def get_expiration_time(self, app, session):250 """A helper method that returns an expiration date for the session251 or `None` if the session is linked to the browser session. The251 or ``None`` if the session is linked to the browser session. The252 default implementation returns now + the permanent session253 lifetime configured on the application.254 """255 if session.permanent:
3 unmodified lines
259 """Indicates whether a cookie should be set now or not. This is260 used by session backends to figure out if they should emit a261 set-cookie header or not. The default behavior is controlled by262 the ``SESSION_REFRESH_EACH_REQUEST`` config variable. If263 it's set to `False` then a cookie is only set if the session is264 modified, if set to `True` it's always set if the session is263 it's set to ``False`` then a cookie is only set if the session is264 modified, if set to ``True`` it's always set if the session is265 permanent.266267 This check is usually skipped if sessions get deleted.268
4 unmodified lines
273 save_each = app.config['SESSION_REFRESH_EACH_REQUEST']274 return save_each and session.permanent275276 def open_session(self, app, request):277 """This method has to be implemented and must either return `None`277 """This method has to be implemented and must either return ``None``278 in case the loading failed because of a configuration error or an279 instance of a session object which implements a dictionary like280 interface + the methods and attributes on :class:`SessionMixin`.281 """
84 unmodified lines
modified:flask/wrappers.py+11 added-11 removed
45 unmodified lines
46 #: .. versionadded:: 0.647 url_rule = None4849 #: A dict of view arguments that matched the request. If an exception50 #: happened when matching, this will be `None`.50 #: happened when matching, this will be ``None``.51 view_args = None5253 #: If matching the URL failed, this is the exception that will be54 #: raised / was raised as part of the request handling. This is
6 unmodified lines
61 _is_old_module = False6263 @property64 def max_content_length(self):65 """Read-only view of the `MAX_CONTENT_LENGTH` config key."""65 """Read-only view of the ``MAX_CONTENT_LENGTH`` config key."""66 ctx = _request_ctx_stack.top67 if ctx is not None:68 return ctx.app.config['MAX_CONTENT_LENGTH']69
1 unmodified line
71 def endpoint(self):72 """The endpoint that matched the request. This in combination with73 :attr:`view_args` can be used to reconstruct the same or a74 modified URL. If an exception happened when matching, this will75 be `None`.75 be ``None``.76 """77 if self.url_rule is not None:78 return self.url_rule.endpoint79
17 unmodified lines
97 return self.url_rule.endpoint.rsplit('.', 1)[0]9899 @property100 def json(self):101 """If the mimetype is `application/json` this will contain the102 parsed JSON data. Otherwise this will be `None`.101 """If the mimetype is :mimetype:`application/json` this will contain the102 parsed JSON data. Otherwise this will be ``None``.103104 The :meth:`get_json` method should be used instead.105 """106 from warnings import warn
4 unmodified lines
111 @property112 def is_json(self):113 """Indicates if this request is JSON or not. By default a request114 is considered to include JSON data if the mimetype is115 ``application/json`` or ``application/*+json``.115 :mimetype:`application/json` or :mimetype:`application/*+json`.116117 .. versionadded:: 0.11118 """119 mt = self.mimetype
6 unmodified lines
126 def get_json(self, force=False, silent=False, cache=True):127 """Parses the incoming JSON request data and returns it. If128 parsing fails the :meth:`on_json_loading_failed` method on the129 request object will be invoked. By default this function will130 only load the json data if the mimetype is ``application/json``130 only load the json data if the mimetype is :mimetype:`application/json`131 but this can be overridden by the `force` parameter.132133 :param force: if set to `True` the mimetype is ignored.134 :param silent: if set to `True` this method will fail silently135 and return `None`.136 :param cache: if set to `True` the parsed JSON data is remembered133 :param force: if set to ``True`` the mimetype is ignored.134 :param silent: if set to ``True`` this method will fail silently135 and return ``None``.136 :param cache: if set to ``True`` the parsed JSON data is remembered137 on the request.138 """139 rv = getattr(self, '_cached_json', _missing)140 if rv is not _missing:
61 unmodified lines
modified:CHANGES+15 added-15 removed
10 unmodified lines
11- Added `**kwargs` to :meth:`flask.Test.test_client` to support passing12 additional keyword arguments to the constructor of13 :attr:`flask.Flask.test_client_class`.14- Added ``SESSION_REFRESH_EACH_REQUEST`` config key that controls the15 set-cookie behavior. If set to `True` a permanent session will be15 set-cookie behavior. If set to ``True`` a permanent session will be16 refreshed each request and get their lifetime extended, if set to17 `False` it will only be modified if the session actually modifies.17 ``False`` it will only be modified if the session actually modifies.18 Non permanent sessions are not affected by this and will always19 expire if the browser window closes.20- Made Flask support custom JSON mimetypes for incoming data.21- Added support for returning tuples in the form ``(response, headers)``
5 unmodified lines
27 can be configured with the new ``TEMPLATES_AUTO_RELOAD`` config key.28- Added a workaround for a limitation in Python 3.3's namespace loader.29- Added support for explicit root paths when using Python 3.3's namespace30 packages.31- Added ``flask`` and the ``flask.cli`` module to start the local31- Added :command:`flask` and the ``flask.cli`` module to start the local32 debug server through the click CLI system. This is recommended over the old33 ``flask.run()`` method as it works faster and more reliable due to a34 different design and also replaces ``Flask-Script``.35- Error handlers that match specific classes are now checked first,
146 unmodified lines
182- Logger now only returns the debug log setting if it was not set183 explicitly.184- Unregister a circular dependency between the WSGI environment and185 the request object when shutting down the request. This means that186 environ ``werkzeug.request`` will be `None` after the response was186 environ ``werkzeug.request`` will be ``None`` after the response was187 returned to the WSGI server but has the advantage that the garbage188 collector is not needed on CPython to tear down the request unless189 the user created circular dependencies themselves.190- Session is now stored after callbacks so that if the session payload
12 unmodified lines
203 :meth:`flask.Blueprint.add_app_template_filter`.204- The :func:`flask.get_flashed_messages` function now allows rendering flashed205 message categories in separate blocks, through a ``category_filter``206 argument.207- The :meth:`flask.Flask.run` method now accepts `None` for `host` and `port`208 arguments, using default values when `None`. This allows for calling run207- The :meth:`flask.Flask.run` method now accepts ``None`` for `host` and `port`208 arguments, using default values when ``None``. This allows for calling run209 using configuration values, e.g. ``app.run(app.config.get('MYHOST'),210 app.config.get('MYPORT'))``, with proper behavior whether or not a config211 file is provided.212- The :meth:`flask.render_template` method now accepts a either an iterable of
112 unmodified lines
325Released on June 28th 2011, codename Grappa326327- Added :meth:`~flask.Flask.make_default_options_response`328 which can be used by subclasses to alter the default329 behavior for `OPTIONS` responses.329 behavior for ``OPTIONS`` responses.330- Unbound locals now raise a proper :exc:`RuntimeError` instead331 of an :exc:`AttributeError`.332- Mimetype guessing and etag support based on file objects is now333 deprecated for :func:`flask.send_file` because it was unreliable.
4 unmodified lines
338 was not reliable and caused issues on Google's App Engine. Until339 1.0 the old behavior will continue to work but issue dependency340 warnings.341- fixed a problem for Flask to run on jython.342- added a `PROPAGATE_EXCEPTIONS` configuration variable that can be342- added a ``PROPAGATE_EXCEPTIONS`` configuration variable that can be343 used to flip the setting of exception propagation which previously344 was linked to `DEBUG` alone and is now linked to either `DEBUG` or345 `TESTING`.344 was linked to ``DEBUG`` alone and is now linked to either ``DEBUG`` or345 ``TESTING``.346- Flask no longer internally depends on rules being added through the347 `add_url_rule` function and can now also accept regular werkzeug348 rules added to the url map.349- Added an `endpoint` method to the flask application object which
28 unmodified lines
378-------------379380Bugfix release, released on December 31st 2010381382- Fixed an issue where the default `OPTIONS` response was383 not exposing all valid methods in the `Allow` header.382- Fixed an issue where the default ``OPTIONS`` response was383 not exposing all valid methods in the ``Allow`` header.384- Jinja2 template loading syntax now allows "./" in front of385 a template load path. Previously this caused issues with386 module setups.387- Fixed an issue where the subdomain setting for modules was
61 unmodified lines
449Released on July 6th 2010, codename Calvados450451- fixed a bug with subdomains that was caused by the inability to452 specify the server name. The server name can now be set with453 the `SERVER_NAME` config key. This key is now also used to set453 the ``SERVER_NAME`` config key. This key is now also used to set454 the session cookie cross-subdomain wide.455- autoescaping is no longer active for all templates. Instead it456 is only active for ``.html``, ``.htm``, ``.xml`` and ``.xhtml``.457 Inside templates this behavior can be changed with the
23 unmodified lines
481 for a little longer. This can also be used to trigger custom482 requests that do not pop the request stack for testing.483- because the Python standard library caches loggers, the name of484 the logger is configurable now to better support unittests.485- added `TESTING` switch that can activate unittesting helpers.486- the logger switches to `DEBUG` mode now if debug is enabled.485- added ``TESTING`` switch that can activate unittesting helpers.486- the logger switches to ``DEBUG`` mode now if debug is enabled.487488Version 0.3.1489-------------490
48 unmodified lines