Improved documentation, added a contextmanager for request binding
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 · parent 44b42e0 · Browse files · 4 files·+198 added−28 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+198 added−28 removed
- other:+198 added−28 removed
Provenance
- Commit
3b36bef- Tree
d21429c- Author
Armin Ronacher <mitsuhiko@nausicaa.local>- Committer
Armin Ronacher <mitsuhiko@nausicaa.local>- Parent
44b42e0
4 files changed+198 added−28 removed
modified:docs/api.rst+152 added-2 removed
6 unmodified lines7 parts where Flask depends on external libraries, we document the most8 important right here and provide links to the canonical documentation.9 10 11-General Structure12------------------11+Application Object12+------------------13 14 .. autoclass:: Flask15 :members:16+17+Incoming Request Data18+---------------------19+20+.. class:: request21+22+ To access incoming request data, you can use the global `request`23+ object. Flask parses incoming request data for you and gives you24+ access to it through that global object. Internally Flask makes25+ sure that you always get the correct data for the active thread if you26+ are in a multithreaded environment.27+28+ The request object is an instance of a :class:`~werkzeug.Request`29+ subclass and provides all of the attributes Werkzeug defines. This30+ just shows a quick overview of the most important ones.31+32+ .. attribute:: form33+34+ A :class:`~werkzeug.MultiDict` with the parsed form data from `POST`35+ or `PUT` requests. Please keep in mind that file uploads will not36+ end up here, but instead in the :attr:`files` attribute.37+38+ .. attribute:: args39+40+ A :class:`~werkzeug.MultiDict` with the parsed contents of the query41+ string. (The part in the URL after the question mark).42+43+ .. attribute:: values44+45+ A :class:`~werkzeug.CombinedMultiDict` with the contents of both46+ :attr:`form` and :attr:`args`.47+48+ .. attribute:: cookies49+50+ A :class:`dict` with the contents of all cookies transmitted with51+ the request.52+53+ .. attribute:: stream54+55+ If the incoming form data was not encoded with a known encoding (for56+ example it was transmitted as JSON) the data is stored unmodified in57+ this stream for consumption. For example to read the incoming58+ request data as JSON, one can do the following::59+60+ json_body = simplejson.load(request.stream)61+62+ .. attribute:: files63+64+ A :class:`~werkzeug.MultiDict` with files uploaded as part of a65+ `POST` or `PUT` request. Each file is stored as66+ :class:`~werkzeug.FileStorage` object. It basically behaves like a67+ standard file object you know from Python, with the difference that68+ it also has a :meth:`~werkzeug.FileStorage.save` function that can69+ store the file on the filesystem.70+71+ .. attribute:: method72+73+ The current request method (``POST``, ``GET`` etc.)74+75+ .. attribute:: path76+ .. attribute:: script_root77+ .. attribute:: url78+ .. attribute:: base_url79+ .. attribute:: url_root80+81+ Provides different ways to look at the current URL. Imagine your82+ application is listening on the following URL::83+84+ http://www.example.com/myapplication85+86+ And a user requests the following URL::87+88+ http://www.example.com/myapplication/page.html?x=y89+90+ In this case the values of the above mentioned attributes would be91+ the following:92+93+ ============= ======================================================94+ `path` ``/page.html``95+ `script_root` ``/myapplication``96+ `url` ``http://www.example.com/myapplication/page.html``97+ `base_url` ``http://www.example.com/myapplication/page.html?x=y``98+ `root_url` ``http://www.example.com/myapplication/``99+ ============= ======================================================100+101+102+Sessions103+--------104+105+If you have the :attr:`Flask.secret_key` set you can use sessions in Flask106+applications. A session basically makes it possible to remember107+information from one request to another. The way Flask does this is by108+using a signed cookie. So the user can look at the session contents, but109+not modify it unless he knows the secret key, so make sure to set that to110+something complex and unguessable.111+112+To access the current session you can use the :class:`session` object:113+114+.. class:: session115+116+ The session object works pretty much like an ordinary dict, with the117+ difference that it keeps track on modifications.118+119+ The following attributes are interesting:120+121+ .. attribute:: new122+123+ `True` if the session is new, `False` otherwise.124+125+ .. attribute:: modified126+127+ `True` if the session object detected a modification. Be advised128+ that modifications on mutable structures are not picked up129+ automatically, in that situation you have to explicitly set the130+ attribute to `True` yourself. Here an example::131+132+ # this change is not picked up because a mutable object (here133+ # a list) is changed.134+ session['objects'].append(42)135+ # so mark it as modified yourself136+ session.modified = True137+138+139+Useful Functions and Classes140+----------------------------141+142+.. autofunction:: url_for143+144+.. autofunction:: abort145+146+.. autofunction:: redirect147+148+.. autofunction:: escape149+150+.. autoclass:: Markup151+ :members: escape, unescape, striptags152+153+Message Flashing154+----------------155+156+.. autofunction:: flash157+158+.. autofunction:: get_flashed_messages159+160+Template Rendering161+------------------162+163+.. autofunction:: render_template164+165+.. autofunction:: render_template_stringmodified:docs/conf.py+6 added-1 removed
23 unmodified lines24 #needs_sphinx = '1.0'25 26 # Add any Sphinx extension module names here, as strings. They can be extensions27 # coming with Sphinx (named 'sphinx.ext.*') or your custom ones.28-extensions = ['sphinx.ext.autodoc']28+extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx']29 30 # Add any paths that contain templates here, relative to this directory.31 templates_path = ['_templates']32 200 unmodified lines233 #epub_exclude_files = []234 235 # The depth of the table of contents in toc.ncx.236 #epub_tocdepth = 3237+238+intersphinx_mapping = {239+ 'http://docs.python.org/dev': None,240+ 'http://werkzeug.pocoo.org/documentation/dev/': None241+}modified:examples/minitwit/minitwit.py+2 added-2 removed
5 unmodified lines6 from hashlib import md57 from datetime import datetime8 from contextlib import closing9 from flask import Flask, request, session, url_for, redirect, \10- render_template, abort, g, flash, generate_password_hash, \11- check_password_hash10+ render_template, abort, g, flash11+from werkzeug import check_password_hash, generate_password_hash12 13 14 # configuration15 DATABASE = '/tmp/minitwit.db'213 unmodified linesmodified:flask.py+38 added-23 removed
11 unmodified lines12 import os13 import sys14 import pkg_resources15 from threading import local16+from contextlib import contextmanager17 from jinja2 import Environment, PackageLoader17-from werkzeug import Request, Response, LocalStack, LocalProxy18+from werkzeug import Request, Response, LocalStack, LocalProxy, \19+ create_environ, cached_property20 from werkzeug.routing import Map, Rule21 from werkzeug.exceptions import HTTPException, InternalServerError22 from werkzeug.contrib.securecookie import SecureCookie23 22-# try to import the json helpers23-try:24- from simplejson import loads as load_json, dumps as dump_json25-except ImportError:26- try:27- from json import loads as load_json, dumps as dump_json28- except ImportError:29- pass30-24 # utilities we import from Werkzeug and Jinja2 that are unused25 # in the module but are exported as public interface.33-from werkzeug import abort, redirect, secure_filename, cached_property, \34- html, import_string, generate_password_hash, check_password_hash26+from werkzeug import abort, redirect27 from jinja2 import Markup, escape28 29 30 class FlaskRequest(Request):43 unmodified lines74 """75 return _request_ctx_stack.top.url_adapter.build(endpoint, values)76 77 86-def jsonified(**values):87- """Returns a json response"""88- return current_app.response_class(dump_json(values),89- mimetype='application/json')90-91-78 def flash(message):79 """Flashes a message to the next request. In order to remove the80 flashed message from the session and to display it to the user,81 the template has to call :func:`get_flashed_messages`.16 unmodified lines98 def render_template(template_name, **context):99 """Renders a template from the template folder with the given100 context.101 """102+ current_app.update_template_context(context)103 return current_app.jinja_env.get_template(template_name).render(context)104 105 106 def render_template_string(source, **context):107 """Renders a template from the given template source string108 with the given context.109 """110+ current_app.update_template_context(context)111 return current_app.jinja_env.from_string(source).render(context)112 113 114 class Flask(object):92 unmodified lines207 self.jinja_env = Environment(loader=self.create_jinja_loader(),208 **self.jinja_options)209 self.jinja_env.globals.update(210 url_for=url_for,223- request=request,224- session=session,225- g=g,211 get_flashed_messages=get_flashed_messages212 )213 214 def create_jinja_loader(self):3 unmodified lines218 override this method.219 """220 return PackageLoader(self.package_name)221 222+ def update_template_context(self, context):223+ """Update the template context with some commonly used variables.224+ This injects request, session and g into the template context.225+ """226+ reqctx = _request_ctx_stack.top227+ context['request'] = reqctx.request228+ context['session'] = reqctx.session229+ context['g'] = reqctx.g230+231 def run(self, host='localhost', port=5000, **options):232 """Runs the application on a local development server. If the233 :attr:`debug` flag is set the server will automatically reload234 for code changes and show a debugger in case an exception happened.201 unmodified lines436 `__call__` so that middlewares can be applied:437 438 app.wsgi_app = MyMiddleware(app.wsgi_app)439 """446- _request_ctx_stack.push(_RequestContext(self, environ))447- try:440+ with self.request_context(environ):441 rv = self.preprocess_request()442 if rv is None:443 rv = self.dispatch_request()444 response = self.make_response(rv)445 response = self.process_response(response)446 return response(environ, start_response)447+448+ @contextmanager449+ def request_context(self, environ):450+ """Creates a request context from the given environment and binds451+ it to the current context. This must be used in combination with452+ the `with` statement because the request is only bound to the453+ current context for the duration of the `with` block.454+455+ Example usage::456+457+ with app.request_context(environ):458+ do_something_with(request)459+ """460+ _request_ctx_stack.push(_RequestContext(self, environ))461+ try:462+ yield463 finally:464 _request_ctx_stack.pop()465 466+ def test_request_context(self, *args, **kwargs):467+ """Creates a WSGI environment from the given values (see468+ :func:`werkzeug.create_environ` for more information).469+ """470+ return self.request_context(create_environ(*args, **kwargs))471+472 def __call__(self, environ, start_response):473 """Shortcut for :attr:`wsgi_app`"""474 return self.wsgi_app(environ, start_response)475 7 unmodified lines