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
Provenance
- Commit
3249eeb- Tree
3905777- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent 1
ab110d8- Parent 2
f071990
33 files changed+677 added−310 removed
modified:docs/deploying/fastcgi.rst+5 added-6 removed
1 unmodified line2 3 FastCGI4 =======5 6-FastCGI is a deployment option on servers like `nginx`_, `lighttpd`_,7-and `cherokee`_; see :ref:`deploying-uwsgi` and8-:ref:`deploying-other-servers` for other options. To use your WSGI9-application with any of them you will need a FastCGI server first. The10-most popular one is `flup`_ which we will use for this guide. Make sure11-to have it installed to follow along.6+FastCGI is a deployment option on servers like `nginx`_, `lighttpd`_, and7+`cherokee`_; see :ref:`deploying-uwsgi` and :ref:`deploying-wsgi-standalone`8+for other options. To use your WSGI application with any of them you will need9+a FastCGI server first. The most popular one is `flup`_ which we will use for10+this guide. Make sure to have it installed to follow along.11 12 .. admonition:: Watch Out13 14 Please make sure in advance that any ``app.run()`` calls you might149 unmodified linesmodified:docs/deploying/index.rst+6 added-3 removed
11 unmodified lines12 If you have a different WSGI server look up the server documentation13 about how to use a WSGI app with it. Just remember that your14 :class:`Flask` application object is the actual WSGI application.15 16+For hosted options to get up and running quickly, see17+:ref:`quickstart_deployment` in the Quickstart.18+19 .. toctree::20 :maxdepth: 221 22 mod_wsgi20- cgi21- fastcgi23+ wsgi-standalone24 uwsgi23- others25+ fastcgi26+ cgideleted:docs/deploying/others.rst-102 removed
1-.. _deploying-other-servers:2-3-Other Servers4-=============5-6-There are popular servers written in Python that allow the execution of WSGI7-applications as well. These servers stand alone when they run; you can proxy8-to them from your web server.9-10-Tornado11---------12-13-`Tornado`_ is an open source version of the scalable, non-blocking web14-server and tools that power `FriendFeed`_. Because it is non-blocking and15-uses epoll, it can handle thousands of simultaneous standing connections,16-which means it is ideal for real-time web services. Integrating this17-service with Flask is a trivial task::18-19- from tornado.wsgi import WSGIContainer20- from tornado.httpserver import HTTPServer21- from tornado.ioloop import IOLoop22- from yourapplication import app23-24- http_server = HTTPServer(WSGIContainer(app))25- http_server.listen(5000)26- IOLoop.instance().start()27-28-29-.. _Tornado: http://www.tornadoweb.org/30-.. _FriendFeed: http://friendfeed.com/31-32-Gevent33--------34-35-`Gevent`_ is a coroutine-based Python networking library that uses36-`greenlet`_ to provide a high-level synchronous API on top of `libevent`_37-event loop::38-39- from gevent.wsgi import WSGIServer40- from yourapplication import app41-42- http_server = WSGIServer(('', 5000), app)43- http_server.serve_forever()44-45-.. _Gevent: http://www.gevent.org/46-.. _greenlet: http://codespeak.net/py/0.9.2/greenlet.html47-.. _libevent: http://monkey.org/~provos/libevent/48-49-Gunicorn50---------51-52-`Gunicorn`_ 'Green Unicorn' is a WSGI HTTP Server for UNIX. It's a pre-fork53-worker model ported from Ruby's Unicorn project. It supports both `eventlet`_54-and `greenlet`_. Running a Flask application on this server is quite simple::55-56- gunicorn myproject:app57-58-`Gunicorn`_ provides many command-line options -- see ``gunicorn -h``.59-For example, to run a Flask application with 4 worker processes (``-w60-4``) binding to localhost port 4000 (``-b 127.0.0.1:4000``)::61-62- gunicorn -w 4 -b 127.0.0.1:4000 myproject:app63-64-.. _Gunicorn: http://gunicorn.org/65-.. _eventlet: http://eventlet.net/66-.. _greenlet: http://codespeak.net/py/0.9.2/greenlet.html67-68-Proxy Setups69-------------70-71-If you deploy your application using one of these servers behind an HTTP72-proxy you will need to rewrite a few headers in order for the73-application to work. The two problematic values in the WSGI environment74-usually are `REMOTE_ADDR` and `HTTP_HOST`. Werkzeug ships a fixer that75-will solve some common setups, but you might want to write your own WSGI76-middleware for specific setups.77-78-The most common setup invokes the host being set from `X-Forwarded-Host`79-and the remote address from `X-Forwarded-For`::80-81- from werkzeug.contrib.fixers import ProxyFix82- app.wsgi_app = ProxyFix(app.wsgi_app)83-84-Please keep in mind that it is a security issue to use such a middleware85-in a non-proxy setup because it will blindly trust the incoming86-headers which might be forged by malicious clients.87-88-If you want to rewrite the headers from another header, you might want to89-use a fixer like this::90-91- class CustomProxyFix(object):92-93- def __init__(self, app):94- self.app = app95-96- 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)101-102- app.wsgi_app = CustomProxyFix(app.wsgi_app)modified:docs/deploying/uwsgi.rst+4 added-5 removed
2 unmodified lines3 uWSGI4 =====5 6 uWSGI 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 WSGI9-application with uWSGI protocol you will need a uWSGI server10-first. uWSGI is both a protocol and an application server; the11-application server can serve uWSGI, FastCGI, and HTTP protocols.7+`cherokee`_; see :ref:`deploying-fastcgi` and :ref:`deploying-wsgi-standalone`8+for other options. To use your WSGI application with uWSGI protocol you will9+need a uWSGI server first. uWSGI is both a protocol and an application server;10+the application server can serve uWSGI, FastCGI, and HTTP protocols.11 12 The most popular uWSGI server is `uwsgi`_, which we will use for this13 guide. Make sure to have it installed to follow along.14 53 unmodified linesadded:docs/deploying/wsgi-standalone.rst+132 added
1+.. _deploying-wsgi-standalone:2+3+Standalone WSGI Containers4+==========================5+6+There are popular servers written in Python that contain WSGI applications and7+serve HTTP. These servers stand alone when they run; you can proxy to them8+from your web server. Note the section on :ref:`deploying-proxy-setups` if you9+run into issues.10+11+Gunicorn12+--------13+14+`Gunicorn`_ 'Green Unicorn' is a WSGI HTTP Server for UNIX. It's a pre-fork15+worker model ported from Ruby's Unicorn project. It supports both `eventlet`_16+and `greenlet`_. Running a Flask application on this server is quite simple::17+18+ gunicorn myproject:app19+20+`Gunicorn`_ provides many command-line options -- see ``gunicorn -h``.21+For example, to run a Flask application with 4 worker processes (``-w22+4``) binding to localhost port 4000 (``-b 127.0.0.1:4000``)::23+24+ gunicorn -w 4 -b 127.0.0.1:4000 myproject:app25+26+.. _Gunicorn: http://gunicorn.org/27+.. _eventlet: http://eventlet.net/28+.. _greenlet: http://codespeak.net/py/0.9.2/greenlet.html29+30+Tornado31+--------32+33+`Tornado`_ is an open source version of the scalable, non-blocking web34+server and tools that power `FriendFeed`_. Because it is non-blocking and35+uses epoll, it can handle thousands of simultaneous standing connections,36+which means it is ideal for real-time web services. Integrating this37+service with Flask is straightforward::38+39+ from tornado.wsgi import WSGIContainer40+ from tornado.httpserver import HTTPServer41+ from tornado.ioloop import IOLoop42+ from yourapplication import app43+44+ http_server = HTTPServer(WSGIContainer(app))45+ http_server.listen(5000)46+ IOLoop.instance().start()47+48+49+.. _Tornado: http://www.tornadoweb.org/50+.. _FriendFeed: http://friendfeed.com/51+52+Gevent53+-------54+55+`Gevent`_ is a coroutine-based Python networking library that uses56+`greenlet`_ to provide a high-level synchronous API on top of `libevent`_57+event loop::58+59+ from gevent.wsgi import WSGIServer60+ from yourapplication import app61+62+ http_server = WSGIServer(('', 5000), app)63+ http_server.serve_forever()64+65+.. _Gevent: http://www.gevent.org/66+.. _greenlet: http://codespeak.net/py/0.9.2/greenlet.html67+.. _libevent: http://monkey.org/~provos/libevent/68+69+.. _deploying-proxy-setups:70+71+Proxy Setups72+------------73+74+If you deploy your application using one of these servers behind an HTTP proxy75+you will need to rewrite a few headers in order for the application to work.76+The two problematic values in the WSGI environment usually are `REMOTE_ADDR`77+and `HTTP_HOST`. You can configure your httpd to pass these headers, or you78+can fix them in middleware. Werkzeug ships a fixer that will solve some common79+setups, but you might want to write your own WSGI middleware for specific80+setups.81+82+Here's a simple nginx configuration which proxies to an application served on83+localhost at port 8000, setting appropriate headers:84+85+.. sourcecode:: nginx86+87+ server {88+ listen 80;89+90+ server_name _;91+92+ access_log /var/log/nginx/access.log;93+ error_log /var/log/nginx/error.log;94+95+ location / {96+ proxy_pass http://127.0.0.1:8000/;97+ proxy_redirect off;98+99+ 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+ }104+105+If your httpd is not providing these headers, the most common setup invokes the106+host being set from `X-Forwarded-Host` and the remote address from107+`X-Forwarded-For`::108+109+ from werkzeug.contrib.fixers import ProxyFix110+ app.wsgi_app = ProxyFix(app.wsgi_app)111+112+.. admonition:: Trusting Headers113+114+ 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.117+118+If you want to rewrite the headers from another header, you might want to119+use a fixer like this::120+121+ class CustomProxyFix(object):122+123+ def __init__(self, app):124+ self.app = app125+126+ 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)131+132+ app.wsgi_app = CustomProxyFix(app.wsgi_app)modified:docs/patterns/appdispatch.rst+18 added
28 unmodified lines29 30 Note that :func:`run_simple <werkzeug.serving.run_simple>` is not intended for31 use in production. Use a :ref:`full-blown WSGI server <deployment>`.32 33+In order to use the interactive debuggger, debugging must be enabled both on34+the application and the simple server, here is the "hello world" example with35+debugging and :func:`run_simple <werkzeug.serving.run_simple>`::36 37+ from flask import Flask38+ from werkzeug.serving import run_simple39+40+ app = Flask(__name__)41+ app.debug = True42+43+ @app.route('/')44+ def hello_world():45+ return 'Hello World!'46+47+ if __name__ == '__main__':48+ run_simple('localhost', 5000, app,49+ use_reloader=True, use_debugger=True, use_evalex=True)50+51+52 Combining Applications53 ----------------------54 55 If you have entirely separated applications and you want them to work next133 unmodified linesmodified:docs/patterns/mongokit.rst+1 added-1 removed
139 unmodified lines140 >>> r['email']141 u'admin@localhost'142 143 For 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 lines54 1. 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.57 2. 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**.61 62 Here's an example `__init__.py`::53 unmodified linesmodified:docs/tutorial/setup.rst+10 added-10 removed
9 unmodified lines10 into the module which we will be doing here. However a cleaner solution11 would be to create a separate `.ini` or `.py` file and load that or import12 the values from there.13 14-::14+In `flaskr.py`::15 16 # all the imports17 import sqlite318 from flask import Flask, request, session, g, redirect, url_for, \6 unmodified lines25 USERNAME = 'admin'26 PASSWORD = 'default'27 28 Next we can create our actual application and initialize it with the29-config from the same file::29+config from the same file, in `flaskr.py`::30 31 # create our little application :)32 app = Flask(__name__)33 app.config.from_object(__name__)2 unmodified lines36 string it will import it) and then look for all uppercase variables37 defined there. In our case, the configuration we just wrote a few lines38 of code above. You can also move that into a separate file.39 40-It is also a good idea to be able to load a configuration from a41-configurable file. This is what :meth:`~flask.Config.from_envvar` can42-do::40+Usually, it is a good idea to load a configuration from a configurable41+file. This is what :meth:`~flask.Config.from_envvar` can do, replacing the42+:meth:`~flask.Config.from_object` line above::43 44 app.config.from_envvar('FLASKR_SETTINGS', silent=True)45 46 That way someone can set an environment variable called47-:envvar:`FLASKR_SETTINGS` to specify a config file to be loaded which will48-then override the default values. The silent switch just tells Flask to49-not complain if no such environment key is set.47+:envvar:`FLASKR_SETTINGS` to specify a config file to be loaded which will then48+override the default values. The silent switch just tells Flask to not complain49+if no such environment key is set.50 51 The `secret_key` is needed to keep the client-side sessions secure.52 Choose that key wisely and as hard to guess and complex as possible. The53-debug flag enables or disables the interactive debugger. Never leave54-debug mode activated in a production system because it will allow users to53+debug flag enables or disables the interactive debugger. *Never leave54+debug mode activated in a production system*, because it will allow users to55 execute code on the server!56 57 We also add a method to easily connect to the database specified. That58 can be used to open a connection on request and also from the interactive32 unmodified linesadded:docs/advanced_foreword.rst+67 added
1+Foreword for Experienced Programmers2+====================================3+4+This chapter is for programmers who have worked with other frameworks in the5+past, and who may have more specific or esoteric concerns that the typical6+user.7+8+Threads in Flask9+----------------10+11+One of the design decisions with Flask was that simple tasks should be simple;12+they should not take a lot of code and yet they should not limit you. Because13+of that we made a few design choices that some people might find surprising or14+unorthodox. For example, Flask uses thread-local objects internally so that15+you don’t have to pass objects around from function to function within a16+request in order to stay threadsafe. While this is a really easy approach and17+saves you a lot of time, it might also cause some troubles for very large18+applications because changes on these thread-local objects can happen anywhere19+in the same thread. In order to solve these problems we don’t hide the thread20+locals for you but instead embrace them and provide you with a lot of tools to21+make it as pleasant as possible to work with them.22+23+Web Development is Dangerous24+----------------------------25+26+If you write a web application, you are probably allowing users to register27+and leave their data on your server. The users are entrusting you with data.28+And even if you are the only user that might leave data in your application,29+you still want that data to be stored securely.30+31+Unfortunately, there are many ways the security of a web application can be32+compromised. Flask protects you against one of the most common security33+problems of modern web applications: cross-site scripting (XSS). Unless34+you deliberately mark insecure HTML as secure, Flask and the underlying35+Jinja2 template engine have you covered. But there are many more ways to36+cause security problems.37+38+The documentation will warn you about aspects of web development that39+require attention to security. Some of these security concerns40+are far more complex than one might think, and we all sometimes underestimate41+the likelihood that a vulnerability will be exploited - until a clever42+attacker figures out a way to exploit our applications. And don't think43+that your application is not important enough to attract an attacker.44+Depending on the kind of attack, chances are that automated bots are45+probing for ways to fill your database with spam, links to malicious46+software, and the like.47+48+So always keep security in mind when doing web development.49+50+The Status of Python 351+----------------------52+53+Currently the Python community is in the process of improving libraries to54+support the new iteration of the Python programming language. While the55+situation is greatly improving there are still some issues that make it56+hard for us to switch over to Python 3 just now. These problems are57+partially caused by changes in the language that went unreviewed for too58+long, partially also because we have not quite worked out how the lower-59+level API should change to account for the Unicode differences in Python 3.60+61+Werkzeug and Flask will be ported to Python 3 as soon as a solution for62+the changes is found, and we will provide helpful tips how to upgrade63+existing applications to Python 3. Until then, we strongly recommend64+using Python 2.6 and 2.7 with activated Python 3 warnings during65+development. If you plan on upgrading to Python 3 in the near future we66+strongly recommend that you read `How to write forwards compatible67+Python code <http://lucumr.pocoo.org/2011/1/22/forwards-compatible-python/>`_.modified:docs/api.rst+1 added-1 removed
523 unmodified lines524 525 The following converters are available:526 527 =========== ===============================================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 linesmodified:docs/conf.py+1 added-1 removed
41 unmodified lines42 master_doc = 'index'43 44 # General information about the project.45 project = u'Flask'46-copyright = u'2010, Armin Ronacher'46+copyright = u'2012, Armin Ronacher'47 48 # 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 linesmodified:docs/config.rst+8 added-1 removed
108 unmodified lines109 ``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 it158 unmodified lines282 DATABASE_URI = 'sqlite://:memory:'283 284 class ProductionConfig(Config):285 DATABASE_URI = 'mysql://user@localhost/foo'279- 286+287 class DevelopmentConfig(Config):288 DEBUG = True289 290 class TestingConfig(Config):110 unmodified linesmodified:docs/extensiondev.rst+56 added-73 removed
123 unmodified lines124 Initializing Extensions125 -----------------------126 127 Many extensions will need some kind of initialization step. For example,128-consider your application is currently connecting to SQLite like the129-documentation suggests (:ref:`sqlite3`) you will need to provide a few130-functions and before / after request handlers. So how does the extension128+consider an application that's currently connecting to SQLite like the129+documentation suggests (:ref:`sqlite3`). So how does the extension130 know the name of the application object?131 132 Quite simple: you pass it to it.133 134 There are two recommended ways for an extension to initialize:135 136 initialization functions:137+138 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.142 143 classes:144+145 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.150 151 What to use depends on what you have in mind. For the SQLite 3 extension151-we will use the class-based approach because it will provide users with a152-manager object that handles opening and closing database connections.152+we will use the class-based approach because it will provide users with an153+object that handles opening and closing database connections.154 155 The Extension Code156 ------------------157 158 Here's the contents of the `flask_sqlite3.py` for copy/paste::159 159- from __future__ import absolute_import160 import sqlite3161 162 from flask import _request_ctx_stack163 164+165 class SQLite3(object):166 166- 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 = None173+174+ 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 lines187 def teardown_request(self, exception):188 ctx = _request_ctx_stack.top189 ctx.sqlite3_db.close()190 183- def get_db(self):191+ @property192+ def connection(self):193 ctx = _request_ctx_stack.top194 if ctx is not None:195 return ctx.sqlite3_db196 197+198 So here's what these lines of code do:199 190-1. 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.194-2. 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.198-3. Next, we define a `connect` function that opens a database connection.200+1. The ``__init__`` method takes an optional app object and, if supplied, will201+ call ``init_app``.202+2. 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.208+3. Next, we define a ``connect`` method that opens a database connection.209 4. 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.203-5. 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.213+5. Finally, we add a ``connection`` property that simplifies access to the context's214 database.215 216 So why did we decide on a class-based approach here? Because using our217 extension looks something like this::2 unmodified lines220 from flask_sqlite3 import SQLite3221 222 app = Flask(__name__)223 app.config.from_pyfile('the-config.cfg')214- manager = SQLite3(app)215- db = manager.get_db()224+ db = SQLite3(app)225 226 You can then use the database from views like this::227 228 @app.route('/')229 def show_all():221- cur = db.cursor()230+ cur = db.connection.cursor()231 cur.execute(...)232 224-Opening a database connection from outside a view function is simple.233+Additionally, the ``init_app`` method is used to support the factory pattern234+for creating apps::235 226->>> 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)240 230-Adding an `init_app` Function231------------------------------241+Keep in mind that supporting this factory pattern for creating apps is required242+for approved flask extensions (described below).243 233-In practice, you'll almost always want to permit users to initialize your234-extension and provide an app object after the fact. This can help avoid235-circular import problems when a user is breaking their app into multiple files.236-Our extension could add an `init_app` function as follows::244 238- class SQLite3(object):245+Using _request_ctx_stack246+------------------------247 240- 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 = None248+In the example above, before every request, a ``sqlite3_db`` variable is assigned249+to ``_request_ctx_stack.top``. In a view function, this variable is accessible250+using the ``connection`` property of ``SQLite3``. During the teardown of a251+request, the ``sqlite3_db`` connection is closed. By using this pattern, the252+*same* connection to the sqlite3 database is accessible to anything that needs it253+for the duration of the request.254 247- 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)252-253- def connect(self):254- return sqlite3.connect(app.config['SQLITE3_DATABASE'])255-256- def before_request(self):257- ctx = _request_ctx_stack.top258- ctx.sqlite3_db = self.connect()259-260- def teardown_request(self, exception):261- ctx = _request_ctx_stack.top262- ctx.sqlite3_db.close()263-264- def get_db(self):265- ctx = _request_ctx_stack.top266- if ctx is not None:267- return ctx.sqlite3_db268-269-The user could then initialize the extension in one file::270-271- manager = SQLite3()272-273-and bind their app to the extension in another file::274-275- manager.init_app(app)276-255 End-Of-Request Behavior256 -----------------------257 258 Due to the change in Flask 0.7 regarding functions that are run at the end10 unmodified lines269 app.teardown_request(close_connection)270 else:271 app.after_request(close_connection)272 273+274 Strictly speaking the above code is wrong, because teardown functions are275 passed the exception and typically don't return anything. However because276 the return value is discarded this will just work assuming that the code277 in between does not touch the passed parameter.26 unmodified lines304 new releases. These approved extensions are listed on the `Flask305 Extension Registry`_ and marked appropriately. If you want your own306 extension to be approved you have to follow these guidelines:307 308+0. 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.312 1. 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.315 2. 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.321 3. APIs of approved extensions will be checked for the following322 characteristics:323 324 - an approved extension has to support multiple applications46 unmodified linesmodified:docs/foreword.rst+37 added-82 removed
6 unmodified lines7 8 What does "micro" mean?9 -----------------------10 11-To me, the "micro" in microframework refers not only to the simplicity and12-small size of the framework, but also the fact that it does not make many13-decisions for you. While Flask does pick a templating engine for you, we14-won't make such decisions for your datastore or other parts.11+“Micro” does not mean that your whole web application has to fit into12+a single Python file (although it certainly can). Nor does it mean13+that Flask is lacking in functionality. The "micro" in microframework14+means Flask aims to keep the core simple but extensible. Flask won't make 15+many decisions for you, such as what database to use. Those decisions that 16+it does make, such as what templating engine to use, are easy to change. 17+Everything else is up to you, so that Flask can be everything you need 18+and nothing you don't.19 16-However, to us the term “micro” does not mean that the whole implementation17-has to fit into a single Python file.20+By default, Flask does not include a database abstraction layer, form21+validation or anything else where different libraries already exist that can22+handle that. Instead, FLask extensions add such functionality to your23+application as if it was implemented in Flask itself. Numerous extensions24+provide database integration, form validation, upload handling, various open25+authentication technologies, and more. Flask may be "micro", but the26+possibilities are endless.27 19-One of the design decisions with Flask was that simple tasks should be20-simple; they should not take a lot of code and yet they should not limit you.21-Because of that we made a few design choices that some people might find22-surprising or unorthodox. For example, Flask uses thread-local objects23-internally so that you don't have to pass objects around from function to24-function within a request in order to stay threadsafe. While this is a25-really easy approach and saves you a lot of time, it might also cause some26-troubles for very large applications because changes on these thread-local27-objects can happen anywhere in the same thread. In order to solve these28-problems we don't hide the thread locals for you but instead embrace them29-and provide you with a lot of tools to make it as pleasant as possible to30-work with them.28+Convention over Configuration29+-----------------------------30 32-Flask is also based on convention over configuration, which means that33-many things are preconfigured. For example, by convention templates and34-static files are stored in subdirectories within the application's Python source tree.35-While this can be changed you usually don't have to.31+Flask is based on convention over configuration, which means that many things32+are preconfigured. For example, by convention templates and static files are33+stored in subdirectories within the application's Python source tree. While34+this can be changed you usually don't have to. We want to minimize the time35+you need to spend in order to get up and running, without assuming things 36+about your needs.37 37-The main reason Flask is called a "microframework" is the idea38-to keep the core simple but extensible. There is no database abstraction39-layer, no form validation or anything else where different libraries40-already exist that can handle that. However Flask supports41-extensions to add such functionality to your application as if it42-was implemented in Flask itself. There are currently extensions for43-object-relational mappers, form validation, upload handling, various open44-authentication technologies and more.38+Growing Up39+----------40 46-Since Flask is based on a very solid foundation there is not a lot of code47-in Flask itself. As such it's easy to adapt even for large applications48-and we are making sure that you can either configure it as much as49-possible by subclassing things or by forking the entire codebase. If you50-are interested in that, check out the :ref:`becomingbig` chapter.41+Since Flask is based on a very solid foundation there is not a lot of code in42+Flask itself. As such it's easy to adapt even for large applications and we43+are making sure that you can either configure it as much as possible by44+subclassing things or by forking the entire codebase. If you are interested45+in that, check out the :ref:`becomingbig` chapter.46 52-If you are curious about the Flask design principles, head over to the53-section about :ref:`design`.47+If you are curious about the Flask design principles, head over to the section48+about :ref:`design`.49 55-Web Development is Dangerous56-----------------------------50+For the Stalwart and Wizened...51+-------------------------------52 58-I'm not joking. Well, maybe a little. If you write a web59-application, you are probably allowing users to register and leave their60-data on your server. The users are entrusting you with data. And even if61-you are the only user that might leave data in your application, you still62-want that data to be stored securely.63-64-Unfortunately, there are many ways the security of a web application can be65-compromised. Flask protects you against one of the most common security66-problems of modern web applications: cross-site scripting (XSS). Unless67-you deliberately mark insecure HTML as secure, Flask and the underlying68-Jinja2 template engine have you covered. But there are many more ways to69-cause security problems.70-71-The documentation will warn you about aspects of web development that72-require attention to security. Some of these security concerns73-are far more complex than one might think, and we all sometimes underestimate74-the likelihood that a vulnerability will be exploited - until a clever75-attacker figures out a way to exploit our applications. And don't think76-that your application is not important enough to attract an attacker.77-Depending on the kind of attack, chances are that automated bots are78-probing for ways to fill your database with spam, links to malicious79-software, and the like.80-81-So always keep security in mind when doing web development.82-83-The Status of Python 384-----------------------85-86-Currently the Python community is in the process of improving libraries to87-support the new iteration of the Python programming language. While the88-situation is greatly improving there are still some issues that make it89-hard for us to switch over to Python 3 just now. These problems are90-partially caused by changes in the language that went unreviewed for too91-long, partially also because we have not quite worked out how the lower-92-level API should change to account for the Unicode differences in Python 3.93-94-Werkzeug and Flask will be ported to Python 3 as soon as a solution for95-the changes is found, and we will provide helpful tips how to upgrade96-existing applications to Python 3. Until then, we strongly recommend97-using Python 2.6 and 2.7 with activated Python 3 warnings during98-development. If you plan on upgrading to Python 3 in the near future we99-strongly recommend that you read `How to write forwards compatible100-Python code <http://lucumr.pocoo.org/2011/1/22/forwards-compatible-python/>`_.53+If you're more curious about the minutiae of Flask's implementation, and54+whether its structure is right for your needs, read the55+:ref:`advanced_foreword`.modified:docs/installation.rst+1 added-1 removed
92 unmodified lines93 System-Wide Installation94 ------------------------95 96 This is possible as well, though I do not recommend it. Just run97-`easy_install` with root privileges::97+`pip` with root privileges::98 99 $ sudo pip install Flask100 101 (On Windows systems, run it in a command-prompt window with administrator73 unmodified linesmodified:docs/quickstart.rst+28 added-6 removed
166 unmodified lines167 =========== ===========================================168 169 .. admonition:: Unique URLs / Redirection Behaviour170 171- 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.174 175 Take these two rules::176 15 unmodified lines192 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.194 195 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.199 200 32 unmodified lines233 /user/John%20Doe234 235 (This also uses the :meth:`~flask.Flask.test_request_context` method, explained236 below. It tells Flask to behave as though it is handling a request, even237-though were are interacting with it through a Python shell. Have a look at the237+though we are interacting with it through a Python shell. Have a look at the238 explanation below. :ref:`context-locals`).239 240 Why would you want to build URLs instead of hard-coding them into your241 templates? There are three good reasons for this:90 unmodified lines332 configured to serve them for you, but during development Flask can do that333 as well. Just create a folder called `static` in your package or next to334 your module and it will be available at `/static` on the application.335 336-To generate URLs that part of the URL, use the special ``'static'`` URL337-name::336+To generate URLs for static files, use the special ``'static'`` endpoint name::337 338 url_for('static', filename='style.css')339 340 The file has to be stored on the filesystem as ``static/style.css``.483 unmodified lines824 can do it like this::825 826 from werkzeug.contrib.fixers import LighttpdCGIRootFix827 app.wsgi_app = LighttpdCGIRootFix(app.wsgi_app)828+829+.. _quickstart_deployment:830+831+Deploying to a Web Server832+-------------------------833+834+Ready to deploy your new Flask app? To wrap up the quickstart, you can835+immediately deploy to a hosted platform, all of which offer a free plan for836+small projects:837+838+- `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/>`_842+843+Other places where you can host your Flask app:844+845+- `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/>`_848+849+If you manage your own hosts and would like to host yourself, see the chapter850+on :ref:`deployment`.modified:docs/signals.rst+13 added
129 unmodified lines130 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.133 134+.. _signals-sending:135+136 Sending Signals137 ---------------138 139 If you want to emit a signal, you can do so by calling the17 unmodified lines157 ``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.160 161+162+Signals and Flask's Request Context163+-----------------------------------164+165+Signals fully support :ref:`request-context` when receiving signals.166+Context-local variables are consistently available between167+:data:`~flask.request_started` and :data:`~flask.request_finished`, so you can168+rely on :class:`flask.g` and others as needed. Note the limitations described169+in :ref:`signals-sending` and the :data:`~flask.request_tearing_down` signal.170+171+172 Decorator Based Signal Subscriptions173 ------------------------------------174 175 With Blinker 1.1 you can also easily subscribe to signals by using the new96 unmodified linesmodified:flask/testsuite/basic.py+29 added
657 unmodified lines658 self.assert_equal(rv.status_code, 404)659 self.assert_equal(rv.data, 'W00t')660 self.assert_equal(rv.mimetype, 'text/html')661 662+ 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')671+672+ 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')677+678+ 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')683+684+ 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')689+690+691 def test_url_generation(self):692 app = flask.Flask(__name__)693 @app.route('/hello/<name>', methods=['POST'])694 def hello():455 unmodified linesmodified:flask/testsuite/blueprints.py+14 added
14 unmodified lines15 import unittest16 import warnings17 from flask.testsuite import FlaskTestCase, emits_module_deprecation_warning18 from werkzeug.exceptions import NotFound19+from werkzeug.http import parse_cache_control_header20 from jinja2 import TemplateNotFound21 22 23 # import moduleapp here because it uses deprecated features and we don't333 unmodified lines357 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 */')360 361+ # 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_default373+374 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 linesmodified:flask/testsuite/config.py+18 added
67 unmodified lines68 self.common_object_test(app)69 finally:70 os.environ = env71 72+ 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 = env89+90 def test_config_missing(self):91 app = flask.Flask(__name__)92 try:93 app.config.from_pyfile('missing.cfg')207 unmodified linesmodified:flask/testsuite/helpers.py+54 added-1 removed
15 unmodified lines16 import unittest17 from logging import StreamHandler18 from StringIO import StringIO19 from flask.testsuite import FlaskTestCase, catch_warnings, catch_stderr20-from werkzeug.http import parse_options_header20+from werkzeug.http import parse_cache_control_header, parse_options_header21 22 23 def has_encoding(name):24 try:14 unmodified lines39 c = app.test_client()40 rv = c.post('/json', data='malformed', content_type='application/json')41 self.assert_equal(rv.status_code, 400)42 43+ 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'])54+55 def test_json_body_encoding(self):56 app = flask.Flask(__name__)57 app.testing = True58 @app.route('/')13 unmodified lines72 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(") )95 96 def test_json_attr(self):97 app = flask.Flask(__name__)98 @app.route('/add', methods=['POST'])130 unmodified lines229 value, options = parse_options_header(rv.headers['Content-Disposition'])230 self.assert_equal(value, 'attachment')231 self.assert_equal(options['filename'], 'index.txt')232 233+ 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)259 260+261 class LoggingTestCase(FlaskTestCase):262 263 def test_logger_cache(self):264 app = flask.Flask(__name__)148 unmodified linesmodified:flask/app.py+22 added-1 removed
247 unmodified lines248 '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 lines1021 else:1022 self.error_handler_spec.setdefault(key, {}).setdefault(None, []) \1023 .append((code_or_exception, f))1024 1025+ 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 options1030+1031 @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 function333 unmodified lines1368 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)1388 1389 def create_url_adapter(self, request):1390 """Creates a URL adapter for the given request. The URL adapter203 unmodified linesmodified:flask/config.py+1 added-2 removed
104 unmodified lines105 '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)110 111 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 the55 unmodified linesadded:flask/exceptions.py+49 added
1+# -*- coding: utf-8 -*-2+"""3+ flask.exceptions4+ ~~~~~~~~~~~~5+6+ Flask specific additions to :class:`~werkzeug.exceptions.HTTPException`7+8+ :copyright: (c) 2011 by Armin Ronacher.9+ :license: BSD, see LICENSE for more details.10+"""11+from werkzeug.exceptions import HTTPException, BadRequest12+from .helpers import json13+14+15+class JSONHTTPException(HTTPException):16+ """A base class for HTTP exceptions with ``Content-Type:17+ application/json``.18+19+ The ``description`` attribute of this class must set to a string (*not* an20+ HTML string) which describes the error.21+22+ """23+24+ 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.27+28+ """29+ return json.dumps(dict(description=self.get_description(environ)))30+31+ def get_headers(self, environ):32+ """Returns a list of headers including ``Content-Type:33+ application/json``.34+35+ """36+ return [('Content-Type', 'application/json')]37+38+39+class 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).42+43+ """44+45+ #: 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 lines117 security reasons only objects are supported toplevel. For more118 information about this, have a look at :ref:`json-security`.119 120 .. versionadded:: 0.2121+122+ .. 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.129+130+ 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')148 149 154 unmodified lines304 ``'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'] = flashes318 319 320 def get_flashed_messages(with_categories=False, category_filter=[]):321 """Pulls all flashed messages from the session and returns them.49 unmodified lines371 to send certain files as attachment (HTML for instance). The mimetype372 guessing requires a `filename` or an `attachment_filename` to be373 provided.374 375+ Note `get_send_file_options` in :class:`flask.Flask` hooks the376+ ``SEND_FILE_MAX_AGE_DEFAULT`` configuration variable to set the default377+ cache_timeout.378+379 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 lines551 """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)557 558 559 def get_root_path(import_name):560 """Returns the path to a package or cwd if that cannot be found. This147 unmodified lines708 if self.template_folder is not None:709 return FileSystemLoader(os.path.join(self.root_path,710 self.template_folder))711 712+ def get_send_file_options(self, filename):713+ """Provides keyword arguments to send to :func:`send_from_directory`.714+715+ 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`)::718+719+ 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 options726+727+ .. versionadded:: 0.9728+ """729+ return {}730+731 def send_static_file(self, filename):732 """Function used internally to send static files from the static733 folder to the browser.734 735 .. 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))741 742 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 linesmodified:flask/views.py+1 added-1 removed
105 unmodified lines106 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 for36 unmodified linesmodified:flask/wrappers.py+14 added-4 removed
8 unmodified lines9 :license: BSD, see LICENSE for more details.10 """11 12 from werkzeug.wrappers import Request as RequestBase, Response as ResponseBase13-from werkzeug.exceptions import BadRequest13 from werkzeug.utils import cached_property14 15+from .exceptions import JSONBadRequest16 from .debughelpers import attach_enctype_error_multidict17 from .helpers import json, _assert_have_json18 from .globals import _request_ctx_stack19 87 unmodified lines107 return self.on_json_loading_failed(e)108 109 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::116 117+ {"description": "The browser (or proxy) sent a request that \118+ this server could not understand."}119+120+ .. versionchanged:: 0.9121+ Return a :class:`JSONBadRequest` instead of a122+ :class:`~werkzeug.exceptions.BadRequest` by default.123+124 .. versionadded:: 0.8125 """116- raise BadRequest()126+ raise JSONBadRequest()127 128 def _load_form_data(self):129 RequestBase._load_form_data(self)130 18 unmodified linesmodified:CHANGES+15 added-1 removed
6 unmodified lines7 -----------8 9 Relase date to be decided, codename to be chosen.10 11+- 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 lines49 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.66 52-67 Version 0.8.168 -------------69 70 Bugfix release, release date to be decided293 unmodified linesmodified:LICENSE+1 added-1 removed
1-Copyright (c) 2010 by Armin Ronacher and contributors. See AUTHORS1+Copyright (c) 2012 by Armin Ronacher and contributors. See AUTHORS2 for more details.3 4 Some rights reserved.5 28 unmodified linesmodified:Makefile+4 added-2 removed
20 unmodified lines21 find . -name '*.pyc' -exec rm -f {} +22 find . -name '*.pyo' -exec rm -f {} +23 find . -name '*~' -exec rm -f {} +24 25-# ebook-convert docs: http://manual.calibre-ebook.com/cli/ebook-convert.html25 upload-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...'33+34+# ebook-convert docs: http://manual.calibre-ebook.com/cli/ebook-convert.html35+ebook: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 linesmodified:setup.py+4 added-1 removed
57 unmodified lines58 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)64 65 warns = 066 # Define top-level directories32 unmodified lines99 '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 linesmodified:tox.ini+3 added
1 unmodified line2 envlist=py25,py26,py27,pypy3 4 [testenv]5 commands=python run-tests.py6+7+[testenv:py25]8+deps=simplejson