flask.py
This file
Path
flask.py
801 lines · 29.9 KiB · Python
Last changed by
Use setdefault() because it sets session.modified correctly.florentxbefore adoptiondbe0df7
History of this fileTake it
Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 1–111# -*- coding: utf-8 -*-2"""3 flask4 ~~~~~56 A microframework based on Werkzeug. It's extensively documented7 and follows best practice patterns.89 :copyright: (c) 2010 by Armin Ronacher.10 :license: BSD, see LICENSE for more details.11"""Can't believe I forgot that future import.Armin Ronacherbefore adoption1d8432e
line 12why, one step back12from __future__ import with_statementInitial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 13–1413import os14import sysFlask now runs without the presence of pkg_resources as well.Armin Ronacherbefore adoption2d9bb69
lines 15–16why, one step back1516from jinja2 import Environment, PackageLoader, FileSystemLoaderAdded testing documentationArmin Ronacherbefore adoption03148db
line 17why, one step back17from werkzeug import Request as RequestBase, Response as ResponseBase, \Added JSON Support and started working on jQuery docsArmin Ronacherbefore adoption6e2be6a
line 18why, one step back18 LocalStack, LocalProxy, create_environ, SharedDataMiddleware, \Documented some routing converter possibilities.Armin Ronacherbefore adoption95750b3
line 19why, one step back19 ImmutableDict, cached_property20from werkzeug.routing import Map, RuleRemoved two unused imports.Armin Ronacherbefore adoption0770f5c
line 21why, one step back21from werkzeug.exceptions import HTTPExceptionInitial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 22–2322from werkzeug.contrib.securecookie import SecureCookie23Added JSON Support and started working on jQuery docsArmin Ronacherbefore adoption6e2be6a
lines 24–34why, one step back24# try to load the best simplejson implementation available. If JSON25# is not installed, we add a failing class.26json_available = True27try:28 import simplejson as json29except ImportError:30 try:31 import json32 except ImportError:33 json_available = False34Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 35–3635# utilities we import from Werkzeug and Jinja2 that are unused36# in the module but are exported as public interface.Improved documentation, added a contextmanager for request bindingArmin Ronacherbefore adoption3b36bef
line 37why, one step back37from werkzeug import abort, redirectInitial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 38–3938from jinja2 import Markup, escape39Flask now runs without the presence of pkg_resources as well.Armin Ronacherbefore adoption2d9bb69
lines 40–47why, one step back40# use pkg_resource if that works, otherwise fall back to cwd. The41# current working directory is generally not reliable with the notable42# exception of google appengine.43try:44 import pkg_resources45 pkg_resources.resource_stream46except (ImportError, AttributeError):47 pkg_resources = None48Flask now runs without the presence of pkg_resources as well.Armin Ronacherbefore adoption2d9bb69
line 49why, one step back49Added testing documentationArmin Ronacherbefore adoption03148db
line 50why, one step back50class Request(RequestBase):Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 51–5251 """The request object used by default in flask. Remembers the52 matched endpoint and view arguments.Added testing documentationArmin Ronacherbefore adoption03148db
lines 53–56why, one step back5354 It is what ends up as :class:`~flask.request`. If you want to replace55 the request object used you can subclass this and set56 :attr:`~flask.Flask.request_class` to your subclass.Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 57–5857 """58Use a tuple to store _flashes, and simplify the flask.Request class.florentxbefore adoption3eacc1d
line 59why, one step back59 endpoint = view_args = None60Added JSON Support and started working on jQuery docsArmin Ronacherbefore adoption6e2be6a
lines 61–65why, one step back61 @cached_property62 def json(self):63 """If the mimetype is `application/json` this will contain the64 parsed JSON data.65 """Some more documentation updates.Armin Ronacherbefore adoption715f64d
lines 66–67why, one step back66 if __debug__:67 _assert_have_json()Added JSON Support and started working on jQuery docsArmin Ronacherbefore adoption6e2be6a
lines 68–69why, one step back68 if self.mimetype == 'application/json':69 return json.loads(self.data)70Added JSON Support and started working on jQuery docsArmin Ronacherbefore adoption6e2be6a
line 71why, one step back71Added testing documentationArmin Ronacherbefore adoption03148db
line 72why, one step back72class Response(ResponseBase):Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 73–7473 """The response object that is used by default in flask. Works like the74 response object from Werkzeug but is set to have a HTML mimetype byAdded testing documentationArmin Ronacherbefore adoption03148db
lines 75–79why, one step back75 default. Quite often you don't have to create this object yourself because76 :meth:`~flask.Flask.make_response` will take care of that for you.7778 If you want to replace the response object used you can subclass this and79 set :attr:`~flask.Flask.request_class` to your subclass.Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 80–8780 """81 default_mimetype = 'text/html'828384class _RequestGlobals(object):85 pass8687Session falls back to a dummy object now if secret_key is missing.Armin Ronacherbefore adoption5310fc3
lines 88–102why, one step back88class _NullSession(SecureCookie):89 """Class used to generate nicer error messages if sessions are not90 available. Will still allow read-only access to the empty session91 but fail on setting.92 """9394 def _fail(self, *args, **kwargs):95 raise RuntimeError('the session is unavailable because no secret '96 'key was set. Set the secret_key on the '97 'application to something unique and secret')98 __setitem__ = __delitem__ = clear = pop = popitem = \99 update = setdefault = _fail100 del _fail101102Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 103–114103class _RequestContext(object):104 """The request context contains all request relevant information. It is105 created at the beginning of the request and pushed to the106 `_request_ctx_stack` and removed at the end of it. It will create the107 URL adapter and request object for the WSGI environment provided.108 """109110 def __init__(self, app, environ):111 self.app = app112 self.url_adapter = app.url_map.bind_to_environ(environ)113 self.request = app.request_class(environ)114 self.session = app.open_session(self.request)Session falls back to a dummy object now if secret_key is missing.Armin Ronacherbefore adoption5310fc3
lines 115–116why, one step back115 if self.session is None:116 self.session = _NullSession()Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 117–119117 self.g = _RequestGlobals()118 self.flashes = None119Preserve the request context in debug mode.Armin Ronacherbefore adoption7b50150
lines 120–121why, one step back120 def __enter__(self):121 _request_ctx_stack.push(self)122Preserve the request context in debug mode.Armin Ronacherbefore adoption7b50150
lines 123–130why, one step back123 def __exit__(self, exc_type, exc_value, tb):124 # do not pop the request stack if we are in debug mode and an125 # exception happened. This will allow the debugger to still126 # access the request object in the interactive shell.127 if tb is None or not self.app.debug:128 _request_ctx_stack.pop()129130Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 131–139131def url_for(endpoint, **values):132 """Generates a URL to the given endpoint with the method provided.133134 :param endpoint: the endpoint of the URL (name of the function)135 :param values: the variable arguments of the URL rule136 """137 return _request_ctx_stack.top.url_adapter.build(endpoint, values)138139Added support for macro pulling and documented certain design decisions.Armin Ronacherbefore adoption190059c
lines 140–153why, one step back140def get_template_attribute(template_name, attribute):141 """Loads a macro (or variable) a template exports. This can be used to142 invoke a macro from within Python code. If you for example have a143 template named `_foo.html` with the following contents:144145 .. sourcecode:: html+jinja146147 {% macro hello(name) %}Hello {{ name }}!{% endmacro %}148149 You can access this from Python code like this::150151 hello = get_template_attribute('_foo.html', 'hello')152 return hello('World')153Added JSON Support and started working on jQuery docsArmin Ronacherbefore adoption6e2be6a
lines 154–155why, one step back154 .. versionadded:: 0.2155Added support for macro pulling and documented certain design decisions.Armin Ronacherbefore adoption190059c
lines 156–162why, one step back156 :param template_name: the name of the template157 :param attribute: the name of the variable of macro to acccess158 """159 return getattr(current_app.jinja_env.get_template(template_name).module,160 attribute)161162Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 163–166163def flash(message):164 """Flashes a message to the next request. In order to remove the165 flashed message from the session and to display it to the user,166 the template has to call :func:`get_flashed_messages`.Heavily improved documentationArmin Ronacherbefore adoption05f36c7
lines 167–168why, one step back167168 :param message: the message to be flashed.169 """Use setdefault() because it sets session.modified correctly.florentxbefore adoptiondbe0df7
line 170why, one step back170 session.setdefault('_flashes', []).append(message)Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 171–179171172173def get_flashed_messages():174 """Pulls all flashed messages from the session and returns them.175 Further calls in the same request to the function will return176 the same messages.177 """178 flashes = _request_ctx_stack.top.flashes179 if flashes is None:Use setdefault() because it sets session.modified correctly.florentxbefore adoptiondbe0df7
line 180why, one step back180 _request_ctx_stack.top.flashes = flashes = session.pop('_flashes', [])Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 181–183181 return flashes182183Added JSON Support and started working on jQuery docsArmin Ronacherbefore adoption6e2be6a
lines 184–208why, one step back184def jsonify(*args, **kwargs):185 """Creates a :class:`~flask.Response` with the JSON representation of186 the given arguments with an `application/json` mimetype. The arguments187 to this function are the same as to the :class:`dict` constructor.188189 Example usage::190191 @app.route('/_get_current_user')192 def get_current_user():193 return jsonify(username=g.user.username,194 email=g.user.email,195 id=g.user.id)196197 This will send a JSON response like this to the browser::198199 {200 "username": "admin",201 "email": "admin@localhost",202 "id": 42203 }204205 This requires Python 2.6 or an installed version of simplejson.206207 .. versionadded:: 0.2208 """Some more documentation updates.Armin Ronacherbefore adoption715f64d
lines 209–210why, one step back209 if __debug__:210 _assert_have_json()Added JSON Support and started working on jQuery docsArmin Ronacherbefore adoption6e2be6a
lines 211–214why, one step back211 return current_app.response_class(json.dumps(dict(*args, **kwargs),212 indent=None if request.is_xhr else 2), mimetype='application/json')213214Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 215–217215def render_template(template_name, **context):216 """Renders a template from the template folder with the given217 context.Heavily improved documentationArmin Ronacherbefore adoption05f36c7
lines 218–221why, one step back218219 :param template_name: the name of the template to be rendered220 :param context: the variables that should be available in the221 context of the template.222 """Improved documentation, added a contextmanager for request bindingArmin Ronacherbefore adoption3b36bef
line 223why, one step back223 current_app.update_template_context(context)Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 224–229224 return current_app.jinja_env.get_template(template_name).render(context)225226227def render_template_string(source, **context):228 """Renders a template from the given template source string229 with the given context.Heavily improved documentationArmin Ronacherbefore adoption05f36c7
lines 230–234why, one step back230231 :param template_name: the sourcecode of the template to be232 rendered233 :param context: the variables that should be available in the234 context of the template.235 """Improved documentation, added a contextmanager for request bindingArmin Ronacherbefore adoption3b36bef
line 236why, one step back236 current_app.update_template_context(context)Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 237–239237 return current_app.jinja_env.from_string(source).render(context)238239Fixed a documentation error and implemented template context processors.Armin Ronacherbefore adoptiona01e8b4
lines 240–251why, one step back240def _default_template_ctx_processor():241 """Default template context processor. Injects `request`,242 `session` and `g`.243 """244 reqctx = _request_ctx_stack.top245 return dict(246 request=reqctx.request,247 session=reqctx.session,248 g=reqctx.g249 )250251Some more documentation updates.Armin Ronacherbefore adoption715f64d
line 252why, one step back252def _assert_have_json():Fix typos and remove unused import.florentxbefore adoption3c821a0
line 253why, one step back253 """Helper function that fails if JSON is unavailable."""Some more documentation updates.Armin Ronacherbefore adoption715f64d
lines 254–257why, one step back254 if not json_available:255 raise RuntimeError('simplejson not installed')256257Added screenshot of the debugger to Flask docs. Flask now runs from theArmin Ronacherbefore adoption40e0024
lines 258–265why, one step back258def _get_package_path(name):259 """Returns the path to a package or cwd if that cannot be found."""260 try:261 return os.path.abspath(os.path.dirname(sys.modules[name].__file__))262 except (KeyError, AttributeError):263 return os.getcwd()264265Tiny refactoringArmin Ronacherbefore adoptionaf3b73f
lines 266–268why, one step back266# figure out if simplejson escapes slashes. This behaviour was changed267# from one version to another without reason.268if not json_available or '\\/' not in json.dumps('/'):Fix a doc oversight, and revert 5876a8fd.florentxbefore adoptionf014ce2
line 269why, one step back269Tiny refactoringArmin Ronacherbefore adoptionaf3b73f
line 270why, one step back270 def _tojson_filter(*args, **kwargs):Slightly faster _tojson_filter.florentxbefore adoption75057bb
lines 271–272why, one step back271 if __debug__:272 _assert_have_json()Tiny refactoringArmin Ronacherbefore adoptionaf3b73f
line 273why, one step back273 return json.dumps(*args, **kwargs).replace('/', '\\/')Slightly faster _tojson_filter.florentxbefore adoption75057bb
lines 274–275why, one step back274else:275 _tojson_filter = json.dumpsFixed a security problem caused by changed simplejson semantics.Armin Ronacherbefore adoptionade4905
lines 276–277why, one step back276277Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 278–279278class Flask(object):279 """The flask object implements a WSGI application and acts as the centralStarted working on documentation.Armin Ronacherbefore adoption4ec7d2a
lines 280–295why, one step back280 object. It is passed the name of the module or package of the281 application. Once it is created it will act as a central registry for282 the view functions, the URL rules, template configuration and much more.283284 The name of the package is used to resolve resources from inside the285 package or the folder the module is contained in depending on if the286 package parameter resolves to an actual python package (a folder with287 an `__init__.py` file inside) or a standard module (just a `.py` file).288289 For more information about resource loading, see :func:`open_resource`.290291 Usually you create a :class:`Flask` instance in your main module or292 in the `__init__.py` file of your package like this::293294 from flask import Flask295 app = Flask(__name__)Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 296–297296 """297Added testing documentationArmin Ronacherbefore adoption03148db
lines 298–300why, one step back298 #: the class that is used for request objects. See :class:`~flask.request`299 #: for more information.300 request_class = Request301Added testing documentationArmin Ronacherbefore adoption03148db
lines 302–304why, one step back302 #: the class that is used for response objects. See303 #: :class:`~flask.Response` for more information.304 response_class = ResponseInitial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 305–319305306 #: path for the static files. If you don't want to use static files307 #: you can set this value to `None` in which case no URL rule is added308 #: and the development server will no longer serve any static files.309 static_path = '/static'310311 #: if a secret key is set, cryptographic components can use this to312 #: sign cookies and other things. Set this to a complex random value313 #: when you want to use the secure cookie for instance.314 secret_key = None315316 #: The secure cookie uses this for the name of the session cookie317 session_cookie_name = 'session'318319 #: options that are passed directly to the Jinja2 environmentDocumented some routing converter possibilities.Armin Ronacherbefore adoption95750b3
line 320why, one step back320 jinja_options = ImmutableDict(Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 321–325321 autoescape=True,322 extensions=['jinja2.ext.autoescape', 'jinja2.ext.with_']323 )324325 def __init__(self, package_name):Started working on documentation.Armin Ronacherbefore adoption4ec7d2a
lines 326–330why, one step back326 #: the debug flag. Set this to `True` to enable debugging of327 #: the application. In debug mode the debugger will kick in328 #: when an unhandled exception ocurrs and the integrated server329 #: will automatically reload the application if changes in the330 #: code are detected.331 self.debug = FalseStarted working on documentation.Armin Ronacherbefore adoption4ec7d2a
lines 332–334why, one step back332333 #: the name of the package or module. Do not change this once334 #: it was set by the constructor.335 self.package_name = package_nameStarted working on documentation.Armin Ronacherbefore adoption4ec7d2a
line 336why, one step back336Flask now runs without the presence of pkg_resources as well.Armin Ronacherbefore adoption2d9bb69
line 337why, one step back337 #: where is the app root located?Added screenshot of the debugger to Flask docs. Flask now runs from theArmin Ronacherbefore adoption40e0024
line 338why, one step back338 self.root_path = _get_package_path(self.package_name)Flask now runs without the presence of pkg_resources as well.Armin Ronacherbefore adoption2d9bb69
line 339why, one step back339Started working on documentation.Armin Ronacherbefore adoption4ec7d2a
lines 340–343why, one step back340 #: a dictionary of all view functions registered. The keys will341 #: be function names which are also used to generate URLs and342 #: the values are the function objects themselves.343 #: to register a view function, use the :meth:`route` decorator.344 self.view_functions = {}Started working on documentation.Armin Ronacherbefore adoption4ec7d2a
lines 345–350why, one step back345346 #: a dictionary of all registered error handlers. The key is347 #: be the error code as integer, the value the function that348 #: should handle that error.349 #: To register a error handler, use the :meth:`errorhandler`350 #: decorator.351 self.error_handlers = {}Started working on documentation.Armin Ronacherbefore adoption4ec7d2a
lines 352–356why, one step back352353 #: a list of functions that should be called at the beginning354 #: of the request before request dispatching kicks in. This355 #: can for example be used to open database connections or356 #: getting hold of the currently logged in user.request_init -> before_request and request_shutdown -> after_requestArmin Ronacherbefore adoptionfb2d2e4
line 357why, one step back357 #: To register a function here, use the :meth:`before_request`Started working on documentation.Armin Ronacherbefore adoption4ec7d2a
line 358why, one step back358 #: decorator.request_init -> before_request and request_shutdown -> after_requestArmin Ronacherbefore adoptionfb2d2e4
line 359why, one step back359 self.before_request_funcs = []Started working on documentation.Armin Ronacherbefore adoption4ec7d2a
lines 360–361why, one step back360361 #: a list of functions that are called at the end of theFixed typo and added AUTHORS file and license text to docs.Armin Ronacherbefore adoption3a1e518
line 362why, one step back362 #: request. The function is passed the current responseStarted working on documentation.Armin Ronacherbefore adoption4ec7d2a
line 363why, one step back363 #: object and modify it in place or replace it.request_init -> before_request and request_shutdown -> after_requestArmin Ronacherbefore adoptionfb2d2e4
line 364why, one step back364 #: To register a function here use the :meth:`after_request`Started working on documentation.Armin Ronacherbefore adoption4ec7d2a
line 365why, one step back365 #: decorator.request_init -> before_request and request_shutdown -> after_requestArmin Ronacherbefore adoptionfb2d2e4
line 366why, one step back366 self.after_request_funcs = []Fixed a documentation error and implemented template context processors.Armin Ronacherbefore adoptiona01e8b4
lines 367–374why, one step back367368 #: a list of functions that are called without arguments369 #: to populate the template context. Each returns a dictionary370 #: that the template context is updated with.371 #: To register a function here, use the :meth:`context_processor`372 #: decorator.373 self.template_context_processors = [_default_template_ctx_processor]374Documented some routing converter possibilities.Armin Ronacherbefore adoption95750b3
lines 375–389why, one step back375 #: the :class:`~werkzeug.routing.Map` for this instance. You can use376 #: this to change the routing converters after the class was created377 #: but before any routes are connected. Example::378 #:379 #: from werkzeug import BaseConverter380 #:381 #: class ListConverter(BaseConverter):382 #: def to_python(self, value):383 #: return value.split(',')384 #: def to_url(self, values):385 #: return ','.join(BaseConverter.to_url(value)386 #: for value in values)387 #:388 #: app = Flask(__name__)389 #: app.url_map.converters['list'] = ListConverterInitial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 390–392390 self.url_map = Map()391392 if self.static_path is not None:Documented some routing converter possibilities.Armin Ronacherbefore adoption95750b3
lines 393–394why, one step back393 self.add_url_rule(self.static_path + '/<filename>',394 build_only=True, endpoint='static')Flask now runs without the presence of pkg_resources as well.Armin Ronacherbefore adoption2d9bb69
lines 395–398why, one step back395 if pkg_resources is not None:396 target = (self.package_name, 'static')397 else:398 target = os.path.join(self.root_path, 'static')Static files are active in the WSGI app now, not just the server.Armin Ronacherbefore adoptionca520fb
line 399why, one step back399 self.wsgi_app = SharedDataMiddleware(self.wsgi_app, {Flask now runs without the presence of pkg_resources as well.Armin Ronacherbefore adoption2d9bb69
line 400why, one step back400 self.static_path: targetStatic files are active in the WSGI app now, not just the server.Armin Ronacherbefore adoptionca520fb
line 401why, one step back401 })402Started working on documentation.Armin Ronacherbefore adoption4ec7d2a
lines 403–405why, one step back403 #: the Jinja2 environment. It is created from the404 #: :attr:`jinja_options` and the loader that is returned405 #: by the :meth:`create_jinja_loader` function.Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 406–411406 self.jinja_env = Environment(loader=self.create_jinja_loader(),407 **self.jinja_options)408 self.jinja_env.globals.update(409 url_for=url_for,410 get_flashed_messages=get_flashed_messages411 )Some more documentation updates.Armin Ronacherbefore adoption715f64d
line 412why, one step back412 self.jinja_env.filters['tojson'] = _tojson_filterInitial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 413–419413414 def create_jinja_loader(self):415 """Creates the Jinja loader. By default just a package loader for416 the configured package is returned that looks up templates in the417 `templates` folder. To add other loaders it's possible to418 override this method.419 """Flask now runs without the presence of pkg_resources as well.Armin Ronacherbefore adoption2d9bb69
lines 420–421why, one step back420 if pkg_resources is None:421 return FileSystemLoader(os.path.join(self.root_path, 'templates'))Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 422–423422 return PackageLoader(self.package_name)423Improved documentation, added a contextmanager for request bindingArmin Ronacherbefore adoption3b36bef
lines 424–426why, one step back424 def update_template_context(self, context):425 """Update the template context with some commonly used variables.426 This injects request, session and g into the template context.Heavily improved documentationArmin Ronacherbefore adoption05f36c7
lines 427–429why, one step back427428 :param context: the context as a dictionary that is updated in place429 to add extra variables.Improved documentation, added a contextmanager for request bindingArmin Ronacherbefore adoption3b36bef
line 430why, one step back430 """Fixed a documentation error and implemented template context processors.Armin Ronacherbefore adoptiona01e8b4
lines 431–432why, one step back431 for func in self.template_context_processors:432 context.update(func())Improved documentation, added a contextmanager for request bindingArmin Ronacherbefore adoption3b36bef
line 433why, one step back433flask uses 127.0.0.1 as host by default now. stupid chrome.Armin Ronacherbefore adoption00f87f6
line 434why, one step back434 def run(self, host='127.0.0.1', port=5000, **options):Started working on documentation.Armin Ronacherbefore adoption4ec7d2a
lines 435–437why, one step back435 """Runs the application on a local development server. If the436 :attr:`debug` flag is set the server will automatically reload437 for code changes and show a debugger in case an exception happened.Heavily improved documentationArmin Ronacherbefore adoption05f36c7
lines 438–444why, one step back438439 :param host: the hostname to listen on. set this to ``'0.0.0.0'``440 to have the server available externally as well.441 :param port: the port of the webserver442 :param options: the options to be forwarded to the underlying443 Werkzeug server. See :func:`werkzeug.run_simple`444 for more information.Started working on documentation.Armin Ronacherbefore adoption4ec7d2a
line 445why, one step back445 """Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 446–452446 from werkzeug import run_simple447 if 'debug' in options:448 self.debug = options.pop('debug')449 options.setdefault('use_reloader', self.debug)450 options.setdefault('use_debugger', self.debug)451 return run_simple(host, port, self, **options)452Added tests for minitwit. Testing with Flask is awesomeArmin Ronacherbefore adoptionf2dc38c
line 453why, one step back453 def test_client(self):Added testing documentationArmin Ronacherbefore adoption03148db
lines 454–456why, one step back454 """Creates a test client for this application. For information455 about unit testing head over to :ref:`testing`.456 """Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 457–460457 from werkzeug import Client458 return Client(self, self.response_class, use_cookies=True)459460 def open_resource(self, resource):Started working on documentation.Armin Ronacherbefore adoption4ec7d2a
lines 461–477why, one step back461 """Opens a resource from the application's resource folder. To see462 how this works, consider the following folder structure::463464 /myapplication.py465 /schemal.sql466 /static467 /style.css468 /template469 /layout.html470 /index.html471472 If you want to open the `schema.sql` file you would do the473 following::474475 with app.open_resource('schema.sql') as f:476 contents = f.read()477 do_something_with(contents)Heavily improved documentationArmin Ronacherbefore adoption05f36c7
lines 478–480why, one step back478479 :param resource: the name of the resource. To access resources within480 subfolders use forward slashes as separator.Started working on documentation.Armin Ronacherbefore adoption4ec7d2a
line 481why, one step back481 """Flask now runs without the presence of pkg_resources as well.Armin Ronacherbefore adoption2d9bb69
lines 482–483why, one step back482 if pkg_resources is None:483 return open(os.path.join(self.root_path, resource), 'rb')Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 484–486484 return pkg_resources.resource_stream(self.package_name, resource)485486 def open_session(self, request):Started working on documentation.Armin Ronacherbefore adoption4ec7d2a
lines 487–489why, one step back487 """Creates or opens a new session. Default implementation stores all488 session data in a signed cookie. This requires that the489 :attr:`secret_key` is set.Heavily improved documentationArmin Ronacherbefore adoption05f36c7
lines 490–491why, one step back490491 :param request: an instance of :attr:`request_class`.Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 492–498492 """493 key = self.secret_key494 if key is not None:495 return SecureCookie.load_cookie(request, self.session_cookie_name,496 secret_key=key)497498 def save_session(self, session, response):Started working on documentation.Armin Ronacherbefore adoption4ec7d2a
lines 499–500why, one step back499 """Saves the session if it needs updates. For the default500 implementation, check :meth:`open_session`.Heavily improved documentationArmin Ronacherbefore adoption05f36c7
lines 501–504why, one step back501502 :param session: the session to be saved (a503 :class:`~werkzeug.contrib.securecookie.SecureCookie`504 object)Fixed a documentation error and implemented template context processors.Armin Ronacherbefore adoptiona01e8b4
line 505why, one step back505 :param response: an instance of :attr:`response_class`Started working on documentation.Armin Ronacherbefore adoption4ec7d2a
line 506why, one step back506 """Session falls back to a dummy object now if secret_key is missing.Armin Ronacherbefore adoption5310fc3
line 507why, one step back507 session.save_cookie(response, self.session_cookie_name)508Make it easier to associate a rule, endpoint and view_functionunknownbefore adoption3088a93
line 509why, one step back509 def add_url_rule(self, rule, endpoint, view_func=None, **options):Documented non-decorator uses of registation.Armin Ronacherbefore adoption7d6b8e9
line 510why, one step back510 """Connects a URL rule. Works exactly like the :meth:`route`Fix typos and remove unused import.florentxbefore adoption3c821a0
line 511why, one step back511 decorator. If a view_func is provided it will be registered with theSome more documentation updates.Armin Ronacherbefore adoption715f64d
line 512why, one step back512 endpoint.Documented non-decorator uses of registation.Armin Ronacherbefore adoption7d6b8e9
lines 513–519why, one step back513514 Basically this example::515516 @app.route('/')517 def index():518 pass519Added docs, fixed some bugs I introduced last commitArmin Ronacherbefore adoption3d719f3
line 520why, one step back520 Is equivalent to the following::Documented non-decorator uses of registation.Armin Ronacherbefore adoption7d6b8e9
lines 521–523why, one step back521522 def index():523 passMake it easier to associate a rule, endpoint and view_functionunknownbefore adoption3088a93
line 524why, one step back524 app.add_url_rule('/', 'index', index)Some more documentation updates.Armin Ronacherbefore adoption715f64d
lines 525–528why, one step back525526 If the view_func is not provided you will need to connect the endpoint527 to a view function like so::528Documented non-decorator uses of registation.Armin Ronacherbefore adoption7d6b8e9
line 529why, one step back529 app.view_functions['index'] = indexHeavily improved documentationArmin Ronacherbefore adoption05f36c7
line 530why, one step back530Some more documentation updates.Armin Ronacherbefore adoption715f64d
lines 531–533why, one step back531 .. versionchanged:: 0.2532 `view_func` parameter added533Heavily improved documentationArmin Ronacherbefore adoption05f36c7
lines 534–537why, one step back534 :param rule: the URL rule as string535 :param endpoint: the endpoint for the registered URL rule. Flask536 itself assumes the name of the view function as537 endpointFix typos and remove unused import.florentxbefore adoption3c821a0
line 538why, one step back538 :param view_func: the function to call when serving a request to theSome more documentation updates.Armin Ronacherbefore adoption715f64d
line 539why, one step back539 provided endpointHeavily improved documentationArmin Ronacherbefore adoption05f36c7
lines 540–541why, one step back540 :param options: the options to be forwarded to the underlying541 :class:`~werkzeug.routing.Rule` objectDocumented non-decorator uses of registation.Armin Ronacherbefore adoption7d6b8e9
line 542why, one step back542 """Added docs, fixed some bugs I introduced last commitArmin Ronacherbefore adoption3d719f3
line 543why, one step back543 options['endpoint'] = endpointDocumented non-decorator uses of registation.Armin Ronacherbefore adoption7d6b8e9
lines 544–545why, one step back544 options.setdefault('methods', ('GET',))545 self.url_map.add(Rule(rule, **options))Make it easier to associate a rule, endpoint and view_functionunknownbefore adoption3088a93
lines 546–547why, one step back546 if view_func is not None:547 self.view_functions[endpoint] = view_funcDocumented non-decorator uses of registation.Armin Ronacherbefore adoption7d6b8e9
line 548why, one step back548Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 549–555549 def route(self, rule, **options):550 """A decorator that is used to register a view function for a551 given URL rule. Example::552553 @app.route('/')554 def index():555 return 'Hello World'Started working on documentation.Armin Ronacherbefore adoption4ec7d2a
lines 556–558why, one step back556557 Variables parts in the route can be specified with angular558 brackets (``/user/<username>``). By default a variable partAdded testing documentationArmin Ronacherbefore adoption03148db
line 559why, one step back559 in the URL accepts any string without a slash however a differentStarted working on documentation.Armin Ronacherbefore adoption4ec7d2a
lines 560–586why, one step back560 converter can be specified as well by using ``<converter:name>``.561562 Variable parts are passed to the view function as keyword563 arguments.564565 The following converters are possible:566567 =========== ===========================================568 `int` accepts integers569 `float` like `int` but for floating point values570 `path` like the default but also accepts slashes571 =========== ===========================================572573 Here some examples::574575 @app.route('/')576 def index():577 pass578579 @app.route('/<username>')580 def show_user(username):581 pass582583 @app.route('/post/<int:post_id>')584 def show_post(post_id):585 pass586Updated documentation. Starting to look pretty goodArmin Ronacherbefore adoption4aa7621
lines 587–599why, one step back587 An important detail to keep in mind is how Flask deals with trailing588 slashes. The idea is to keep each URL unique so the following rules589 apply:590591 1. If a rule ends with a slash and is requested without a slash592 by the user, the user is automatically redirected to the same593 page with a trailing slash attached.594 2. If a rule does not end with a trailing slash and the user request595 the page with a trailing slash, a 404 not found is raised.596597 This is consistent with how web servers deal with static files. This598 also makes it possible to use relative link targets safely.599Started working on documentation.Armin Ronacherbefore adoption4ec7d2a
lines 600–602why, one step back600 The :meth:`route` decorator accepts a couple of other arguments601 as well:602Heavily improved documentationArmin Ronacherbefore adoption05f36c7
line 603why, one step back603 :param rule: the URL rule as stringStarted working on documentation.Armin Ronacherbefore adoption4ec7d2a
line 604why, one step back604 :param methods: a list of methods this rule should be limitedUpdated documentation. Starting to look pretty goodArmin Ronacherbefore adoption4aa7621
lines 605–606why, one step back605 to (``GET``, ``POST`` etc.). By default a rule606 just listens for ``GET`` (and implicitly ``HEAD``).Started working on documentation.Armin Ronacherbefore adoption4ec7d2a
lines 607–610why, one step back607 :param subdomain: specifies the rule for the subdoain in case608 subdomain matching is in use.609 :param strict_slashes: can be used to disable the strict slashes610 setting for this rule. See above.Heavily improved documentationArmin Ronacherbefore adoption05f36c7
lines 611–612why, one step back611 :param options: other options to be forwarded to the underlying612 :class:`~werkzeug.routing.Rule` object.Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 613–614613 """614 def decorator(f):Refactored the @route decorator to use the new add_url_rule method.cgrindsbefore adoption5acc491
line 615why, one step back615 self.add_url_rule(rule, f.__name__, f, **options)Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 616–625616 return f617 return decorator618619 def errorhandler(self, code):620 """A decorator that is used to register a function give a given621 error code. Example::622623 @app.errorhandler(404)624 def page_not_found():625 return 'This page does not exist', 404Documented non-decorator uses of registation.Armin Ronacherbefore adoption7d6b8e9
lines 626–633why, one step back626627 You can also register a function as error handler without using628 the :meth:`errorhandler` decorator. The following example is629 equivalent to the one above::630631 def page_not_found():632 return 'This page does not exist', 404633 app.error_handlers[404] = page_not_foundHeavily improved documentationArmin Ronacherbefore adoption05f36c7
lines 634–635why, one step back634635 :param code: the code as integer for the handlerInitial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 636–641636 """637 def decorator(f):638 self.error_handlers[code] = f639 return f640 return decorator641request_init -> before_request and request_shutdown -> after_requestArmin Ronacherbefore adoptionfb2d2e4
line 642why, one step back642 def before_request(self, f):643 """Registers a function to run before each request."""request_init -> before_request and request_shutdown -> after_requestArmin Ronacherbefore adoptionfb2d2e4
line 644why, one step back644 self.before_request_funcs.append(f)Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 645–646645 return f646request_init -> before_request and request_shutdown -> after_requestArmin Ronacherbefore adoptionfb2d2e4
line 647why, one step back647 def after_request(self, f):648 """Register a function to be run after each request."""request_init -> before_request and request_shutdown -> after_requestArmin Ronacherbefore adoptionfb2d2e4
line 649why, one step back649 self.after_request_funcs.append(f)Fixed a documentation error and implemented template context processors.Armin Ronacherbefore adoptiona01e8b4
lines 650–654why, one step back650 return f651652 def context_processor(self, f):653 """Registers a template context processor function."""654 self.template_context_processors.append(f)Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 655–688655 return f656657 def match_request(self):658 """Matches the current request against the URL map and also659 stores the endpoint and view arguments on the request object660 is successful, otherwise the exception is stored.661 """662 rv = _request_ctx_stack.top.url_adapter.match()663 request.endpoint, request.view_args = rv664 return rv665666 def dispatch_request(self):667 """Does the request dispatching. Matches the URL and returns the668 return value of the view or error handler. This does not have to669 be a response object. In order to convert the return value to a670 proper response object, call :func:`make_response`.671 """672 try:673 endpoint, values = self.match_request()674 return self.view_functions[endpoint](**values)675 except HTTPException, e:676 handler = self.error_handlers.get(e.code)677 if handler is None:678 return e679 return handler(e)680 except Exception, e:681 handler = self.error_handlers.get(500)682 if self.debug or handler is None:683 raise684 return handler(e)685686 def make_response(self, rv):687 """Converts the return value from a view function to a real688 response object that is an instance of :attr:`response_class`.Heavily improved documentationArmin Ronacherbefore adoption05f36c7
lines 689–704why, one step back689690 The following types are allowd for `rv`:691692 ======================= ===========================================693 :attr:`response_class` the object is returned unchanged694 :class:`str` a response object is created with the695 string as body696 :class:`unicode` a response object is created with the697 string encoded to utf-8 as body698 :class:`tuple` the response object is created with the699 contents of the tuple as arguments700 a WSGI function the function is called as WSGI application701 and buffered as response object702 ======================= ===========================================703704 :param rv: the return value from the view functionInitial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 705–715705 """706 if isinstance(rv, self.response_class):707 return rv708 if isinstance(rv, basestring):709 return self.response_class(rv)710 if isinstance(rv, tuple):711 return self.response_class(*rv)712 return self.response_class.force_type(rv, request.environ)713714 def preprocess_request(self):715 """Called before the actual request dispatching and willrequest_init -> before_request and request_shutdown -> after_requestArmin Ronacherbefore adoptionfb2d2e4
line 716why, one step back716 call every as :meth:`before_request` decorated function.Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 717–720717 If any of these function returns a value it's handled as718 if it was the return value from the view and further719 request handling is stopped.720 """request_init -> before_request and request_shutdown -> after_requestArmin Ronacherbefore adoptionfb2d2e4
line 721why, one step back721 for func in self.before_request_funcs:Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 722–727722 rv = func()723 if rv is not None:724 return rv725726 def process_response(self, response):727 """Can be overridden in order to modify the response objectrequest_init -> before_request and request_shutdown -> after_requestArmin Ronacherbefore adoptionfb2d2e4
lines 728–729why, one step back728 before it's sent to the WSGI server. By default this will729 call all the :meth:`after_request` decorated functions.Heavily improved documentationArmin Ronacherbefore adoption05f36c7
lines 730–733why, one step back730731 :param response: a :attr:`response_class` object.732 :return: a new response object or the same, has to be an733 instance of :attr:`response_class`.Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 734–735734 """735 session = _request_ctx_stack.top.sessionSession falls back to a dummy object now if secret_key is missing.Armin Ronacherbefore adoption5310fc3
line 736why, one step back736 if not isinstance(session, _NullSession):737 self.save_session(session, response)request_init -> before_request and request_shutdown -> after_requestArmin Ronacherbefore adoptionfb2d2e4
line 738why, one step back738 for handler in self.after_request_funcs:Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 739–743739 response = handler(response)740 return response741742 def wsgi_app(self, environ, start_response):743 """The actual WSGI application. This is not implemented inAdded support for macro pulling and documented certain design decisions.Armin Ronacherbefore adoption190059c
lines 744–745why, one step back744 `__call__` so that middlewares can be applied without losing a745 reference to the class. So instead of doing this::746Added support for macro pulling and documented certain design decisions.Armin Ronacherbefore adoption190059c
lines 747–750why, one step back747 app = MyMiddleware(app)748749 It's a better idea to do this instead::750751 app.wsgi_app = MyMiddleware(app.wsgi_app)Added support for macro pulling and documented certain design decisions.Armin Ronacherbefore adoption190059c
lines 752–754why, one step back752753 Then you still have the original application object around and754 can continue to call methods on it.Heavily improved documentationArmin Ronacherbefore adoption05f36c7
lines 755–759why, one step back755756 :param environ: a WSGI environment757 :param start_response: a callable accepting a status code,758 a list of headers and an optional759 exception context to start the response760 """Improved documentation, added a contextmanager for request bindingArmin Ronacherbefore adoption3b36bef
line 761why, one step back761 with self.request_context(environ):Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 762–767762 rv = self.preprocess_request()763 if rv is None:764 rv = self.dispatch_request()765 response = self.make_response(rv)766 response = self.process_response(response)767 return response(environ, start_response)Improved documentation, added a contextmanager for request bindingArmin Ronacherbefore adoption3b36bef
lines 768–778why, one step back768769 def request_context(self, environ):770 """Creates a request context from the given environment and binds771 it to the current context. This must be used in combination with772 the `with` statement because the request is only bound to the773 current context for the duration of the `with` block.774775 Example usage::776777 with app.request_context(environ):778 do_something_with(request)Heavily improved documentationArmin Ronacherbefore adoption05f36c7
lines 779–780why, one step back779780 :params environ: a WSGI environmentImproved documentation, added a contextmanager for request bindingArmin Ronacherbefore adoption3b36bef
line 781why, one step back781 """Preserve the request context in debug mode.Armin Ronacherbefore adoption7b50150
line 782why, one step back782 return _RequestContext(self, environ)Improved documentation, added a contextmanager for request bindingArmin Ronacherbefore adoption3b36bef
lines 783–785why, one step back783784 def test_request_context(self, *args, **kwargs):785 """Creates a WSGI environment from the given values (seeHeavily improved documentationArmin Ronacherbefore adoption05f36c7
lines 786–787why, one step back786 :func:`werkzeug.create_environ` for more information, this787 function accepts the same arguments).Improved documentation, added a contextmanager for request bindingArmin Ronacherbefore adoption3b36bef
lines 788–789why, one step back788 """789 return self.request_context(create_environ(*args, **kwargs))Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 790–791790791 def __call__(self, environ, start_response):Fix typos and remove unused import.florentxbefore adoption3c821a0
line 792why, one step back792 """Shortcut for :attr:`wsgi_app`."""Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0
lines 793–801793 return self.wsgi_app(environ, start_response)794795796# context locals797_request_ctx_stack = LocalStack()798current_app = LocalProxy(lambda: _request_ctx_stack.top.app)799request = LocalProxy(lambda: _request_ctx_stack.top.request)800session = LocalProxy(lambda: _request_ctx_stack.top.session)801g = LocalProxy(lambda: _request_ctx_stack.top.g)