Skip to content
Myr

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

1 file+224 added−0 removed

modified:docs/quickstart.rst+224 added
91 unmodified lines
92`float` like `int` but for floating point values93`path` like the default but also accepts slashes94=========== ===========================================9596URL Building97````````````9899If it can match URLs, can it also generate them? Of course you can. To100build a URL to a specific function you can use the :func:`~flask.url_for`101function. It accepts the name of the function as first argument and a102number of keyword arguments, each corresponding to the variable part of103the URL rule. Here some examples:104105>>> 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%20Doe124125(This also uses the :meth:`~flask.Flask.test_request_context` method126explained below. It basically tells flask to think we are handling a127request even though we are not, we are in an interactive Python shell.128Have a look at the explanation below. :ref:`context-locals`).129130131HTTP Methods132````````````133134HTTP knows different methods to access URLs. By default a route only
12 unmodified lines
147don't have to deal with that. It will also make sure that ``HEAD``148requests are handled like the RFC demands, so you can completely ignore149that part of the HTTP specification.150151Rendering Templates152-------------------153154Generating HTML from within Python is not fun, and actually pretty155cumbersome because you have to do the HTML escaping on your own to keep156the application secure. Because of that Flask configures the `Jinja2157<http://jinja.pocoo.org/2/>`_ template engine for you automatically.158159To render a template you can use the :func:`~flask.render_template`160method. All you have to do is to provide the name of the template and the161variables you want to pass to the template engine as keyword arguments.162Here a simple example of how to render a template::163164 from flask import render_template165166 @app.route('/hello/')167 @app.route('/hello/<name>')168 def hello(name=None):169 return render_template('hello.html', name=name)170171Flask will look for templates in the `templates` folder. So if your172application is a module, that folder is next to that module, if it's a173pacakge it's actually inside your package:174175**Case 1**: a module::176 177 /application.py178 /templates179 /hello.html180181**Case 2**: a package::182183 /application184 /__init__.py185 /templates186 /hello.html187188For templates you can use the full power of Jinja2 templates. Head over189to the `Jinja2 Template Documentation190<http://jinja.pocoo.org/2/documentation/templates>`_ for more information.191192Here an example template:193194.. sourcecode:: html+jinja195196 <!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 %}203204Inside 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.207208Automatic escaping is enabled, so if name contains HTML it will be escaped209automatically. If you can trust a variable and you know that it will be210safe HTML (because for example it came from a module that converts wiki211markup to HTML) you can mark it as safe by using the212:class:`~jinja2.Markup` class or by using the ``|safe`` filter in the213template. Head over to the Jinja 2 documentation for more examples.214215Here a basic introduction in how the :class:`~jinja2.Markup` class works:216217>>> from flask import Markup218>>> Markup('<strong>Hello %s!</strong>') % '<blink>hacker</blink>'219Markup(u'<strong>Hello &lt;blink&gt;hacker&lt;/blink&gt;!</strong>')220>>> Markup.escape('<blink>hacker</blink>')221Markup(u'&lt;blink&gt;hacker&lt;/blink&gt;')222>>> Markup('<em>Marked up</em> &raquo; HTML').striptags()223u'Marked up \xbb HTML'224225226Accessing Request Data227----------------------228229For web applications it's crucial to react to the data a client sent to
1 unmodified line
231:class:`~flask.request` object. If you have some experience with Python232you might be wondering how that object can be global and how Flask233manages to still be threadsafe. The answer are context locals:234235236.. _context-locals:237238Context Locals239``````````````240241.. admonition:: Insider Information
139 unmodified lines
381transmits. If you want to use sessions, do not use the cookies directly382but instead use the :ref:`sessions` in Flask that add some security on top383of cookies for you.384385386Redirects and Errors387--------------------388389To redirect a user to somewhere else you can use the390:func:`~flask.redirect` function, to abort a request early with an error391code the :func:`~flask.abort` function. Here an example how this works::392393 from flask import abort, redirect, url_for394395 @app.route('/')396 def index():397 return redirect(url_for('login'))398399 @app.route('/login')400 def login():401 abort(401)402 this_is_never_executed()403404This is a rather pointless example because a user will be redirected from405the index to a page he cannot access (401 means access denied) but it406shows how that works.407408By default a black and white error page is shown for each error code. If409you want to customize the error page, you can use the410:meth:`~flask.Flask.errorhandler` decorator::411412 from flask import render_template413414 @app.errorhandler(404)415 def page_not_found(error):416 return render_template('page_not_found.html')417418.. _sessions:419420Sessions421--------
31 unmodified lines
453 @app.route('/logout')454 def logout():455 # remove the username from the session if its there456 session.pop('username', None)457458Message Flashing459----------------460461Good applications and user interfaces are all about feedback. If the user462does not get enough feedback he will probably end up hating the463application. Flask provides a really simple way to give feedback to a464user with the flashing system. The flashing system basically makes it465possible to record a message at the end of a request and access it next466request and only next request. This is usually combined with a layout467template that does this.468469So here a full example::470471 from flask import flash, redirect, url_for, render_template472473 @app.route('/')474 def index():475 return render_template('index.html')476477 @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)488489And here the ``layout.html`` template which does the magic:490491.. sourcecode:: html+jinja492493 <!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 %}505506And here the index.html template:507508.. sourcecode:: html+jinja509510 {% 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 %}515516And of course the login template:517518.. sourcecode:: html+jinja519520 {% 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 %}