Skip to content
Myr

Merge branch 'master' of github.com:mitsuhiko/flask

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

authored by Armin Ronacher · committed by Armin Ronacher · parents ab110d8, f071990 · Browse files · 33 files+677 added−310 removed
This commit

State

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

Diff stats

33 files+677 added−310 removed

  • other:+677 added−310 removed

33 files+677 added−310 removed

modified:docs/deploying/fastcgi.rst+5 added-6 removed
1 unmodified line
23FastCGI4=======56FastCGI is a deployment option on servers like `nginx`_, `lighttpd`_,7and `cherokee`_; see :ref:`deploying-uwsgi` and8:ref:`deploying-other-servers` for other options. To use your WSGI9application with any of them you will need a FastCGI server first. The10most popular one is `flup`_ which we will use for this guide. Make sure11to have it installed to follow along.6FastCGI is a deployment option on servers like `nginx`_, `lighttpd`_, and7`cherokee`_; see :ref:`deploying-uwsgi` and :ref:`deploying-wsgi-standalone`8for other options. To use your WSGI application with any of them you will need9a FastCGI server first. The most popular one is `flup`_ which we will use for10this guide. Make sure to have it installed to follow along.1112.. admonition:: Watch Out1314 Please make sure in advance that any ``app.run()`` calls you might
149 unmodified lines
modified:docs/deploying/index.rst+6 added-3 removed
11 unmodified lines
12If you have a different WSGI server look up the server documentation13about how to use a WSGI app with it. Just remember that your14:class:`Flask` application object is the actual WSGI application.1516For hosted options to get up and running quickly, see17:ref:`quickstart_deployment` in the Quickstart.1819.. toctree::20 :maxdepth: 22122 mod_wsgi20 cgi21 fastcgi23 wsgi-standalone24 uwsgi23 others25 fastcgi26 cgi
deleted:docs/deploying/others.rst-102 removed
1.. _deploying-other-servers:23Other Servers4=============56There are popular servers written in Python that allow the execution of WSGI7applications as well. These servers stand alone when they run; you can proxy8to them from your web server.910Tornado11--------1213`Tornado`_ is an open source version of the scalable, non-blocking web14server and tools that power `FriendFeed`_. Because it is non-blocking and15uses epoll, it can handle thousands of simultaneous standing connections,16which means it is ideal for real-time web services. Integrating this17service with Flask is a trivial task::1819 from tornado.wsgi import WSGIContainer20 from tornado.httpserver import HTTPServer21 from tornado.ioloop import IOLoop22 from yourapplication import app2324 http_server = HTTPServer(WSGIContainer(app))25 http_server.listen(5000)26 IOLoop.instance().start()272829.. _Tornado: http://www.tornadoweb.org/30.. _FriendFeed: http://friendfeed.com/3132Gevent33-------3435`Gevent`_ is a coroutine-based Python networking library that uses36`greenlet`_ to provide a high-level synchronous API on top of `libevent`_37event loop::3839 from gevent.wsgi import WSGIServer40 from yourapplication import app4142 http_server = WSGIServer(('', 5000), app)43 http_server.serve_forever()4445.. _Gevent: http://www.gevent.org/46.. _greenlet: http://codespeak.net/py/0.9.2/greenlet.html47.. _libevent: http://monkey.org/~provos/libevent/4849Gunicorn50--------5152`Gunicorn`_ 'Green Unicorn' is a WSGI HTTP Server for UNIX. It's a pre-fork53worker model ported from Ruby's Unicorn project. It supports both `eventlet`_54and `greenlet`_. Running a Flask application on this server is quite simple::5556 gunicorn myproject:app5758`Gunicorn`_ provides many command-line options -- see ``gunicorn -h``.59For example, to run a Flask application with 4 worker processes (``-w604``) binding to localhost port 4000 (``-b 127.0.0.1:4000``)::6162 gunicorn -w 4 -b 127.0.0.1:4000 myproject:app6364.. _Gunicorn: http://gunicorn.org/65.. _eventlet: http://eventlet.net/66.. _greenlet: http://codespeak.net/py/0.9.2/greenlet.html6768Proxy Setups69------------7071If you deploy your application using one of these servers behind an HTTP72proxy you will need to rewrite a few headers in order for the73application to work. The two problematic values in the WSGI environment74usually are `REMOTE_ADDR` and `HTTP_HOST`. Werkzeug ships a fixer that75will solve some common setups, but you might want to write your own WSGI76middleware for specific setups.7778The most common setup invokes the host being set from `X-Forwarded-Host`79and the remote address from `X-Forwarded-For`::8081 from werkzeug.contrib.fixers import ProxyFix82 app.wsgi_app = ProxyFix(app.wsgi_app)8384Please keep in mind that it is a security issue to use such a middleware85in a non-proxy setup because it will blindly trust the incoming86headers which might be forged by malicious clients.8788If you want to rewrite the headers from another header, you might want to89use a fixer like this::9091 class CustomProxyFix(object):9293 def __init__(self, app):94 self.app = app9596 def __call__(self, environ, start_response):97 host = environ.get('HTTP_X_FHOST', '')98 if host:99 environ['HTTP_HOST'] = host100 return self.app(environ, start_response)101102 app.wsgi_app = CustomProxyFix(app.wsgi_app)
modified:docs/deploying/uwsgi.rst+4 added-5 removed
2 unmodified lines
3uWSGI4=====56uWSGI is a deployment option on servers like `nginx`_, `lighttpd`_, and7`cherokee`_; see :ref:`deploying-fastcgi` and8:ref:`deploying-other-servers` for other options. To use your WSGI9application with uWSGI protocol you will need a uWSGI server10first. uWSGI is both a protocol and an application server; the11application server can serve uWSGI, FastCGI, and HTTP protocols.7`cherokee`_; see :ref:`deploying-fastcgi` and :ref:`deploying-wsgi-standalone`8for other options. To use your WSGI application with uWSGI protocol you will9need a uWSGI server first. uWSGI is both a protocol and an application server;10the application server can serve uWSGI, FastCGI, and HTTP protocols.1112The most popular uWSGI server is `uwsgi`_, which we will use for this13guide. Make sure to have it installed to follow along.14
53 unmodified lines
added:docs/deploying/wsgi-standalone.rst+132 added
1.. _deploying-wsgi-standalone:23Standalone WSGI Containers4==========================56There are popular servers written in Python that contain WSGI applications and7serve HTTP. These servers stand alone when they run; you can proxy to them8from your web server. Note the section on :ref:`deploying-proxy-setups` if you9run into issues.1011Gunicorn12--------1314`Gunicorn`_ 'Green Unicorn' is a WSGI HTTP Server for UNIX. It's a pre-fork15worker model ported from Ruby's Unicorn project. It supports both `eventlet`_16and `greenlet`_. Running a Flask application on this server is quite simple::1718 gunicorn myproject:app1920`Gunicorn`_ provides many command-line options -- see ``gunicorn -h``.21For example, to run a Flask application with 4 worker processes (``-w224``) binding to localhost port 4000 (``-b 127.0.0.1:4000``)::2324 gunicorn -w 4 -b 127.0.0.1:4000 myproject:app2526.. _Gunicorn: http://gunicorn.org/27.. _eventlet: http://eventlet.net/28.. _greenlet: http://codespeak.net/py/0.9.2/greenlet.html2930Tornado31--------3233`Tornado`_ is an open source version of the scalable, non-blocking web34server and tools that power `FriendFeed`_. Because it is non-blocking and35uses epoll, it can handle thousands of simultaneous standing connections,36which means it is ideal for real-time web services. Integrating this37service with Flask is straightforward::3839 from tornado.wsgi import WSGIContainer40 from tornado.httpserver import HTTPServer41 from tornado.ioloop import IOLoop42 from yourapplication import app4344 http_server = HTTPServer(WSGIContainer(app))45 http_server.listen(5000)46 IOLoop.instance().start()474849.. _Tornado: http://www.tornadoweb.org/50.. _FriendFeed: http://friendfeed.com/5152Gevent53-------5455`Gevent`_ is a coroutine-based Python networking library that uses56`greenlet`_ to provide a high-level synchronous API on top of `libevent`_57event loop::5859 from gevent.wsgi import WSGIServer60 from yourapplication import app6162 http_server = WSGIServer(('', 5000), app)63 http_server.serve_forever()6465.. _Gevent: http://www.gevent.org/66.. _greenlet: http://codespeak.net/py/0.9.2/greenlet.html67.. _libevent: http://monkey.org/~provos/libevent/6869.. _deploying-proxy-setups:7071Proxy Setups72------------7374If you deploy your application using one of these servers behind an HTTP proxy75you will need to rewrite a few headers in order for the application to work.76The two problematic values in the WSGI environment usually are `REMOTE_ADDR`77and `HTTP_HOST`. You can configure your httpd to pass these headers, or you78can fix them in middleware. Werkzeug ships a fixer that will solve some common79setups, but you might want to write your own WSGI middleware for specific80setups.8182Here's a simple nginx configuration which proxies to an application served on83localhost at port 8000, setting appropriate headers:8485.. sourcecode:: nginx8687 server {88 listen 80;8990 server_name _;9192 access_log /var/log/nginx/access.log;93 error_log /var/log/nginx/error.log;9495 location / {96 proxy_pass http://127.0.0.1:8000/;97 proxy_redirect off;9899 proxy_set_header Host $host;100 proxy_set_header X-Real-IP $remote_addr;101 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;102 }103 }104105If your httpd is not providing these headers, the most common setup invokes the106host being set from `X-Forwarded-Host` and the remote address from107`X-Forwarded-For`::108109 from werkzeug.contrib.fixers import ProxyFix110 app.wsgi_app = ProxyFix(app.wsgi_app)111112.. admonition:: Trusting Headers113114 Please keep in mind that it is a security issue to use such a middleware in115 a non-proxy setup because it will blindly trust the incoming headers which116 might be forged by malicious clients.117118If you want to rewrite the headers from another header, you might want to119use a fixer like this::120121 class CustomProxyFix(object):122123 def __init__(self, app):124 self.app = app125126 def __call__(self, environ, start_response):127 host = environ.get('HTTP_X_FHOST', '')128 if host:129 environ['HTTP_HOST'] = host130 return self.app(environ, start_response)131132 app.wsgi_app = CustomProxyFix(app.wsgi_app)
modified:docs/patterns/appdispatch.rst+18 added
28 unmodified lines
2930Note that :func:`run_simple <werkzeug.serving.run_simple>` is not intended for31use in production. Use a :ref:`full-blown WSGI server <deployment>`.3233In order to use the interactive debuggger, debugging must be enabled both on34the application and the simple server, here is the "hello world" example with35debugging and :func:`run_simple <werkzeug.serving.run_simple>`::3637 from flask import Flask38 from werkzeug.serving import run_simple3940 app = Flask(__name__)41 app.debug = True4243 @app.route('/')44 def hello_world():45 return 'Hello World!'4647 if __name__ == '__main__':48 run_simple('localhost', 5000, app,49 use_reloader=True, use_debugger=True, use_evalex=True)505152Combining Applications53----------------------5455If you have entirely separated applications and you want them to work next
133 unmodified lines
modified:docs/patterns/mongokit.rst+1 added-1 removed
139 unmodified lines
140>>> r['email']141u'admin@localhost'142143For more information about MongoKit, head over to the144`website <http://bytebucket.org/namlook/mongokit/>`_.144`website <https://github.com/namlook/mongokit>`_.
modified:docs/patterns/packages.rst+1 added-1 removed
53 unmodified lines
541. the `Flask` application object creation has to be in the55 `__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 when in the `__init__.py` file.58 decorator on top) have to be imported in the `__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`::
53 unmodified lines
modified:docs/tutorial/setup.rst+10 added-10 removed
9 unmodified lines
10into the module which we will be doing here. However a cleaner solution11would be to create a separate `.ini` or `.py` file and load that or import12the values from there.1314::14In `flaskr.py`::1516 # all the imports17 import sqlite318 from flask import Flask, request, session, g, redirect, url_for, \
6 unmodified lines
25 USERNAME = 'admin'26 PASSWORD = 'default'2728Next we can create our actual application and initialize it with the29config from the same file::29config from the same file, in `flaskr.py`::3031 # create our little application :)32 app = Flask(__name__)33 app.config.from_object(__name__)
2 unmodified lines
36string it will import it) and then look for all uppercase variables37defined there. In our case, the configuration we just wrote a few lines38of code above. You can also move that into a separate file.3940It is also a good idea to be able to load a configuration from a41configurable file. This is what :meth:`~flask.Config.from_envvar` can42do::40Usually, it is a good idea to load a configuration from a configurable41file. This is what :meth:`~flask.Config.from_envvar` can do, replacing the42:meth:`~flask.Config.from_object` line above::4344 app.config.from_envvar('FLASKR_SETTINGS', silent=True)4546That way someone can set an environment variable called47:envvar:`FLASKR_SETTINGS` to specify a config file to be loaded which will48then override the default values. The silent switch just tells Flask to49not complain if no such environment key is set.47:envvar:`FLASKR_SETTINGS` to specify a config file to be loaded which will then48override the default values. The silent switch just tells Flask to not complain49if no such environment key is set.5051The `secret_key` is needed to keep the client-side sessions secure.52Choose that key wisely and as hard to guess and complex as possible. The53debug flag enables or disables the interactive debugger. Never leave54debug mode activated in a production system because it will allow users to53debug flag enables or disables the interactive debugger. *Never leave54debug mode activated in a production system*, because it will allow users to55execute code on the server!5657We also add a method to easily connect to the database specified. That58can be used to open a connection on request and also from the interactive
32 unmodified lines
added:docs/advanced_foreword.rst+67 added
1Foreword for Experienced Programmers2====================================34This chapter is for programmers who have worked with other frameworks in the5past, and who may have more specific or esoteric concerns that the typical6user.78Threads in Flask9----------------1011One of the design decisions with Flask was that simple tasks should be simple;12they should not take a lot of code and yet they should not limit you. Because13of that we made a few design choices that some people might find surprising or14unorthodox. For example, Flask uses thread-local objects internally so that15you don’t have to pass objects around from function to function within a16request in order to stay threadsafe. While this is a really easy approach and17saves you a lot of time, it might also cause some troubles for very large18applications because changes on these thread-local objects can happen anywhere19in the same thread. In order to solve these problems we don’t hide the thread20locals for you but instead embrace them and provide you with a lot of tools to21make it as pleasant as possible to work with them.2223Web Development is Dangerous24----------------------------2526If you write a web application, you are probably allowing users to register27and leave their data on your server. The users are entrusting you with data.28And even if you are the only user that might leave data in your application,29you still want that data to be stored securely.3031Unfortunately, there are many ways the security of a web application can be32compromised. Flask protects you against one of the most common security33problems of modern web applications: cross-site scripting (XSS). Unless34you deliberately mark insecure HTML as secure, Flask and the underlying35Jinja2 template engine have you covered. But there are many more ways to36cause security problems.3738The documentation will warn you about aspects of web development that39require attention to security. Some of these security concerns40are far more complex than one might think, and we all sometimes underestimate41the likelihood that a vulnerability will be exploited - until a clever42attacker figures out a way to exploit our applications. And don't think43that your application is not important enough to attract an attacker.44Depending on the kind of attack, chances are that automated bots are45probing for ways to fill your database with spam, links to malicious46software, and the like.4748So always keep security in mind when doing web development.4950The Status of Python 351----------------------5253Currently the Python community is in the process of improving libraries to54support the new iteration of the Python programming language. While the55situation is greatly improving there are still some issues that make it56hard for us to switch over to Python 3 just now. These problems are57partially caused by changes in the language that went unreviewed for too58long, partially also because we have not quite worked out how the lower-59level API should change to account for the Unicode differences in Python 3.6061Werkzeug and Flask will be ported to Python 3 as soon as a solution for62the changes is found, and we will provide helpful tips how to upgrade63existing applications to Python 3. Until then, we strongly recommend64using Python 2.6 and 2.7 with activated Python 3 warnings during65development. If you plan on upgrading to Python 3 in the near future we66strongly recommend that you read `How to write forwards compatible67Python code <http://lucumr.pocoo.org/2011/1/22/forwards-compatible-python/>`_.
modified:docs/api.rst+1 added-1 removed
523 unmodified lines
524525The following converters are available:526527=========== ===============================================528`unicode` accepts any text without a slash (the default)528`string` accepts any text without a slash (the default)529`int` accepts integers530`float` like `int` but for floating point values531`path` like the default but also accepts slashes532=========== ===============================================
110 unmodified lines
modified:docs/conf.py+1 added-1 removed
41 unmodified lines
42master_doc = 'index'4344# General information about the project.45project = u'Flask'46copyright = u'2010, Armin Ronacher'46copyright = u'2012, Armin Ronacher'4748# The version info for the project you're documenting, acts as replacement for49# |version| and |release|, also used in various other places throughout the50# built documents.
219 unmodified lines
modified:docs/config.rst+8 added-1 removed
108 unmodified lines
109``MAX_CONTENT_LENGTH`` If set to a value in bytes, Flask will110 reject incoming requests with a111 content length greater than this by112 returning a 413 status code.113``SEND_FILE_MAX_AGE_DEFAULT``: Default cache control max age to use with114 :meth:`flask.Flask.send_static_file`, in115 seconds. Override this value on a per-file116 basis using the117 :meth:`flask.Flask.get_send_file_options` and118 :meth:`flask.Blueprint.get_send_file_options`119 hooks. Defaults to 43200 (12 hours).120``TRAP_HTTP_EXCEPTIONS`` If this is set to ``True`` Flask will121 not execute the error handlers of HTTP122 exceptions but instead treat the123 exception like any other and bubble it
158 unmodified lines
282 DATABASE_URI = 'sqlite://:memory:'283284 class ProductionConfig(Config):285 DATABASE_URI = 'mysql://user@localhost/foo'279 286287 class DevelopmentConfig(Config):288 DEBUG = True289290 class TestingConfig(Config):
110 unmodified lines
modified:docs/extensiondev.rst+56 added-73 removed
123 unmodified lines
124Initializing Extensions125-----------------------126127Many extensions will need some kind of initialization step. For example,128consider your application is currently connecting to SQLite like the129documentation suggests (:ref:`sqlite3`) you will need to provide a few130functions and before / after request handlers. So how does the extension128consider an application that's currently connecting to SQLite like the129documentation suggests (:ref:`sqlite3`). So how does the extension130know the name of the application object?131132Quite simple: you pass it to it.133134There are two recommended ways for an extension to initialize:135136initialization functions:137138 If your extension is called `helloworld` you might have a function139 called ``init_helloworld(app[, extra_args])`` that initializes the140 extension for that application. It could attach before / after141 handlers etc.142143classes:144145 Classes work mostly like initialization functions but can later be146 used to further change the behaviour. For an example look at how the147 `OAuth extension`_ works: there is an `OAuth` object that provides148 some helper functions like `OAuth.remote_app` to create a reference to149 a remote application that uses OAuth.150151What to use depends on what you have in mind. For the SQLite 3 extension151we will use the class-based approach because it will provide users with a152manager object that handles opening and closing database connections.152we will use the class-based approach because it will provide users with an153object that handles opening and closing database connections.154155The Extension Code156------------------157158Here's the contents of the `flask_sqlite3.py` for copy/paste::159159 from __future__ import absolute_import160 import sqlite3161162 from flask import _request_ctx_stack163164165 class SQLite3(object):166166 def __init__(self, app):167 def __init__(self, app=None):168 if app is not None:169 self.app = app170 self.init_app(self.app)171 else:172 self.app = None173174 def init_app(self, app):175 self.app = app176 self.app.config.setdefault('SQLITE3_DATABASE', ':memory:')177 self.app.teardown_request(self.teardown_request)178 self.app.before_request(self.before_request)
8 unmodified lines
187 def teardown_request(self, exception):188 ctx = _request_ctx_stack.top189 ctx.sqlite3_db.close()190183 def get_db(self):191 @property192 def connection(self):193 ctx = _request_ctx_stack.top194 if ctx is not None:195 return ctx.sqlite3_db196197198So here's what these lines of code do:1991901. The ``__future__`` import is necessary to activate absolute imports.191 Otherwise we could not call our module `sqlite3.py` and import the192 top-level `sqlite3` module which actually implements the connection to193 SQLite.1942. We create a class for our extension that requires a supplied `app` object,195 sets a configuration for the database if it's not there196 (:meth:`dict.setdefault`), and attaches `before_request` and197 `teardown_request` handlers.1983. Next, we define a `connect` function that opens a database connection.2001. The ``__init__`` method takes an optional app object and, if supplied, will201 call ``init_app``.2022. The ``init_app`` method exists so that the ``SQLite3`` object can be203 instantiated without requiring an app object. This method supports the204 factory pattern for creating applications. The ``init_app`` will set the205 configuration for the database, defaulting to an in memory database if206 no configuration is supplied. In addition, the ``init_app`` method attaches207 ``before_request`` and ``teardown_request`` handlers.2083. Next, we define a ``connect`` method that opens a database connection.2094. Then we set up the request handlers we bound to the app above. Note here210 that we're attaching our database connection to the top request context via201 `_request_ctx_stack.top`. Extensions should use the top context and not the202 `g` object to store things like database connections.2035. Finally, we add a `get_db` function that simplifies access to the context's211 ``_request_ctx_stack.top``. Extensions should use the top context and not the212 ``g`` object to store things like database connections.2135. Finally, we add a ``connection`` property that simplifies access to the context's214 database.215216So why did we decide on a class-based approach here? Because using our217extension looks something like this::
2 unmodified lines
220 from flask_sqlite3 import SQLite3221222 app = Flask(__name__)223 app.config.from_pyfile('the-config.cfg')214 manager = SQLite3(app)215 db = manager.get_db()224 db = SQLite3(app)225226You can then use the database from views like this::227228 @app.route('/')229 def show_all():221 cur = db.cursor()230 cur = db.connection.cursor()231 cur.execute(...)232224Opening a database connection from outside a view function is simple.233Additionally, the ``init_app`` method is used to support the factory pattern234for creating apps::235226>>> from yourapplication import db227>>> cur = db.cursor()228>>> cur.execute(...)236 db = Sqlite3()237 # Then later on.238 app = create_app('the-config.cfg')239 db.init_app(app)240230Adding an `init_app` Function231-----------------------------241Keep in mind that supporting this factory pattern for creating apps is required242for approved flask extensions (described below).243233In practice, you'll almost always want to permit users to initialize your234extension and provide an app object after the fact. This can help avoid235circular import problems when a user is breaking their app into multiple files.236Our extension could add an `init_app` function as follows::244238 class SQLite3(object):245Using _request_ctx_stack246------------------------247240 def __init__(self, app=None):241 if app is not None:242 self.app = app243 self.init_app(self.app)244 else:245 self.app = None248In the example above, before every request, a ``sqlite3_db`` variable is assigned249to ``_request_ctx_stack.top``. In a view function, this variable is accessible250using the ``connection`` property of ``SQLite3``. During the teardown of a251request, the ``sqlite3_db`` connection is closed. By using this pattern, the252*same* connection to the sqlite3 database is accessible to anything that needs it253for the duration of the request.254247 def init_app(self, app):248 self.app = app249 self.app.config.setdefault('SQLITE3_DATABASE', ':memory:')250 self.app.teardown_request(self.teardown_request)251 self.app.before_request(self.before_request)252253 def connect(self):254 return sqlite3.connect(app.config['SQLITE3_DATABASE'])255256 def before_request(self):257 ctx = _request_ctx_stack.top258 ctx.sqlite3_db = self.connect()259260 def teardown_request(self, exception):261 ctx = _request_ctx_stack.top262 ctx.sqlite3_db.close()263264 def get_db(self):265 ctx = _request_ctx_stack.top266 if ctx is not None:267 return ctx.sqlite3_db268269The user could then initialize the extension in one file::270271 manager = SQLite3()272273and bind their app to the extension in another file::274275 manager.init_app(app)276255End-Of-Request Behavior256-----------------------257258Due to the change in Flask 0.7 regarding functions that are run at the end
10 unmodified lines
269 app.teardown_request(close_connection)270 else:271 app.after_request(close_connection)272273274Strictly speaking the above code is wrong, because teardown functions are275passed the exception and typically don't return anything. However because276the return value is discarded this will just work assuming that the code277in between does not touch the passed parameter.
26 unmodified lines
304new releases. These approved extensions are listed on the `Flask305Extension Registry`_ and marked appropriately. If you want your own306extension to be approved you have to follow these guidelines:3073080. An approved Flask extension requires a maintainer. In the event an309 extension author would like to move beyond the project, the project should310 find a new maintainer including full source hosting transition and PyPI311 access. If no maintainer is available, give access to the Flask core team.3121. An approved Flask extension must provide exactly one package or module313 named ``flask_extensionname``. They might also reside inside a314 ``flaskext`` namespace packages though this is discouraged now.3152. It must ship a testing suite that can either be invoked with ``make test``316 or ``python setup.py test``. For test suites invoked with ``make317 test`` the extension has to ensure that all dependencies for the test335 are installed automatically, in case of ``python setup.py test``336 dependencies for tests alone can be specified in the `setup.py`337 file. The test suite also has to be part of the distribution.318 are installed automatically. If tests are invoked with ``python setup.py319 test``, test dependencies can be specified in the `setup.py` file. The320 test suite also has to be part of the distribution.3213. APIs of approved extensions will be checked for the following322 characteristics:323324 - an approved extension has to support multiple applications
46 unmodified lines
modified:docs/foreword.rst+37 added-82 removed
6 unmodified lines
78What does "micro" mean?9-----------------------1011To me, the "micro" in microframework refers not only to the simplicity and12small size of the framework, but also the fact that it does not make many13decisions for you. While Flask does pick a templating engine for you, we14won't make such decisions for your datastore or other parts.11“Micro” does not mean that your whole web application has to fit into12a single Python file (although it certainly can). Nor does it mean13that Flask is lacking in functionality. The "micro" in microframework14means Flask aims to keep the core simple but extensible. Flask won't make 15many decisions for you, such as what database to use. Those decisions that 16it does make, such as what templating engine to use, are easy to change. 17Everything else is up to you, so that Flask can be everything you need 18and nothing you don't.1916However, to us the term “micro” does not mean that the whole implementation17has to fit into a single Python file.20By default, Flask does not include a database abstraction layer, form21validation or anything else where different libraries already exist that can22handle that. Instead, FLask extensions add such functionality to your23application as if it was implemented in Flask itself. Numerous extensions24provide database integration, form validation, upload handling, various open25authentication technologies, and more. Flask may be "micro", but the26possibilities are endless.2719One of the design decisions with Flask was that simple tasks should be20simple; they should not take a lot of code and yet they should not limit you.21Because of that we made a few design choices that some people might find22surprising or unorthodox. For example, Flask uses thread-local objects23internally so that you don't have to pass objects around from function to24function within a request in order to stay threadsafe. While this is a25really easy approach and saves you a lot of time, it might also cause some26troubles for very large applications because changes on these thread-local27objects can happen anywhere in the same thread. In order to solve these28problems we don't hide the thread locals for you but instead embrace them29and provide you with a lot of tools to make it as pleasant as possible to30work with them.28Convention over Configuration29-----------------------------3032Flask is also based on convention over configuration, which means that33many things are preconfigured. For example, by convention templates and34static files are stored in subdirectories within the application's Python source tree.35While this can be changed you usually don't have to.31Flask is based on convention over configuration, which means that many things32are preconfigured. For example, by convention templates and static files are33stored in subdirectories within the application's Python source tree. While34this can be changed you usually don't have to. We want to minimize the time35you need to spend in order to get up and running, without assuming things 36about your needs.3737The main reason Flask is called a "microframework" is the idea38to keep the core simple but extensible. There is no database abstraction39layer, no form validation or anything else where different libraries40already exist that can handle that. However Flask supports41extensions to add such functionality to your application as if it42was implemented in Flask itself. There are currently extensions for43object-relational mappers, form validation, upload handling, various open44authentication technologies and more.38Growing Up39----------4046Since Flask is based on a very solid foundation there is not a lot of code47in Flask itself. As such it's easy to adapt even for large applications48and we are making sure that you can either configure it as much as49possible by subclassing things or by forking the entire codebase. If you50are interested in that, check out the :ref:`becomingbig` chapter.41Since Flask is based on a very solid foundation there is not a lot of code in42Flask itself. As such it's easy to adapt even for large applications and we43are making sure that you can either configure it as much as possible by44subclassing things or by forking the entire codebase. If you are interested45in that, check out the :ref:`becomingbig` chapter.4652If you are curious about the Flask design principles, head over to the53section about :ref:`design`.47If you are curious about the Flask design principles, head over to the section48about :ref:`design`.4955Web Development is Dangerous56----------------------------50For the Stalwart and Wizened...51-------------------------------5258I'm not joking. Well, maybe a little. If you write a web59application, you are probably allowing users to register and leave their60data on your server. The users are entrusting you with data. And even if61you are the only user that might leave data in your application, you still62want that data to be stored securely.6364Unfortunately, there are many ways the security of a web application can be65compromised. Flask protects you against one of the most common security66problems of modern web applications: cross-site scripting (XSS). Unless67you deliberately mark insecure HTML as secure, Flask and the underlying68Jinja2 template engine have you covered. But there are many more ways to69cause security problems.7071The documentation will warn you about aspects of web development that72require attention to security. Some of these security concerns73are far more complex than one might think, and we all sometimes underestimate74the likelihood that a vulnerability will be exploited - until a clever75attacker figures out a way to exploit our applications. And don't think76that your application is not important enough to attract an attacker.77Depending on the kind of attack, chances are that automated bots are78probing for ways to fill your database with spam, links to malicious79software, and the like.8081So always keep security in mind when doing web development.8283The Status of Python 384----------------------8586Currently the Python community is in the process of improving libraries to87support the new iteration of the Python programming language. While the88situation is greatly improving there are still some issues that make it89hard for us to switch over to Python 3 just now. These problems are90partially caused by changes in the language that went unreviewed for too91long, partially also because we have not quite worked out how the lower-92level API should change to account for the Unicode differences in Python 3.9394Werkzeug and Flask will be ported to Python 3 as soon as a solution for95the changes is found, and we will provide helpful tips how to upgrade96existing applications to Python 3. Until then, we strongly recommend97using Python 2.6 and 2.7 with activated Python 3 warnings during98development. If you plan on upgrading to Python 3 in the near future we99strongly recommend that you read `How to write forwards compatible100Python code <http://lucumr.pocoo.org/2011/1/22/forwards-compatible-python/>`_.53If you're more curious about the minutiae of Flask's implementation, and54whether its structure is right for your needs, read the55:ref:`advanced_foreword`.
modified:docs/installation.rst+1 added-1 removed
92 unmodified lines
93System-Wide Installation94------------------------9596This is possible as well, though I do not recommend it. Just run97`easy_install` with root privileges::97`pip` with root privileges::9899 $ sudo pip install Flask100101(On Windows systems, run it in a command-prompt window with administrator
73 unmodified lines
modified:docs/quickstart.rst+28 added-6 removed
166 unmodified lines
167=========== ===========================================168169.. admonition:: Unique URLs / Redirection Behaviour170171 Flask's URL rules are based on Werkzeug's routing module. The idea behind172 that module is to ensure beautiful and unique also unique URLs based on171 Flask's URL rules are based on Werkzeug's routing module. The idea172 behind that module is to ensure beautiful and unique URLs based on173 precedents laid down by Apache and earlier HTTP servers.174175 Take these two rules::176
15 unmodified lines
192 rather like the pathname of a file on UNIX-like systems. Accessing the URL193 with a trailing slash will produce a 404 "Not Found" error.194195 This behavior allows relative URLs to continue working if users access the196 page when they forget a trailing slash, consistent with how with how Apache196 page when they forget a trailing slash, consistent with how Apache197 and other servers work. Also, the URLs will stay unique, which helps search198 engines avoid indexing the same page twice.199200
32 unmodified lines
233/user/John%20Doe234235(This also uses the :meth:`~flask.Flask.test_request_context` method, explained236below. It tells Flask to behave as though it is handling a request, even237though were are interacting with it through a Python shell. Have a look at the237though we are interacting with it through a Python shell. Have a look at the238explanation below. :ref:`context-locals`).239240Why would you want to build URLs instead of hard-coding them into your241templates? There are three good reasons for this:
90 unmodified lines
332configured to serve them for you, but during development Flask can do that333as well. Just create a folder called `static` in your package or next to334your module and it will be available at `/static` on the application.335336To generate URLs that part of the URL, use the special ``'static'`` URL337name::336To generate URLs for static files, use the special ``'static'`` endpoint name::337338 url_for('static', filename='style.css')339340The file has to be stored on the filesystem as ``static/style.css``.
483 unmodified lines
824can do it like this::825826 from werkzeug.contrib.fixers import LighttpdCGIRootFix827 app.wsgi_app = LighttpdCGIRootFix(app.wsgi_app)828829.. _quickstart_deployment:830831Deploying to a Web Server832-------------------------833834Ready to deploy your new Flask app? To wrap up the quickstart, you can835immediately deploy to a hosted platform, all of which offer a free plan for836small projects:837838- `Deploying Flask on Heroku <http://devcenter.heroku.com/articles/python>`_839- `Deploying Flask on ep.io <https://www.ep.io/docs/quickstart/flask/>`_840- `Deploying WSGI on dotCloud <http://docs.dotcloud.com/services/python/>`_841 with `Flask-specific notes <http://flask.pocoo.org/snippets/48/>`_842843Other places where you can host your Flask app:844845- `Deploying Flask on Webfaction <http://flask.pocoo.org/snippets/65/>`_846- `Deploying Flask on Google App Engine <https://github.com/kamalgill/flask-appengine-template>`_847- `Sharing your Localhost Server with Localtunnel <http://flask.pocoo.org/snippets/89/>`_848849If you manage your own hosts and would like to host yourself, see the chapter850on :ref:`deployment`.
modified:docs/signals.rst+13 added
129 unmodified lines
130 If you are writing a Flask extension and you want to gracefully degrade for131 missing blinker installations, you can do so by using the132 :class:`flask.signals.Namespace` class.133134.. _signals-sending:135136Sending Signals137---------------138139If you want to emit a signal, you can do so by calling the
17 unmodified lines
157 ``current_app._get_current_object()`` instead. The reason for this is158 that :data:`~flask.current_app` is a proxy and not the real application159 object.160161162Signals and Flask's Request Context163-----------------------------------164165Signals fully support :ref:`request-context` when receiving signals.166Context-local variables are consistently available between167:data:`~flask.request_started` and :data:`~flask.request_finished`, so you can168rely on :class:`flask.g` and others as needed. Note the limitations described169in :ref:`signals-sending` and the :data:`~flask.request_tearing_down` signal.170171172Decorator Based Signal Subscriptions173------------------------------------174175With Blinker 1.1 you can also easily subscribe to signals by using the new
96 unmodified lines
modified:flask/testsuite/basic.py+29 added
657 unmodified lines
658 self.assert_equal(rv.status_code, 404)659 self.assert_equal(rv.data, 'W00t')660 self.assert_equal(rv.mimetype, 'text/html')661662 def test_make_response_with_response_instance(self):663 app = flask.Flask(__name__)664 with app.test_request_context():665 rv = flask.make_response(666 flask.jsonify({'msg': 'W00t'}), 400)667 self.assertEqual(rv.status_code, 400)668 self.assertEqual(rv.data,669 '{\n "msg": "W00t"\n}')670 self.assertEqual(rv.mimetype, 'application/json')671672 rv = flask.make_response(673 flask.Response(''), 400)674 self.assertEqual(rv.status_code, 400)675 self.assertEqual(rv.data, '')676 self.assertEqual(rv.mimetype, 'text/html')677678 rv = flask.make_response(679 flask.Response('', headers={'Content-Type': 'text/html'}),680 400, None, 'application/json')681 self.assertEqual(rv.status_code, 400)682 self.assertEqual(rv.headers['Content-Type'], 'application/json')683684 rv = flask.make_response(685 flask.Response('', mimetype='application/json'),686 400, {'Content-Type': 'text/html'})687 self.assertEqual(rv.status_code, 400)688 self.assertEqual(rv.headers['Content-Type'], 'text/html')689690691 def test_url_generation(self):692 app = flask.Flask(__name__)693 @app.route('/hello/<name>', methods=['POST'])694 def hello():
455 unmodified lines
modified:flask/testsuite/blueprints.py+14 added
14 unmodified lines
15import unittest16import warnings17from flask.testsuite import FlaskTestCase, emits_module_deprecation_warning18from werkzeug.exceptions import NotFound19from werkzeug.http import parse_cache_control_header20from jinja2 import TemplateNotFound212223# import moduleapp here because it uses deprecated features and we don't
333 unmodified lines
357 self.assert_equal(rv.data.strip(), 'Admin File')358 rv = c.get('/admin/static/css/test.css')359 self.assert_equal(rv.data.strip(), '/* nested file */')360361 # try/finally, in case other tests use this app for Blueprint tests.362 max_age_default = app.config['SEND_FILE_MAX_AGE_DEFAULT']363 try:364 expected_max_age = 3600365 if app.config['SEND_FILE_MAX_AGE_DEFAULT'] == expected_max_age:366 expected_max_age = 7200367 app.config['SEND_FILE_MAX_AGE_DEFAULT'] = expected_max_age368 rv = c.get('/admin/static/css/test.css')369 cc = parse_cache_control_header(rv.headers['Cache-Control'])370 self.assert_equal(cc.max_age, expected_max_age)371 finally:372 app.config['SEND_FILE_MAX_AGE_DEFAULT'] = max_age_default373374 with app.test_request_context():375 self.assert_equal(flask.url_for('admin.static', filename='test.txt'),376 '/admin/static/test.txt')377
258 unmodified lines
modified:flask/testsuite/config.py+18 added
67 unmodified lines
68 self.common_object_test(app)69 finally:70 os.environ = env7172 def test_config_from_envvar_missing(self):73 env = os.environ74 try:75 os.environ = {'FOO_SETTINGS': 'missing.cfg'}76 try:77 app = flask.Flask(__name__)78 app.config.from_envvar('FOO_SETTINGS')79 except IOError, e:80 msg = str(e)81 self.assert_(msg.startswith('[Errno 2] Unable to load configuration '82 'file (No such file or directory):'))83 self.assert_(msg.endswith("missing.cfg'"))84 else:85 self.fail('expected IOError')86 self.assertFalse(app.config.from_envvar('FOO_SETTINGS', silent=True))87 finally:88 os.environ = env8990 def test_config_missing(self):91 app = flask.Flask(__name__)92 try:93 app.config.from_pyfile('missing.cfg')
207 unmodified lines
modified:flask/testsuite/helpers.py+54 added-1 removed
15 unmodified lines
16import unittest17from logging import StreamHandler18from StringIO import StringIO19from flask.testsuite import FlaskTestCase, catch_warnings, catch_stderr20from werkzeug.http import parse_options_header20from werkzeug.http import parse_cache_control_header, parse_options_header212223def has_encoding(name):24 try:
14 unmodified lines
39 c = app.test_client()40 rv = c.post('/json', data='malformed', content_type='application/json')41 self.assert_equal(rv.status_code, 400)4243 def test_json_bad_requests_content_type(self):44 app = flask.Flask(__name__)45 @app.route('/json', methods=['POST'])46 def return_json():47 return unicode(flask.request.json)48 c = app.test_client()49 rv = c.post('/json', data='malformed', content_type='application/json')50 self.assert_equal(rv.status_code, 400)51 self.assert_equal(rv.mimetype, 'application/json')52 self.assert_('description' in flask.json.loads(rv.data))53 self.assert_('<p>' not in flask.json.loads(rv.data)['description'])5455 def test_json_body_encoding(self):56 app = flask.Flask(__name__)57 app.testing = True58 @app.route('/')
13 unmodified lines
72 return flask.jsonify(**d)73 @app.route('/dict')74 def return_dict():75 return flask.jsonify(d)76 @app.route("/padded")77 def return_padded_json():78 return flask.jsonify(d, padded=True)79 @app.route("/padded_custom")80 def return_padded_json_custom_callback():81 return flask.jsonify(d, padded='my_func_name')82 c = app.test_client()83 for url in '/kw', '/dict':84 rv = c.get(url)85 self.assert_equal(rv.mimetype, 'application/json')86 self.assert_equal(flask.json.loads(rv.data), d)87 for get_arg in 'callback=funcName', 'jsonp=funcName':88 rv = c.get('/padded?' + get_arg)89 self.assert_( rv.data.startswith("funcName(") )90 self.assert_( rv.data.endswith(")") )91 rv_json = rv.data.split('(')[1].split(')')[0]92 self.assert_equal(flask.json.loads(rv_json), d)93 rv = c.get('/padded_custom?my_func_name=funcName')94 self.assert_( rv.data.startswith("funcName(") )9596 def test_json_attr(self):97 app = flask.Flask(__name__)98 @app.route('/add', methods=['POST'])
130 unmodified lines
229 value, options = parse_options_header(rv.headers['Content-Disposition'])230 self.assert_equal(value, 'attachment')231 self.assert_equal(options['filename'], 'index.txt')232233 def test_static_file(self):234 app = flask.Flask(__name__)235 # default cache timeout is 12 hours236 with app.test_request_context():237 rv = app.send_static_file('index.html')238 cc = parse_cache_control_header(rv.headers['Cache-Control'])239 self.assert_equal(cc.max_age, 12 * 60 * 60)240 app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 3600241 with app.test_request_context():242 rv = app.send_static_file('index.html')243 cc = parse_cache_control_header(rv.headers['Cache-Control'])244 self.assert_equal(cc.max_age, 3600)245 # override get_send_file_options with some new values and check them246 class StaticFileApp(flask.Flask):247 def get_send_file_options(self, filename):248 opts = super(StaticFileApp, self).get_send_file_options(filename)249 opts['cache_timeout'] = 10250 # this test catches explicit inclusion of the conditional251 # keyword arg in the guts252 opts['conditional'] = True253 return opts254 app = StaticFileApp(__name__)255 with app.test_request_context():256 rv = app.send_static_file('index.html')257 cc = parse_cache_control_header(rv.headers['Cache-Control'])258 self.assert_equal(cc.max_age, 10)259260261class LoggingTestCase(FlaskTestCase):262263 def test_logger_cache(self):264 app = flask.Flask(__name__)
148 unmodified lines
modified:flask/app.py+22 added-1 removed
247 unmodified lines
248 'SESSION_COOKIE_PATH': None,249 'SESSION_COOKIE_HTTPONLY': True,250 'SESSION_COOKIE_SECURE': False,251 'MAX_CONTENT_LENGTH': None,252 'SEND_FILE_MAX_AGE_DEFAULT': 12 * 60 * 60, # 12 hours253 'TRAP_BAD_REQUEST_ERRORS': False,254 'TRAP_HTTP_EXCEPTIONS': False,255 'PREFERRED_URL_SCHEME': 'http'256 })
764 unmodified lines
1021 else:1022 self.error_handler_spec.setdefault(key, {}).setdefault(None, []) \1023 .append((code_or_exception, f))10241025 def get_send_file_options(self, filename):1026 # Override: Hooks in SEND_FILE_MAX_AGE_DEFAULT config.1027 options = super(Flask, self).get_send_file_options(filename)1028 options['cache_timeout'] = self.config['SEND_FILE_MAX_AGE_DEFAULT']1029 return options10301031 @setupmethod1032 def template_filter(self, name=None):1033 """A decorator that is used to register custom template filter.1034 You can specify a name for the filter, otherwise the function
333 unmodified lines
1368 return rv1369 if isinstance(rv, basestring):1370 return self.response_class(rv)1371 if isinstance(rv, tuple):1372 if len(rv) > 0 and isinstance(rv[0], self.response_class):1373 original = rv[0]1374 new_response = self.response_class('', *rv[1:])1375 if len(rv) < 3:1376 # The args for the response class are1377 # response=None, status=None, headers=None,1378 # mimetype=None, content_type=None, ...1379 # so if there's at least 3 elements the rv1380 # tuple contains header information so the1381 # headers from rv[0] "win."1382 new_response.headers = original.headers1383 new_response.response = original.response1384 return new_response1385 else:1365 return self.response_class(*rv)1386 return self.response_class(*rv)1387 return self.response_class.force_type(rv, request.environ)13881389 def create_url_adapter(self, request):1390 """Creates a URL adapter for the given request. The URL adapter
203 unmodified lines
modified:flask/config.py+1 added-2 removed
104 unmodified lines
105 'and as such configuration could not be '106 'loaded. Set this variable and make it '107 'point to a configuration file' %108 variable_name)109 self.from_pyfile(rv)110 return True109 return self.from_pyfile(rv, silent=silent)110111 def from_pyfile(self, filename, silent=False):112 """Updates the values in the config from a Python file. This function113 behaves as if the file was imported as module with the
55 unmodified lines
added:flask/exceptions.py+49 added
1# -*- coding: utf-8 -*-2"""3 flask.exceptions4 ~~~~~~~~~~~~56 Flask specific additions to :class:`~werkzeug.exceptions.HTTPException`78 :copyright: (c) 2011 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11from werkzeug.exceptions import HTTPException, BadRequest12from .helpers import json131415class JSONHTTPException(HTTPException):16 """A base class for HTTP exceptions with ``Content-Type:17 application/json``.1819 The ``description`` attribute of this class must set to a string (*not* an20 HTML string) which describes the error.2122 """2324 def get_body(self, environ):25 """Overrides :meth:`werkzeug.exceptions.HTTPException.get_body` to26 return the description of this error in JSON format instead of HTML.2728 """29 return json.dumps(dict(description=self.get_description(environ)))3031 def get_headers(self, environ):32 """Returns a list of headers including ``Content-Type:33 application/json``.3435 """36 return [('Content-Type', 'application/json')]373839class JSONBadRequest(JSONHTTPException, BadRequest):40 """Represents an HTTP ``400 Bad Request`` error whose body contains an41 error message in JSON format instead of HTML format (as in the superclass).4243 """4445 #: The description of the error which occurred as a string.46 description = (47 'The browser (or proxy) sent a request that this server could not '48 'understand.'49 )
modified:flask/helpers.py+59 added-3 removed
116 unmodified lines
117 security reasons only objects are supported toplevel. For more118 information about this, have a look at :ref:`json-security`.119120 .. versionadded:: 0.2121122 .. versionadded:: 0.9123 If the ``padded`` argument is true, the JSON object will be padded124 for JSONP calls and the response mimetype will be changed to 125 ``application/javascript``. By default, the request arguments ``callback``126 and ``jsonp`` will be used as the name for the callback function.127 This will work with jQuery and most other JavaScript libraries128 by default.129130 If the ``padded`` argument is a string, jsonify will look for131 the request argument with the same name and use that value as the132 callback-function name.133 """134 if __debug__:135 _assert_have_json()136 if 'padded' in kwargs:137 if isinstance(kwargs['padded'], str):138 callback = request.args.get(kwargs['padded']) or 'jsonp'139 else:140 callback = request.args.get('callback') or \141 request.args.get('jsonp') or 'jsonp'142 del kwargs['padded']143 json_str = json.dumps(dict(*args, **kwargs), indent=None)144 content = str(callback) + "(" + json_str + ")"145 return current_app.response_class(content, mimetype='application/javascript')146 return current_app.response_class(json.dumps(dict(*args, **kwargs),147 indent=None if request.is_xhr else 2), mimetype='application/json')148149
154 unmodified lines
304 ``'error'`` for errors, ``'info'`` for information305 messages and ``'warning'`` for warnings. However any306 kind of string can be used as category.307 """308 # Original implementation:309 #286 session.setdefault('_flashes', []).append((category, message))310 # session.setdefault('_flashes', []).append((category, message))311 #312 # This assumed that changes made to mutable structures in the session are313 # are always in sync with the sess on object, which is not true for session314 # implementations that use external storage for keeping their keys/values.315 flashes = session.get('_flashes', [])316 flashes.append((category, message))317 session['_flashes'] = flashes318319320def get_flashed_messages(with_categories=False, category_filter=[]):321 """Pulls all flashed messages from the session and returns them.
49 unmodified lines
371 to send certain files as attachment (HTML for instance). The mimetype372 guessing requires a `filename` or an `attachment_filename` to be373 provided.374375 Note `get_send_file_options` in :class:`flask.Flask` hooks the376 ``SEND_FILE_MAX_AGE_DEFAULT`` configuration variable to set the default377 cache_timeout.378379 Please never pass filenames to this function from user sources without380 checking them first. Something like this is usually sufficient to381 avoid security problems::382
168 unmodified lines
551 """552 filename = safe_join(directory, filename)553 if not os.path.isfile(filename):554 raise NotFound()555 options.setdefault('conditional', True)520 return send_file(filename, conditional=True, **options)556 return send_file(filename, **options)557558559def get_root_path(import_name):560 """Returns the path to a package or cwd if that cannot be found. This
147 unmodified lines
708 if self.template_folder is not None:709 return FileSystemLoader(os.path.join(self.root_path,710 self.template_folder))711712 def get_send_file_options(self, filename):713 """Provides keyword arguments to send to :func:`send_from_directory`.714715 This allows subclasses to change the behavior when sending files based716 on the filename. For example, to set the cache timeout for .js files717 to 60 seconds (note the options are keywords for :func:`send_file`)::718719 class MyFlask(flask.Flask):720 def get_send_file_options(self, filename):721 options = super(MyFlask, self).get_send_file_options(filename)722 if filename.lower().endswith('.js'):723 options['cache_timeout'] = 60724 options['conditional'] = True725 return options726727 .. versionadded:: 0.9728 """729 return {}730731 def send_static_file(self, filename):732 """Function used internally to send static files from the static733 folder to the browser.734735 .. versionadded:: 0.5736 """737 if not self.has_static_folder:738 raise RuntimeError('No static folder for this object')684 return send_from_directory(self.static_folder, filename)739 return send_from_directory(self.static_folder, filename,740 **self.get_send_file_options(filename))741742 def open_resource(self, resource, mode='rb'):743 """Opens a resource from the application's resource folder. To see744 how this works, consider the following folder structure::
22 unmodified lines
modified:flask/views.py+1 added-1 removed
105 unmodified lines
106 def __new__(cls, name, bases, d):107 rv = type.__new__(cls, name, bases, d)108 if 'methods' not in d:109 methods = set(rv.methods or [])110 for key, value in d.iteritems():110 for key in d:111 if key in http_method_funcs:112 methods.add(key.upper())113 # if we have no method at all in there we don't want to114 # add a method list. (This is for instance the case for
36 unmodified lines
modified:flask/wrappers.py+14 added-4 removed
8 unmodified lines
9 :license: BSD, see LICENSE for more details.10"""1112from werkzeug.wrappers import Request as RequestBase, Response as ResponseBase13from werkzeug.exceptions import BadRequest13from werkzeug.utils import cached_property1415from .exceptions import JSONBadRequest16from .debughelpers import attach_enctype_error_multidict17from .helpers import json, _assert_have_json18from .globals import _request_ctx_stack19
87 unmodified lines
107 return self.on_json_loading_failed(e)108109 def on_json_loading_failed(self, e):110 """Called if decoding of the JSON data failed. The return value of111 this method is used by :attr:`json` when an error ocurred. The112 default implementation raises a :class:`~werkzeug.exceptions.BadRequest`.111 this method is used by :attr:`json` when an error ocurred. The default112 implementation raises a :class:`JSONBadRequest`, which is a subclass of113 :class:`~werkzeug.exceptions.BadRequest` which sets the114 ``Content-Type`` to ``application/json`` and provides a JSON-formatted115 error description::116117 {"description": "The browser (or proxy) sent a request that \118 this server could not understand."}119120 .. versionchanged:: 0.9121 Return a :class:`JSONBadRequest` instead of a122 :class:`~werkzeug.exceptions.BadRequest` by default.123124 .. versionadded:: 0.8125 """116 raise BadRequest()126 raise JSONBadRequest()127128 def _load_form_data(self):129 RequestBase._load_form_data(self)130
18 unmodified lines
modified:CHANGES+15 added-1 removed
6 unmodified lines
7-----------89Relase date to be decided, codename to be chosen.1011- The :func:`flask.Request.on_json_loading_failed` now returns a JSON formatted12 response by default.13- The :func:`flask.url_for` function now can generate anchors to the14 generated links.15- The :func:`flask.url_for` function now can also explicitly generate16 URL rules specific to a given HTTP method.
32 unmodified lines
49 single template name. On an iterable, the first template found is rendered.50- Added :meth:`flask.Flask.app_context` which works very similar to the51 request context but only provides access to the current application. This52 also adds support for URL generation without an active request context.53- View functions can now return a tuple with the first instance being an54 instance of :class:`flask.Response`. This allows for returning55 ``jsonify(error="error msg"), 400`` from a view function.56- :class:`flask.Flask` now provides a `get_send_file_options` hook for57 subclasses to override behavior of serving static files from Flask when using58 :meth:`flask.Flask.send_static_file` based on keywords in59 :func:`flask.helpers.send_file`. This hook is provided a filename, which for60 example allows changing cache controls by file extension. The default61 max-age for `send_static_file` can be configured through a new62 ``SEND_FILE_MAX_AGE_DEFAULT`` configuration variable, regardless of whether63 the `get_send_file_options` hook is used.64- Fixed an assumption in sessions implementation which could break message65 flashing on sessions implementations which use external storage.665267Version 0.8.168-------------6970Bugfix release, release date to be decided
293 unmodified lines
modified:LICENSE+1 added-1 removed
1Copyright (c) 2010 by Armin Ronacher and contributors. See AUTHORS1Copyright (c) 2012 by Armin Ronacher and contributors. See AUTHORS2for more details.34Some rights reserved.5
28 unmodified lines
modified:Makefile+4 added-2 removed
20 unmodified lines
21 find . -name '*.pyc' -exec rm -f {} +22 find . -name '*.pyo' -exec rm -f {} +23 find . -name '*~' -exec rm -f {} +2425# ebook-convert docs: http://manual.calibre-ebook.com/cli/ebook-convert.html25upload-docs:26 $(MAKE) -C docs html dirhtml latex epub27 $(MAKE) -C docs/_build/latex all-pdf28 cd docs/_build/; mv html flask-docs; zip -r flask-docs.zip flask-docs; mv flask-docs html29 rsync -a docs/_build/dirhtml/ pocoo.org:/var/www/flask.pocoo.org/docs/30 rsync -a docs/_build/latex/Flask.pdf pocoo.org:/var/www/flask.pocoo.org/docs/flask-docs.pdf31 rsync -a docs/_build/flask-docs.zip pocoo.org:/var/www/flask.pocoo.org/docs/flask-docs.zip32 rsync -a docs/_build/epub/Flask.epub pocoo.org:/var/www/flask.pocoo.org/docs/flask-docs.epub34 @echo 'Building .mobi from .epub...'3334# ebook-convert docs: http://manual.calibre-ebook.com/cli/ebook-convert.html35ebook:36 @echo 'Using .epub from `make upload-docs` to create .mobi.'37 @echo 'Command `ebook-covert` is provided by calibre package.'38 @echo 'Requires X-forwarding for Qt features used in conversion (ssh -X).'39 @echo 'Do not mind "Invalid value for ..." CSS errors if .mobi renders.'40 ssh -X pocoo.org ebook-convert /var/www/flask.pocoo.org/docs/flask-docs.epub /var/www/flask.pocoo.org/docs/flask-docs.mobi --cover http://flask.pocoo.org/docs/_images/logo-full.png --authors 'Armin Ronacher'
3 unmodified lines
modified:setup.py+4 added-1 removed
57 unmodified lines
58 import os, sys59 try:60 import pyflakes.scripts.pyflakes as flakes61 except ImportError:62 print "Audit requires PyFlakes installed in your system."""62 print "Audit requires PyFlakes installed in your system."63 sys.exit(-1)6465 warns = 066 # Define top-level directories
32 unmodified lines
99 'Intended Audience :: Developers',100 'License :: OSI Approved :: BSD License',101 'Operating System :: OS Independent',102 'Programming Language :: Python',103 'Programming Language :: Python :: 2.5',104 'Programming Language :: Python :: 2.6',105 'Programming Language :: Python :: 2.7',106 'Topic :: Internet :: WWW/HTTP :: Dynamic Content',107 'Topic :: Software Development :: Libraries :: Python Modules'108 ],109 cmdclass={'audit': run_audit},
2 unmodified lines
modified:tox.ini+3 added
1 unmodified line
2envlist=py25,py26,py27,pypy34[testenv]5commands=python run-tests.py67[testenv:py25]8deps=simplejson