Started working on documentation.

So far just the stable parts :)
This commit is contained in:
Armin Ronacher 2010-04-06 16:02:14 +02:00
parent b15ad39427
commit 4ec7d2a0d8
9 changed files with 641 additions and 9 deletions

127
flask.py
View file

@ -125,9 +125,22 @@ def render_template_string(source, **context):
class Flask(object):
"""The flask object implements a WSGI application and acts as the central
object. It is passed the name of the module or package of the application
and optionally a configuration. When it's created it sets up the
template engine and provides ways to register view functions.
object. It is passed the name of the module or package of the
application. Once it is created it will act as a central registry for
the view functions, the URL rules, template configuration and much more.
The name of the package is used to resolve resources from inside the
package or the folder the module is contained in depending on if the
package parameter resolves to an actual python package (a folder with
an `__init__.py` file inside) or a standard module (just a `.py` file).
For more information about resource loading, see :func:`open_resource`.
Usually you create a :class:`Flask` instance in your main module or
in the `__init__.py` file of your package like this::
from flask import Flask
app = Flask(__name__)
"""
#: the class that is used for request objects
@ -156,11 +169,43 @@ class Flask(object):
)
def __init__(self, package_name):
#: the debug flag. Set this to `True` to enable debugging of
#: the application. In debug mode the debugger will kick in
#: when an unhandled exception ocurrs and the integrated server
#: will automatically reload the application if changes in the
#: code are detected.
self.debug = False
#: the name of the package or module. Do not change this once
#: it was set by the constructor.
self.package_name = package_name
#: a dictionary of all view functions registered. The keys will
#: be function names which are also used to generate URLs and
#: the values are the function objects themselves.
#: to register a view function, use the :meth:`route` decorator.
self.view_functions = {}
#: a dictionary of all registered error handlers. The key is
#: be the error code as integer, the value the function that
#: should handle that error.
#: To register a error handler, use the :meth:`errorhandler`
#: decorator.
self.error_handlers = {}
#: a list of functions that should be called at the beginning
#: of the request before request dispatching kicks in. This
#: can for example be used to open database connections or
#: getting hold of the currently logged in user.
#: To register a function here, use the :meth:`request_init`
#: decorator.
self.request_init_funcs = []
#: a list of functions that are called at the end of the
#: request. Tha function is passed the current response
#: object and modify it in place or replace it.
#: To register a function here use the :meth:`request_shtdown`
#: decorator.
self.request_shutdown_funcs = []
self.url_map = Map()
@ -168,6 +213,9 @@ class Flask(object):
self.url_map.add(Rule(self.static_path + '/<filename>',
build_only=True, endpoint='static'))
#: the Jinja2 environment. It is created from the
#: :attr:`jinja_options` and the loader that is returned
#: by the :meth:`create_jinja_loader` function.
self.jinja_env = Environment(loader=self.create_jinja_loader(),
**self.jinja_options)
self.jinja_env.globals.update(
@ -187,7 +235,10 @@ class Flask(object):
return PackageLoader(self.package_name)
def run(self, host='localhost', port=5000, **options):
"""Runs the application on a local development server"""
"""Runs the application on a local development server. If the
:attr:`debug` flag is set the server will automatically reload
for code changes and show a debugger in case an exception happened.
"""
from werkzeug import run_simple
if 'debug' in options:
self.debug = options.pop('debug')
@ -206,12 +257,30 @@ class Flask(object):
return Client(self, self.response_class, use_cookies=True)
def open_resource(self, resource):
"""Opens a resource from the application's resource folder"""
"""Opens a resource from the application's resource folder. To see
how this works, consider the following folder structure::
/myapplication.py
/schemal.sql
/static
/style.css
/template
/layout.html
/index.html
If you want to open the `schema.sql` file you would do the
following::
with app.open_resource('schema.sql') as f:
contents = f.read()
do_something_with(contents)
"""
return pkg_resources.resource_stream(self.package_name, resource)
def open_session(self, request):
"""Creates or opens a new session. Default implementation requires
that `securecookie.secret_key` is set.
"""Creates or opens a new session. Default implementation stores all
session data in a signed cookie. This requires that the
:attr:`secret_key` is set.
"""
key = self.secret_key
if key is not None:
@ -219,7 +288,9 @@ class Flask(object):
secret_key=key)
def save_session(self, session, response):
"""Saves the session if it needs updates."""
"""Saves the session if it needs updates. For the default
implementation, check :meth:`open_session`.
"""
if session is not None:
session.save_cookie(response, self.session_cookie_name)
@ -230,6 +301,46 @@ class Flask(object):
@app.route('/')
def index():
return 'Hello World'
Variables parts in the route can be specified with angular
brackets (``/user/<username>``). By default a variable part
in the URL accepts any string without a slash however a differnt
converter can be specified as well by using ``<converter:name>``.
Variable parts are passed to the view function as keyword
arguments.
The following converters are possible:
=========== ===========================================
`int` accepts integers
`float` like `int` but for floating point values
`path` like the default but also accepts slashes
=========== ===========================================
Here some examples::
@app.route('/')
def index():
pass
@app.route('/<username>')
def show_user(username):
pass
@app.route('/post/<int:post_id>')
def show_post(post_id):
pass
The :meth:`route` decorator accepts a couple of other arguments
as well:
:param methods: a list of methods this rule should be limited
to (``GET``, ``POST`` etc.)
:param subdomain: specifies the rule for the subdoain in case
subdomain matching is in use.
:param strict_slashes: can be used to disable the strict slashes
setting for this rule. See above.
"""
def decorator(f):
if 'endpoint' not in options: