Skip to content
Myr

flask.py

This file

Path

flask.py

467 lines · 16.9 KiB · Python

Last changed by

Started working on documentation.Armin Ronacherbefore adoption4ec7d2a

History of this file

Take it

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 1–127
1# -*- 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"""12import os13import sys14import pkg_resources15from threading import local16from jinja2 import Environment, PackageLoader17from werkzeug import Request, Response, LocalStack, LocalProxy18from werkzeug.routing import Map, Rule19from werkzeug.exceptions import HTTPException, InternalServerError20from werkzeug.contrib.securecookie import SecureCookie2122# 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 pass3031# utilities we import from Werkzeug and Jinja2 that are unused32# 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_hash35from jinja2 import Markup, escape363738class FlaskRequest(Request):39 """The request object used by default in flask. Remembers the40 matched endpoint and view arguments.41 """4243 def __init__(self, environ):44 Request.__init__(self, environ)45 self.endpoint = None46 self.view_args = None474849class FlaskResponse(Response):50 """The response object that is used by default in flask. Works like the51 response object from Werkzeug but is set to have a HTML mimetype by52 default.53 """54 default_mimetype = 'text/html'555657class _RequestGlobals(object):58 pass596061class _RequestContext(object):62 """The request context contains all request relevant information. It is63 created at the beginning of the request and pushed to the64 `_request_ctx_stack` and removed at the end of it. It will create the65 URL adapter and request object for the WSGI environment provided.66 """6768 def __init__(self, app, environ):69 self.app = app70 self.url_adapter = app.url_map.bind_to_environ(environ)71 self.request = app.request_class(environ)72 self.session = app.open_session(self.request)73 self.g = _RequestGlobals()74 self.flashes = None757677def url_for(endpoint, **values):78 """Generates a URL to the given endpoint with the method provided.7980 :param endpoint: the endpoint of the URL (name of the function)81 :param values: the variable arguments of the URL rule82 """83 return _request_ctx_stack.top.url_adapter.build(endpoint, values)848586def jsonified(**values):87 """Returns a json response"""88 return current_app.response_class(dump_json(values),89 mimetype='application/json')909192def flash(message):93 """Flashes a message to the next request. In order to remove the94 flashed message from the session and to display it to the user,95 the template has to call :func:`get_flashed_messages`.96 """97 session['_flashes'] = (session.get('_flashes', [])) + [message]9899100def get_flashed_messages():101 """Pulls all flashed messages from the session and returns them.102 Further calls in the same request to the function will return103 the same messages.104 """105 flashes = _request_ctx_stack.top.flashes106 if flashes is None:107 _request_ctx_stack.top.flashes = flashes = \108 session.pop('_flashes', [])109 return flashes110111112def render_template(template_name, **context):113 """Renders a template from the template folder with the given114 context.115 """116 return current_app.jinja_env.get_template(template_name).render(context)117118119def render_template_string(source, **context):120 """Renders a template from the given template source string121 with the given context.122 """123 return current_app.jinja_env.from_string(source).render(context)124125126class Flask(object):127 """The flask object implements a WSGI application and acts as the central

Started working on documentation.Armin Ronacherbefore adoption4ec7d2a

lines 128–143why, one step back
128 object. It is passed the name of the module or package of the
129 application. Once it is created it will act as a central registry for130 the view functions, the URL rules, template configuration and much more.131132 The name of the package is used to resolve resources from inside the133 package or the folder the module is contained in depending on if the134 package parameter resolves to an actual python package (a folder with135 an `__init__.py` file inside) or a standard module (just a `.py` file).136137 For more information about resource loading, see :func:`open_resource`.138139 Usually you create a :class:`Flask` instance in your main module or140 in the `__init__.py` file of your package like this::141142 from flask import Flask143 app = Flask(__name__)

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 144–171
144 """
145146 #: the class that is used for request objects147 request_class = FlaskRequest148149 #: the class that is used for response objects150 response_class = FlaskResponse151152 #: path for the static files. If you don't want to use static files153 #: you can set this value to `None` in which case no URL rule is added154 #: and the development server will no longer serve any static files.155 static_path = '/static'156157 #: if a secret key is set, cryptographic components can use this to158 #: sign cookies and other things. Set this to a complex random value159 #: when you want to use the secure cookie for instance.160 secret_key = None161162 #: The secure cookie uses this for the name of the session cookie163 session_cookie_name = 'session'164165 #: options that are passed directly to the Jinja2 environment166 jinja_options = dict(167 autoescape=True,168 extensions=['jinja2.ext.autoescape', 'jinja2.ext.with_']169 )170171 def __init__(self, package_name):

Started working on documentation.Armin Ronacherbefore adoption4ec7d2a

lines 172–176why, one step back
172 #: the debug flag. Set this to `True` to enable debugging of
173 #: the application. In debug mode the debugger will kick in174 #: when an unhandled exception ocurrs and the integrated server175 #: will automatically reload the application if changes in the176 #: code are detected.

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

line 177
177 self.debug = False

Started working on documentation.Armin Ronacherbefore adoption4ec7d2a

lines 178–180why, one step back
178
179 #: the name of the package or module. Do not change this once180 #: it was set by the constructor.

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

line 181
181 self.package_name = package_name

Started working on documentation.Armin Ronacherbefore adoption4ec7d2a

lines 182–186why, one step back
182
183 #: a dictionary of all view functions registered. The keys will184 #: be function names which are also used to generate URLs and185 #: the values are the function objects themselves.186 #: to register a view function, use the :meth:`route` decorator.

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

line 187
187 self.view_functions = {}

Started working on documentation.Armin Ronacherbefore adoption4ec7d2a

lines 188–193why, one step back
188
189 #: a dictionary of all registered error handlers. The key is190 #: be the error code as integer, the value the function that191 #: should handle that error.192 #: To register a error handler, use the :meth:`errorhandler`193 #: decorator.

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

line 194
194 self.error_handlers = {}

Started working on documentation.Armin Ronacherbefore adoption4ec7d2a

lines 195–201why, one step back
195
196 #: a list of functions that should be called at the beginning197 #: of the request before request dispatching kicks in. This198 #: can for example be used to open database connections or199 #: getting hold of the currently logged in user.200 #: To register a function here, use the :meth:`request_init`201 #: decorator.

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

line 202
202 self.request_init_funcs = []

Started working on documentation.Armin Ronacherbefore adoption4ec7d2a

lines 203–208why, one step back
203
204 #: a list of functions that are called at the end of the205 #: request. Tha function is passed the current response206 #: object and modify it in place or replace it.207 #: To register a function here use the :meth:`request_shtdown`208 #: decorator.

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 209–215
209 self.request_shutdown_funcs = []
210 self.url_map = Map()211212 if self.static_path is not None:213 self.url_map.add(Rule(self.static_path + '/<filename>',214 build_only=True, endpoint='static'))215

Started working on documentation.Armin Ronacherbefore adoption4ec7d2a

lines 216–218why, one step back
216 #: the Jinja2 environment. It is created from the
217 #: :attr:`jinja_options` and the loader that is returned218 #: by the :meth:`create_jinja_loader` function.

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 219–237
219 self.jinja_env = Environment(loader=self.create_jinja_loader(),
220 **self.jinja_options)221 self.jinja_env.globals.update(222 url_for=url_for,223 request=request,224 session=session,225 g=g,226 get_flashed_messages=get_flashed_messages227 )228229 def create_jinja_loader(self):230 """Creates the Jinja loader. By default just a package loader for231 the configured package is returned that looks up templates in the232 `templates` folder. To add other loaders it's possible to233 override this method.234 """235 return PackageLoader(self.package_name)236237 def run(self, host='localhost', port=5000, **options):

Started working on documentation.Armin Ronacherbefore adoption4ec7d2a

lines 238–241why, one step back
238 """Runs the application on a local development server. If the
239 :attr:`debug` flag is set the server will automatically reload240 for code changes and show a debugger in case an exception happened.241 """

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 242–259
242 from werkzeug import run_simple
243 if 'debug' in options:244 self.debug = options.pop('debug')245 if self.static_path is not None:246 options['static_files'] = {247 self.static_path: (self.package_name, 'static')248 }249 options.setdefault('use_reloader', self.debug)250 options.setdefault('use_debugger', self.debug)251 return run_simple(host, port, self, **options)252253 @cached_property254 def test(self):255 """A test client for this application"""256 from werkzeug import Client257 return Client(self, self.response_class, use_cookies=True)258259 def open_resource(self, resource):

Started working on documentation.Armin Ronacherbefore adoption4ec7d2a

lines 260–277why, one step back
260 """Opens a resource from the application's resource folder. To see
261 how this works, consider the following folder structure::262263 /myapplication.py264 /schemal.sql265 /static266 /style.css267 /template268 /layout.html269 /index.html270271 If you want to open the `schema.sql` file you would do the272 following::273274 with app.open_resource('schema.sql') as f:275 contents = f.read()276 do_something_with(contents)277 """

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 278–280
278 return pkg_resources.resource_stream(self.package_name, resource)
279280 def open_session(self, request):

Started working on documentation.Armin Ronacherbefore adoption4ec7d2a

lines 281–283why, one step back
281 """Creates or opens a new session. Default implementation stores all
282 session data in a signed cookie. This requires that the283 :attr:`secret_key` is set.

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 284–290
284 """
285 key = self.secret_key286 if key is not None:287 return SecureCookie.load_cookie(request, self.session_cookie_name,288 secret_key=key)289290 def save_session(self, session, response):

Started working on documentation.Armin Ronacherbefore adoption4ec7d2a

lines 291–293why, one step back
291 """Saves the session if it needs updates. For the default
292 implementation, check :meth:`open_session`.293 """

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 294–303
294 if session is not None:
295 session.save_cookie(response, self.session_cookie_name)296297 def route(self, rule, **options):298 """A decorator that is used to register a view function for a299 given URL rule. Example::300301 @app.route('/')302 def index():303 return 'Hello World'

Started working on documentation.Armin Ronacherbefore adoption4ec7d2a

lines 304–343why, one step back
304
305 Variables parts in the route can be specified with angular306 brackets (``/user/<username>``). By default a variable part307 in the URL accepts any string without a slash however a differnt308 converter can be specified as well by using ``<converter:name>``.309310 Variable parts are passed to the view function as keyword311 arguments.312313 The following converters are possible:314315 =========== ===========================================316 `int` accepts integers317 `float` like `int` but for floating point values318 `path` like the default but also accepts slashes319 =========== ===========================================320321 Here some examples::322323 @app.route('/')324 def index():325 pass326327 @app.route('/<username>')328 def show_user(username):329 pass330331 @app.route('/post/<int:post_id>')332 def show_post(post_id):333 pass334335 The :meth:`route` decorator accepts a couple of other arguments336 as well:337338 :param methods: a list of methods this rule should be limited339 to (``GET``, ``POST`` etc.)340 :param subdomain: specifies the rule for the subdoain in case341 subdomain matching is in use.342 :param strict_slashes: can be used to disable the strict slashes343 setting for this rule. See above.

Initial checkin of stuff that exists so far.Armin Ronacherbefore adoption33850c0

lines 344–467
344 """
345 def decorator(f):346 if 'endpoint' not in options:347 options['endpoint'] = f.__name__348 self.url_map.add(Rule(rule, **options))349 self.view_functions[options['endpoint']] = f350 return f351 return decorator352353 def errorhandler(self, code):354 """A decorator that is used to register a function give a given355 error code. Example::356357 @app.errorhandler(404)358 def page_not_found():359 return 'This page does not exist', 404360 """361 def decorator(f):362 self.error_handlers[code] = f363 return f364 return decorator365366 def request_init(self, f):367 """Registers a function to run before each request."""368 self.request_init_funcs.append(f)369 return f370371 def request_shutdown(self, f):372 """Register a function to be run after each request."""373 self.request_shutdown_funcs.append(f)374 return f375376 def match_request(self):377 """Matches the current request against the URL map and also378 stores the endpoint and view arguments on the request object379 is successful, otherwise the exception is stored.380 """381 rv = _request_ctx_stack.top.url_adapter.match()382 request.endpoint, request.view_args = rv383 return rv384385 def dispatch_request(self):386 """Does the request dispatching. Matches the URL and returns the387 return value of the view or error handler. This does not have to388 be a response object. In order to convert the return value to a389 proper response object, call :func:`make_response`.390 """391 try:392 endpoint, values = self.match_request()393 return self.view_functions[endpoint](**values)394 except HTTPException, e:395 handler = self.error_handlers.get(e.code)396 if handler is None:397 return e398 return handler(e)399 except Exception, e:400 handler = self.error_handlers.get(500)401 if self.debug or handler is None:402 raise403 return handler(e)404405 def make_response(self, rv):406 """Converts the return value from a view function to a real407 response object that is an instance of :attr:`response_class`.408 """409 if isinstance(rv, self.response_class):410 return rv411 if isinstance(rv, basestring):412 return self.response_class(rv)413 if isinstance(rv, tuple):414 return self.response_class(*rv)415 return self.response_class.force_type(rv, request.environ)416417 def preprocess_request(self):418 """Called before the actual request dispatching and will419 call every as :func:`request_init` decorated function.420 If any of these function returns a value it's handled as421 if it was the return value from the view and further422 request handling is stopped.423 """424 for func in self.request_init_funcs:425 rv = func()426 if rv is not None:427 return rv428429 def process_response(self, response):430 """Can be overridden in order to modify the response object431 before it's sent to the WSGI server.432 """433 session = _request_ctx_stack.top.session434 if session is not None:435 self.save_session(session, response)436 for handler in self.request_shutdown_funcs:437 response = handler(response)438 return response439440 def wsgi_app(self, environ, start_response):441 """The actual WSGI application. This is not implemented in442 `__call__` so that middlewares can be applied:443444 app.wsgi_app = MyMiddleware(app.wsgi_app)445 """446 _request_ctx_stack.push(_RequestContext(self, environ))447 try:448 rv = self.preprocess_request()449 if rv is None:450 rv = self.dispatch_request()451 response = self.make_response(rv)452 response = self.process_response(response)453 return response(environ, start_response)454 finally:455 _request_ctx_stack.pop()456457 def __call__(self, environ, start_response):458 """Shortcut for :attr:`wsgi_app`"""459 return self.wsgi_app(environ, start_response)460461462# context locals463_request_ctx_stack = LocalStack()464current_app = LocalProxy(lambda: _request_ctx_stack.top.app)465request = LocalProxy(lambda: _request_ctx_stack.top.request)466session = LocalProxy(lambda: _request_ctx_stack.top.session)467g = LocalProxy(lambda: _request_ctx_stack.top.g)