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
Provenance
- Commit
727c701- Tree
8e245d8- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
4edec48
5 files changed+199 added−4 removed
modified:docs/api.rst+2 added
1+.. _api:2+3 API4 ===5 6 .. module:: flask181 unmodified linesmodified:docs/index.rst+7 added-3 removed
1 Welcome to Flask2 ================3 4-Welcome to Flask's documentation.4+Welcome to Flask's documentation. This documentation is devided into5+different parts. I would suggest to get started with the6+:ref:`installation` and then heading over to the :ref:`quickstart`. If7+you 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.10 6-Contents:7-11 .. toctree::12 :maxdepth: 213 14 installation15 quickstart16+ patterns17 apiadded:docs/patterns.rst+166 added
1+.. _patterns:2+3+Patterns in Flask4+=================5+6+Certain things are common enough that the changes are high you will find7+them in most web applications. For example quite a lot of applications8+are using relational databases and user authentication. In that case,9+changes are they will open a database connection at the beginning of the10+request and get the information of the currently logged in user. At the11+end of the request, the database connection is closed again.12+13+In Flask you can implement such things with the14+:meth:`~flask.Flask.request_init` and15+:meth:`~flask.Flask.request_shutdown` decorators in combination with the16+special :class:`~flask.g` object.17+18+19+Using SQLite 3 with Flask20+-------------------------21+22+So here a simple example how you can use SQLite 3 with Flask::23+24+ import sqlite325+ from flask import g26+27+ DATABASE = '/path/to/database.db'28+29+ def connect_db():30+ return sqlite3.connect(DATABASE)31+32+ @app.request_init33+ def before_request():34+ g.db = connect_db()35+36+ @app.request_shutdown37+ def after_request(response):38+ g.db.close()39+ return response40+41+Easy Querying42+`````````````43+44+Now in each request handling function you can access `g.db` to get the45+current open database connection. To simplify working with SQLite a46+helper function can be useful::47+48+ 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 rv53+54+This handy little function makes working with the database much more55+pleasant than it is by just using the raw cursor and connection objects.56+57+Here is how you can use it::58+59+ for user in query_db('select * from users'):60+ print user['username'], 'has the id', user['user_id']61+62+Or if you just want a single result::63+64+ 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']70+71+To pass variable parts to the SQL statement, use a question mark in the72+statement and pass in the arguments as a list. Never directly add them to73+the SQL statement with string formattings because this makes it possible74+to attack the application using `SQL Injections75+<http://en.wikipedia.org/wiki/SQL_injection>`_.76+77+Initial Schemas78+```````````````79+80+Relational databases need schemas, so applications often ship a81+`schema.sql` file that creates the database. It's a good idea to provide82+a function that creates the database bases on that schema. This function83+can do that for you::84+85+ 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()92+93+You can then create such a database from the python shell:94+95+>>> from yourapplication import init_db96+>>> init_db()97+98+.. _template-inheritance:99+100+Template Inheritance101+--------------------102+103+The most powerful part of Jinja is template inheritance. Template inheritance104+allows you to build a base "skeleton" template that contains all the common105+elements of your site and defines **blocks** that child templates can override.106+107+Sounds complicated but is very basic. It's easiest to understand it by starting108+with an example.109+110+111+Base Template112+`````````````113+114+This template, which we'll call ``layout.html``, defines a simple HTML skeleton115+document that you might use for a simple two-column page. It's the job of116+"child" templates to fill the empty blocks with content:117+118+.. sourcecode:: html+jinja119+120+ <!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+ © Copyright 2010 by <a href="http://domain.invalid/">you</a>.133+ {% endblock %}134+ </div>135+ </body>136+137+In this example, the ``{% block %}`` tags define four blocks that child templates138+can fill in. All the `block` tag does is to tell the template engine that a139+child template may override those portions of the template.140+141+Child Template142+``````````````143+144+A child template might look like this:145+146+.. sourcecode:: html+jinja147+148+ {% 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 %}161+162+The ``{% extends %}`` tag is the key here. It tells the template engine that163+this template "extends" another template. When the template system evaluates164+this template, first it locates the parent. The extends tag must be the165+first tag in the template. To render the contents of a block defined in166+the parent template, use ``{{ super() }}``.modified:docs/quickstart.rst+23 added
1+.. _quickstart:2+3 Quickstart4 ==========5 6 Eager to get started? This page gives a good introduction in how to gets142 unmodified lines149 don't have to deal with that. It will also make sure that ``HEAD``150 requests are handled like the RFC demands, so you can completely ignore151 that part of the HTTP specification.152 153+Static Files154+------------155+156+Dynamic web applications need static files as well. That's usually where157+the CSS and JavaScript files are coming from. Ideally your web server is158+configured to serve them for you, but during development Flask can do that159+as well. Just create a folder called `static` in your package or next to160+your module and it will be available at `/static` on the application.161+162+To generate URLs to that part of the URL, use the special ``'static'`` URL163+name::164+165+ url_for('static', filename='style.css')166+167+The file has to be stored on the filesystem as ``static/style.css``.168+169 Rendering Templates170 -------------------171 172 Generating HTML from within Python is not fun, and actually pretty49 unmodified lines222 Inside 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.225 226+Templates are especially useful if inheritance is used. If you want to227+know how that works, head over to the :ref:`template-inheritance` pattern228+documentation. Basically template inheritance makes it possible to keep229+certain elements on each page (like header, navigation and footer).230+231 Automatic escaping is enabled, so if name contains HTML it will be escaped232 automatically. If you can trust a variable and you know that it will be233 safe HTML (because for example it came from a module that converts wiki234 markup to HTML) you can mark it as safe by using the325 unmodified linesmodified:examples/minitwit/minitwit.py+1 added-1 removed
63 unmodified lines64 def 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