Skip to content
Myr

And finished documentation for most parts.

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 4edec48 · Browse files · 5 files+199 added−4 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

5 files+199 added−4 removed

  • other:+199 added−4 removed

5 files+199 added−4 removed

modified:docs/api.rst+2 added
1.. _api:23API4===56.. module:: flask
181 unmodified lines
modified:docs/index.rst+7 added-3 removed
1Welcome to Flask2================34Welcome to Flask's documentation.4Welcome to Flask's documentation. This documentation is devided into5different parts. I would suggest to get started with the6:ref:`installation` and then heading over to the :ref:`quickstart`. If7you want to dive into all the internal parts of Flask, check out the8:ref:`api` documentation. Common patterns are described in the9:ref:`patterns` section.106Contents:711.. toctree::12 :maxdepth: 21314 installation15 quickstart16 patterns17 api
added:docs/patterns.rst+166 added
1.. _patterns:23Patterns in Flask4=================56Certain things are common enough that the changes are high you will find7them in most web applications. For example quite a lot of applications8are using relational databases and user authentication. In that case,9changes are they will open a database connection at the beginning of the10request and get the information of the currently logged in user. At the11end of the request, the database connection is closed again.1213In Flask you can implement such things with the14:meth:`~flask.Flask.request_init` and15:meth:`~flask.Flask.request_shutdown` decorators in combination with the16special :class:`~flask.g` object.171819Using SQLite 3 with Flask20-------------------------2122So here a simple example how you can use SQLite 3 with Flask::2324 import sqlite325 from flask import g2627 DATABASE = '/path/to/database.db'2829 def connect_db():30 return sqlite3.connect(DATABASE)3132 @app.request_init33 def before_request():34 g.db = connect_db()3536 @app.request_shutdown37 def after_request(response):38 g.db.close()39 return response4041Easy Querying42`````````````4344Now in each request handling function you can access `g.db` to get the45current open database connection. To simplify working with SQLite a46helper function can be useful::4748 def query_db(query, args=(), one=False):49 cur = g.db.execute(query, args)50 rv = [dict((cur.description[idx][0], value)51 for idx, value in enumerate(row)) for row in cur.fetchall()]52 return (rv[0] if rv else None) if one else rv5354This handy little function makes working with the database much more55pleasant than it is by just using the raw cursor and connection objects.5657Here is how you can use it::5859 for user in query_db('select * from users'):60 print user['username'], 'has the id', user['user_id']6162Or if you just want a single result::6364 user = query_db('select * from users where username = ?',65 [the_username], one=True)66 if user is None:67 print 'No such user'68 else:69 print the_username, 'has the id', user['user_id']7071To pass variable parts to the SQL statement, use a question mark in the72statement and pass in the arguments as a list. Never directly add them to73the SQL statement with string formattings because this makes it possible74to attack the application using `SQL Injections75<http://en.wikipedia.org/wiki/SQL_injection>`_.7677Initial Schemas78```````````````7980Relational databases need schemas, so applications often ship a81`schema.sql` file that creates the database. It's a good idea to provide82a function that creates the database bases on that schema. This function83can do that for you::8485 from contextlib import closing86 87 def init_db():88 with closing(connect_db()) as db:89 with app.open_resource('schema.sql') as f:90 db.cursor().executescript(f.read())91 db.commit()9293You can then create such a database from the python shell:9495>>> from yourapplication import init_db96>>> init_db()9798.. _template-inheritance:99100Template Inheritance101--------------------102103The most powerful part of Jinja is template inheritance. Template inheritance104allows you to build a base "skeleton" template that contains all the common105elements of your site and defines **blocks** that child templates can override.106107Sounds complicated but is very basic. It's easiest to understand it by starting108with an example.109110111Base Template112`````````````113114This template, which we'll call ``layout.html``, defines a simple HTML skeleton115document that you might use for a simple two-column page. It's the job of116"child" templates to fill the empty blocks with content:117118.. sourcecode:: html+jinja119120 <!doctype html>121 <html>122 <head>123 {% block head %}124 <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">125 <title>{% block title %}{% endblock %} - My Webpage</title>126 {% endblock %}127 </head>128 <body>129 <div id="content">{% block content %}{% endblock %}</div>130 <div id="footer">131 {% block footer %}132 &copy; Copyright 2010 by <a href="http://domain.invalid/">you</a>.133 {% endblock %}134 </div>135 </body>136137In this example, the ``{% block %}`` tags define four blocks that child templates138can fill in. All the `block` tag does is to tell the template engine that a139child template may override those portions of the template.140141Child Template142``````````````143144A child template might look like this:145146.. sourcecode:: html+jinja147148 {% extends "layout.html" %}149 {% block title %}Index{% endblock %}150 {% block head %}151 {{ super() }}152 <style type="text/css">153 .important { color: #336699; }154 </style>155 {% endblock %}156 {% block content %}157 <h1>Index</h1>158 <p class="important">159 Welcome on my awesome homepage.160 {% endblock %}161162The ``{% extends %}`` tag is the key here. It tells the template engine that163this template "extends" another template. When the template system evaluates164this template, first it locates the parent. The extends tag must be the165first tag in the template. To render the contents of a block defined in166the parent template, use ``{{ super() }}``.
modified:docs/quickstart.rst+23 added
1.. _quickstart:23Quickstart4==========56Eager to get started? This page gives a good introduction in how to gets
142 unmodified lines
149don't have to deal with that. It will also make sure that ``HEAD``150requests are handled like the RFC demands, so you can completely ignore151that part of the HTTP specification.152153Static Files154------------155156Dynamic web applications need static files as well. That's usually where157the CSS and JavaScript files are coming from. Ideally your web server is158configured to serve them for you, but during development Flask can do that159as well. Just create a folder called `static` in your package or next to160your module and it will be available at `/static` on the application.161162To generate URLs to that part of the URL, use the special ``'static'`` URL163name::164165 url_for('static', filename='style.css')166167The file has to be stored on the filesystem as ``static/style.css``.168169Rendering Templates170-------------------171172Generating HTML from within Python is not fun, and actually pretty
49 unmodified lines
222Inside templates you also have access to the :class:`~flask.request`,223:class:`~flask.session` and :class:`~flask.g` objects as well as the224:func:`~flask.get_flashed_messages` function.225226Templates are especially useful if inheritance is used. If you want to227know how that works, head over to the :ref:`template-inheritance` pattern228documentation. Basically template inheritance makes it possible to keep229certain elements on each page (like header, navigation and footer).230231Automatic escaping is enabled, so if name contains HTML it will be escaped232automatically. If you can trust a variable and you know that it will be233safe HTML (because for example it came from a module that converts wiki234markup to HTML) you can mark it as safe by using the
325 unmodified lines
modified:examples/minitwit/minitwit.py+1 added-1 removed
63 unmodified lines
64def before_request():65 """Make sure we are connected to the database each request and look66 up the current user so that we know he's there.67 """68 g.db = sqlite3.connect(DATABASE)68 g.db = connect_db()69 if 'user_id' in session:70 g.user = query_db('select * from user where user_id = ?',71 [session['user_id']], one=True)72
156 unmodified lines