Heavily improved quickstart section.
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 4aa7621 · Browse files · 1 file·+224 added−0 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
1 file+224 added−0 removed
- other:+224 added−0 removed
Provenance
- Commit
625eba4- Tree
ca7cf17- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
4aa7621
1 file changed+224 added−0 removed
modified:docs/quickstart.rst+224 added
91 unmodified lines92 `float` like `int` but for floating point values93 `path` like the default but also accepts slashes94 =========== ===========================================95 96+URL Building97+````````````98 99+If it can match URLs, can it also generate them? Of course you can. To100+build a URL to a specific function you can use the :func:`~flask.url_for`101+function. It accepts the name of the function as first argument and a102+number of keyword arguments, each corresponding to the variable part of103+the URL rule. Here some examples:104+105+>>> from flask import Flask, url_for106+>>> app = Flask(__name__)107+>>> @app.route('/')108+... def index(): pass109+... 110+>>> @app.route('/login')111+... def login(): pass112+... 113+>>> @app.route('/user/<username>')114+... def profile(username): pass115+... 116+>>> with app.test_request_context():117+... print url_for('index')118+... print url_for('login')119+... print url_for('profile', username='John Doe')120+... 121+/122+/login123+/user/John%20Doe124+125+(This also uses the :meth:`~flask.Flask.test_request_context` method126+explained below. It basically tells flask to think we are handling a127+request even though we are not, we are in an interactive Python shell.128+Have a look at the explanation below. :ref:`context-locals`).129+130+131 HTTP Methods132 ````````````133 134 HTTP knows different methods to access URLs. By default a route only12 unmodified lines147 don't have to deal with that. It will also make sure that ``HEAD``148 requests are handled like the RFC demands, so you can completely ignore149 that part of the HTTP specification.150 151+Rendering Templates152+-------------------153 154+Generating HTML from within Python is not fun, and actually pretty155+cumbersome because you have to do the HTML escaping on your own to keep156+the application secure. Because of that Flask configures the `Jinja2157+<http://jinja.pocoo.org/2/>`_ template engine for you automatically.158+159+To render a template you can use the :func:`~flask.render_template`160+method. All you have to do is to provide the name of the template and the161+variables you want to pass to the template engine as keyword arguments.162+Here a simple example of how to render a template::163+164+ from flask import render_template165+166+ @app.route('/hello/')167+ @app.route('/hello/<name>')168+ def hello(name=None):169+ return render_template('hello.html', name=name)170+171+Flask will look for templates in the `templates` folder. So if your172+application is a module, that folder is next to that module, if it's a173+pacakge it's actually inside your package:174+175+**Case 1**: a module::176+ 177+ /application.py178+ /templates179+ /hello.html180+181+**Case 2**: a package::182+183+ /application184+ /__init__.py185+ /templates186+ /hello.html187+188+For templates you can use the full power of Jinja2 templates. Head over189+to the `Jinja2 Template Documentation190+<http://jinja.pocoo.org/2/documentation/templates>`_ for more information.191+192+Here an example template:193+194+.. sourcecode:: html+jinja195+196+ <!doctype html>197+ <title>Hello from Flask</title>198+ {% if name %}199+ <h1>Hello {{ name }}!</h1>200+ {% else %}201+ <h1>Hello World!</h1>202+ {% endif %}203+204+Inside templates you also have access to the :class:`~flask.request`,205+:class:`~flask.session` and :class:`~flask.g` objects as well as the206+:func:`~flask.get_flashed_messages` function.207+208+Automatic escaping is enabled, so if name contains HTML it will be escaped209+automatically. If you can trust a variable and you know that it will be210+safe HTML (because for example it came from a module that converts wiki211+markup to HTML) you can mark it as safe by using the212+:class:`~jinja2.Markup` class or by using the ``|safe`` filter in the213+template. Head over to the Jinja 2 documentation for more examples.214+215+Here a basic introduction in how the :class:`~jinja2.Markup` class works:216+217+>>> from flask import Markup218+>>> Markup('<strong>Hello %s!</strong>') % '<blink>hacker</blink>'219+Markup(u'<strong>Hello <blink>hacker</blink>!</strong>')220+>>> Markup.escape('<blink>hacker</blink>')221+Markup(u'<blink>hacker</blink>')222+>>> Markup('<em>Marked up</em> » HTML').striptags()223+u'Marked up \xbb HTML'224+225+226 Accessing Request Data227 ----------------------228 229 For web applications it's crucial to react to the data a client sent to1 unmodified line231 :class:`~flask.request` object. If you have some experience with Python232 you might be wondering how that object can be global and how Flask233 manages to still be threadsafe. The answer are context locals:234 235+236+.. _context-locals:237+238 Context Locals239 ``````````````240 241 .. admonition:: Insider Information139 unmodified lines381 transmits. If you want to use sessions, do not use the cookies directly382 but instead use the :ref:`sessions` in Flask that add some security on top383 of cookies for you.384 385+386+Redirects and Errors387+--------------------388+389+To redirect a user to somewhere else you can use the390+:func:`~flask.redirect` function, to abort a request early with an error391+code the :func:`~flask.abort` function. Here an example how this works::392+393+ from flask import abort, redirect, url_for394+395+ @app.route('/')396+ def index():397+ return redirect(url_for('login'))398+399+ @app.route('/login')400+ def login():401+ abort(401)402+ this_is_never_executed()403+404+This is a rather pointless example because a user will be redirected from405+the index to a page he cannot access (401 means access denied) but it406+shows how that works.407+408+By default a black and white error page is shown for each error code. If409+you want to customize the error page, you can use the410+:meth:`~flask.Flask.errorhandler` decorator::411+412+ from flask import render_template413+414+ @app.errorhandler(404)415+ def page_not_found(error):416+ return render_template('page_not_found.html')417+418 .. _sessions:419 420 Sessions421 --------31 unmodified lines453 @app.route('/logout')454 def logout():455 # remove the username from the session if its there456 session.pop('username', None)457+458+Message Flashing459+----------------460+461+Good applications and user interfaces are all about feedback. If the user462+does not get enough feedback he will probably end up hating the463+application. Flask provides a really simple way to give feedback to a464+user with the flashing system. The flashing system basically makes it465+possible to record a message at the end of a request and access it next466+request and only next request. This is usually combined with a layout467+template that does this.468+469+So here a full example::470+471+ from flask import flash, redirect, url_for, render_template472+473+ @app.route('/')474+ def index():475+ return render_template('index.html')476+477+ @app.route('/login', methods=['GET', 'POST'])478+ def login():479+ error = None480+ if request.method == 'POST':481+ if request.form['username'] != 'admin' or \482+ request.form['password'] != 'secret':483+ error = 'Invalid credentials'484+ else:485+ flash('You were sucessfully logged in')486+ return redirect(url_for('index'))487+ return render_template('login.html', error=error)488+489+And here the ``layout.html`` template which does the magic:490+491+.. sourcecode:: html+jinja492+493+ <!doctype html>494+ <title>My Application</title>495+ {% with messages = get_flashed_messages() %}496+ {% if messages %}497+ <ul class=flashes>498+ {% for message in messages %}499+ <li>{{ message }}</li>500+ {% endfor %}501+ </ul>502+ {% endif %}503+ {% endwith %}504+ {% block body %}{% endblock %}505+506+And here the index.html template:507+508+.. sourcecode:: html+jinja509+510+ {% extends "layout.html" %}511+ {% block body %}512+ <h1>Overview</h1>513+ <p>Do you want to <a href="{{ url_for('login') }}">log in?</a>514+ {% endblock %}515+516+And of course the login template:517+518+.. sourcecode:: html+jinja519+520+ {% extends "layout.html" %}521+ {% block body %}522+ <h1>Login</h1>523+ {% if error %}524+ <p class=error><strong>Error:</strong> {{ error }}525+ {% endif %}526+ <form action="" method=post>527+ <dl>528+ <dt>Username:529+ <dd><input type=text name=username value="{{530+ request.form.username }}">531+ <dt>Password:532+ <dd><input type=password name=password>533+ </dl>534+ <p><input type=submit value=Login>535+ </form>536+ {% endblock %}