Skip to content
Myr

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

4 files+198 added−28 removed

modified:docs/api.rst+152 added-2 removed
6 unmodified lines
7parts where Flask depends on external libraries, we document the most8important right here and provide links to the canonical documentation.91011General Structure12-----------------11Application Object12------------------1314.. autoclass:: Flask15 :members:1617Incoming Request Data18---------------------1920.. class:: request2122 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.2728 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.3132 .. attribute:: form3334 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.3738 .. attribute:: args3940 A :class:`~werkzeug.MultiDict` with the parsed contents of the query41 string. (The part in the URL after the question mark).4243 .. attribute:: values4445 A :class:`~werkzeug.CombinedMultiDict` with the contents of both46 :attr:`form` and :attr:`args`.4748 .. attribute:: cookies4950 A :class:`dict` with the contents of all cookies transmitted with51 the request.5253 .. attribute:: stream5455 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::5960 json_body = simplejson.load(request.stream)6162 .. attribute:: files6364 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.7071 .. attribute:: method7273 The current request method (``POST``, ``GET`` etc.)7475 .. attribute:: path76 .. attribute:: script_root77 .. attribute:: url78 .. attribute:: base_url79 .. attribute:: url_root8081 Provides different ways to look at the current URL. Imagine your82 application is listening on the following URL::8384 http://www.example.com/myapplication8586 And a user requests the following URL::8788 http://www.example.com/myapplication/page.html?x=y8990 In this case the values of the above mentioned attributes would be91 the following:9293 ============= ======================================================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 ============= ======================================================100101102Sessions103--------104105If you have the :attr:`Flask.secret_key` set you can use sessions in Flask106applications. A session basically makes it possible to remember107information from one request to another. The way Flask does this is by108using a signed cookie. So the user can look at the session contents, but109not modify it unless he knows the secret key, so make sure to set that to110something complex and unguessable.111112To access the current session you can use the :class:`session` object:113114.. class:: session115116 The session object works pretty much like an ordinary dict, with the117 difference that it keeps track on modifications.118119 The following attributes are interesting:120121 .. attribute:: new122123 `True` if the session is new, `False` otherwise.124125 .. attribute:: modified126127 `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::131132 # 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 = True137138139Useful Functions and Classes140----------------------------141142.. autofunction:: url_for143144.. autofunction:: abort145146.. autofunction:: redirect147148.. autofunction:: escape149150.. autoclass:: Markup151 :members: escape, unescape, striptags152153Message Flashing154----------------155156.. autofunction:: flash157158.. autofunction:: get_flashed_messages159160Template Rendering161------------------162163.. autofunction:: render_template164165.. autofunction:: render_template_string
modified:docs/conf.py+6 added-1 removed
23 unmodified lines
24#needs_sphinx = '1.0'2526# Add any Sphinx extension module names here, as strings. They can be extensions27# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.28extensions = ['sphinx.ext.autodoc']28extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx']2930# Add any paths that contain templates here, relative to this directory.31templates_path = ['_templates']32
200 unmodified lines
233#epub_exclude_files = []234235# The depth of the table of contents in toc.ncx.236#epub_tocdepth = 3237238intersphinx_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 lines
6from hashlib import md57from datetime import datetime8from contextlib import closing9from 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, flash11from werkzeug import check_password_hash, generate_password_hash121314# configuration15DATABASE = '/tmp/minitwit.db'
213 unmodified lines
modified:flask.py+38 added-23 removed
11 unmodified lines
12import os13import sys14import pkg_resources15from threading import local16from contextlib import contextmanager17from jinja2 import Environment, PackageLoader17from werkzeug import Request, Response, LocalStack, LocalProxy18from werkzeug import Request, Response, LocalStack, LocalProxy, \19 create_environ, cached_property20from werkzeug.routing import Map, Rule21from werkzeug.exceptions import HTTPException, InternalServerError22from werkzeug.contrib.securecookie import SecureCookie2322# try to import the json helpers23try:24 from simplejson import loads as load_json, dumps as dump_json25except ImportError:26 try:27 from json import loads as load_json, dumps as dump_json28 except ImportError:29 pass3024# utilities we import from Werkzeug and Jinja2 that are unused25# in the module but are exported as public interface.33from werkzeug import abort, redirect, secure_filename, cached_property, \34 html, import_string, generate_password_hash, check_password_hash26from werkzeug import abort, redirect27from jinja2 import Markup, escape282930class FlaskRequest(Request):
43 unmodified lines
74 """75 return _request_ctx_stack.top.url_adapter.build(endpoint, values)767786def jsonified(**values):87 """Returns a json response"""88 return current_app.response_class(dump_json(values),89 mimetype='application/json')909178def 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 lines
98def 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)104105106def 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)112113114class Flask(object):
92 unmodified lines
207 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 )213214 def create_jinja_loader(self):
3 unmodified lines
218 override this method.219 """220 return PackageLoader(self.package_name)221222 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.g230231 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 lines
436 `__call__` so that middlewares can be applied:437438 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)447448 @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.454455 Example usage::456457 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()465466 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))471472 def __call__(self, environ, start_response):473 """Shortcut for :attr:`wsgi_app`"""474 return self.wsgi_app(environ, start_response)475
7 unmodified lines