Skip to content
Myr

Proofread docs/quickstart

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

authored by Aku Kotkavuo · committed by Armin Ronacher · parent 738c66e · Browse files · 1 file+79 added−82 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+79 added−82 removed

  • other:+79 added−82 removed

1 file+79 added−82 removed

modified:docs/quickstart.rst+79 added-82 removed
1 unmodified line
23Quickstart4==========56Eager to get started? This page gives a good introduction in how to gets6Eager to get started? This page gives a good introduction in how to get7started with Flask. This assumes you already have Flask installed. If8you do not, head over to the :ref:`installation` section.910
25 unmodified lines
36see your hello world greeting.3738So what did that code do?39401. first we imported the :class:`~flask.Flask` class. An instance of this401. First we imported the :class:`~flask.Flask` class. An instance of this41 class will be our WSGI application. The first argument is the name of42 the application's module. If you are using a single module (like here)43 you should use `__name__` because depending on if it's started as44 application or imported as module the name will be different45 (``'__main__'`` versus the actual import name). For more information46 on that, have a look at the :class:`~flask.Flask` documentation.472. next we create an instance of it. We pass it the name of the module /472. Next we create an instance of it. We pass it the name of the module /48 package. This is needed so that Flask knows where it should look for49 templates, static files and so on.503. Then we use the :meth:`~flask.Flask.route` decorator to tell Flask51 what URL should trigger our function.
28 unmodified lines
8081Debug Mode82----------8384Now that :meth:`~flask.Flask.run` method is nice to start a local84The :meth:`~flask.Flask.run` method is nice to start a local85development server, but you would have to restart it manually after each86change you do to code. That is not very nice and Flask can do better. If87you enable the debug support the server will reload itself on code changes88and also provide you with a helpful debugger if things go wrong.
11 unmodified lines
100Both will have exactly the same effect.101102.. admonition:: Attention103104 The interactive debugger however does not work in forking environments105 which makes it nearly impossible to use on production servers but the106 debugger still allows the execution of arbitrary code which makes it a107 major security risk and **must never be used on production machines**108 because of that.104 Even though the interactive debugger does not work in forking environments105 (which makes it nearly impossible to use on production servers), it still106 allows the execution of arbitrary code. That makes it a major security107 risk and therefore it **must never be used on production machines**.108109Screenshot of the debugger in action:110111.. image:: _static/debugger.png
4 unmodified lines
116117Routing118-------119120Modern web applications have beautiful URLs. This helps people remember121the URLs which is especially handy for applications that are used from122mobile devices with slower network connections. If the user can directly123go to the desired page without having to hit the index page it is more124likely he will like the page and come back next time.125126As you have seen above, the :meth:`~flask.Flask.route` decorator is used122to bind a function to a URL. But there is more to it! You can make123certain parts of the URL dynamic and attach multiple rules to a function.127to bind a function to a URL. Here are some basic examples::128125Here some examples::126129 @app.route('/')130 def index():131 return 'Index Page'132133 @app.route('/hello')134 def hello():135 return 'Hello World'136137But there is more to it! You can make certain parts of the URL dynamic138and attach multiple rules to a function.139140Variable Rules141``````````````142139Modern web applications have beautiful URLs. This helps people remember140the URLs which is especially handy for applications that are used from141mobile devices with slower network connections. If the user can directly142go to the desired page without having to hit the index page it is more143likely he will like the page and come back next time.144143To add variable parts to a URL you can mark these special sections as144``<variable_name>``. Such a part is then passed as keyword argument to145your function. Optionally a converter can be specified by specifying a148rule with ``<converter:variable_name>``. Here some nice examples::146rule with ``<converter:variable_name>``. Here are some nice examples::147148 @app.route('/user/<username>')149 def show_user_profile(username):150 # show the user profile for that user
49 unmodified lines
200201URL Building202````````````203206If it can match URLs, can it also generate them? Of course you can. To204If it can match URLs, can it also generate them? Of course it can. To205build a URL to a specific function you can use the :func:`~flask.url_for`206function. It accepts the name of the function as first argument and a207number of keyword arguments, each corresponding to the variable part of208the URL rule. Unknown variable parts are appended to the URL as query211parameter. Here some examples:209parameter. Here are some examples:210211>>> from flask import Flask, url_for212>>> app = Flask(__name__)213>>> @app.route('/')
39 unmodified lines
253254HTTP (the protocol web applications are speaking) knows different methods255to access URLs. By default a route only answers to `GET` requests, but256that can be changed by providing the `methods` argument to the259:meth:`~flask.Flask.route` decorator. Here some examples::257:meth:`~flask.Flask.route` decorator. Here are some examples::258259 @app.route('/login', methods=['GET', 'POST'])260 def login():261 if request.method == 'POST':
7 unmodified lines
269protocol) demands, so you can completely ignore that part of the HTTP270specification. Likewise as of Flask 0.6, `OPTIONS` is implemented for you271as well automatically.272275You have no idea what an HTTP method is? Worry not, here quick276introduction in HTTP methods and why they matter:273You have no idea what an HTTP method is? Worry not, here is a quick274introduction to HTTP methods and why they matter:275276The HTTP method (also often called "the verb") tells the server what the277clients wants to *do* with the requested page. The following methods are278very common:279280`GET`283 The Browser tells the server: just *get* me the information stored on284 that page and send them to me. This is probably the most common285 method.281 The browser tells the server to just *get* the information stored on282 that page and send it. This is probably the most common method.283284`HEAD`288 The Browser tells the server: get me the information, but I am only285 The browser tells the server to get the information, but it is only286 interested in the *headers*, not the content of the page. An287 application is supposed to handle that as if a `GET` request was291 received but not deliver the actual contents. In Flask you don't have292 to deal with that at all, the underlying Werkzeug library handles that293 for you.288 received but to not deliver the actual content. In Flask you don't289 have to deal with that at all, the underlying Werkzeug library handles290 that for you.291292`POST`293 The browser tells the server that it wants to *post* some new294 information to that URL and that the server must ensure the data is
2 unmodified lines
297298`PUT`299 Similar to `POST` but the server might trigger the store procedure300 multiple times by overwriting the old values more than once. Now you304 might be asking why this is any useful, but there are some good305 reasons to do that. Consider the connection is lost during306 transmission, in that situation a system between the browser and the307 server might sent the request safely a second time without breaking301 might be asking why is this useful, but there are some good reasons302 to do it this way. Consider that the connection gets lost during303 transmission: in this situation a system between the browser and the304 server might receive the request safely a second time without breaking305 things. With `POST` that would not be possible because it must only306 be triggered once.307308`DELETE`312 Remove the information that the given location.309 Remove the information at the given location.310311`OPTIONS`315 Provides a quick way for a requesting client to figure out which316 methods are supported by this URL. Starting with Flask 0.6, this317 is implemented for you automatically.312 Provides a quick way for a client to figure out which methods are313 supported by this URL. Starting with Flask 0.6, this is implemented314 for you automatically.315316Now the interesting part is that in HTML4 and XHTML1, the only methods a320form might submit to the server are `GET` and `POST`. But with JavaScript321and future HTML standards you can use other methods as well. Furthermore322HTTP became quite popular lately and there are more things than browsers323that are speaking HTTP. (Your revision control system for instance might324speak HTTP)317form can submit to the server are `GET` and `POST`. But with JavaScript318and future HTML standards you can use the other methods as well. Furthermore319HTTP has become quite popular lately and browsers are no longer the only320clients that are using HTTP. For instance, many revision control system321use it.322323.. _HTTP RFC: http://www.ietf.org/rfc/rfc2068.txt324325Static Files
53 unmodified lines
379to the :ref:`templating` section of the documentation or the official380`Jinja2 Template Documentation381<http://jinja.pocoo.org/2/documentation/templates>`_ for more information.382386Here an example template:383Here is an example template:384385.. sourcecode:: html+jinja386387 <!doctype html>
19 unmodified lines
407markup to HTML) you can mark it as safe by using the408:class:`~jinja2.Markup` class or by using the ``|safe`` filter in the409template. Head over to the Jinja 2 documentation for more examples.410414Here a basic introduction in how the :class:`~jinja2.Markup` class works:411Here is a basic introduction to how the :class:`~jinja2.Markup` class works:412413>>> from flask import Markup414>>> Markup('<strong>Hello %s!</strong>') % '<blink>hacker</blink>'415Markup(u'<strong>Hello &lt;blink&gt;hacker&lt;/blink&gt;!</strong>')
5 unmodified lines
421.. versionchanged:: 0.5422423 Autoescaping is no longer enabled for all templates. The following424 extensions for templates trigger autoescaping: ``.html``, ``.htm``,428 ``.xml``, ``.xhtml``. Templates loaded from string will have425 ``.xml``, ``.xhtml``. Templates loaded from a string will have426 autoescaping disabled.427431.. [#] Unsure what that :class:`~flask.g` object is? It's something you432 can store information on yourself, check the documentation of that433 object (:class:`~flask.g`) and the :ref:`sqlite3` for more428.. [#] Unsure what that :class:`~flask.g` object is? It's something in which429 you can store information for your own needs, check the documentation of430 that object (:class:`~flask.g`) and the :ref:`sqlite3` for more431 information.432433434Accessing Request Data
15 unmodified lines
450451 If you want to understand how that works and how you can implement452 tests with context locals, read this section, otherwise just skip it.453457Certain objects in Flask are global objects, but not just a standard458global object, but actually a proxy to an object that is local to a459specific context. What a mouthful. But that is actually quite easy to460understand.454Certain objects in Flask are global objects, but not of the usual kind.455These objects are actually proxies to objects that are local to a specific456context. What a mouthful. But that is actually quite easy to understand.457458Imagine the context being the handling thread. A request comes in and the459webserver decides to spawn a new thread (or something else, the460underlying object is capable of dealing with other concurrency systems
3 unmodified lines
464It does that in an intelligent way that one application can invoke another465application without breaking.466467So what does this mean to you? Basically you can completely ignore that472this is the case unless you are unittesting or something different. You468this is the case unless you are doing something like unittesting. You469will notice that code that depends on a request object will suddenly break470because there is no request object. The solution is creating a request471object yourself and binding it to the context. The easiest solution for472unittesting is by using the :meth:`~flask.Flask.test_request_context`473context manager. In combination with the `with` statement it will bind a478test request so that you can interact with it. Here an example::474test request so that you can interact with it. Here is an example::475476 from flask import request477478 with app.test_request_context('/hello', method='POST'):
13 unmodified lines
492The Request Object493``````````````````494495The request object is documented in the API section and we will not cover500it here in detail (see :class:`~flask.request`), but just mention some of501the most common operations. First of all you have to import it from the496it here in detail (see :class:`~flask.request`). Here is a broad overview of497some of the most common operations. First of all you have to import it from498the `flask` module::499500 from flask import request501502The current request method is available by using the503:attr:`~flask.request.method` attribute. To access form data (data504transmitted in a `POST` or `PUT` request) you can use the509:attr:`~flask.request.form` attribute. Here a full example of the two505:attr:`~flask.request.form` attribute. Here is a full example of the two506attributes mentioned above::507508 @app.route('/login', methods=['POST', 'GET'])509 def login():
19 unmodified lines
529 searchword = request.args.get('q', '')530531We recommend accessing URL parameters with `get` or by catching the532`KeyError` because users might change the URL and presenting them a 400537bad request page in that case is a bit user unfriendly.533bad request page in that case is not user friendly.534539For a full list of methods and attributes on that object, head over to the540:class:`~flask.request` documentation.535For a full list of methods and attributes of the request object, head over536to the :class:`~flask.request` documentation.537538539File Uploads540````````````541546Obviously you can handle uploaded files with Flask just as easy. Just547make sure not to forget to set the ``enctype="multipart/form-data"``548attribute on your HTML form, otherwise the browser will not transmit your549files at all.542You can handle uploaded files with Flask easily. Just make sure not to543forget to set the ``enctype="multipart/form-data"`` attribute on your HTML544form, otherwise the browser will not transmit your files at all.545546Uploaded files are stored in memory or at a temporary location on the547filesystem. You can access those files by looking at the548:attr:`~flask.request.files` attribute on the request object. Each549uploaded file is stored in that dictionary. It behaves just like a550standard Python :class:`file` object, but it also has a551:meth:`~werkzeug.FileStorage.save` method that allows you to store that557file on the filesystem of the server. Here a simple example how that558works::552file on the filesystem of the server. Here is a simple example showing how553that works::554555 from flask import request556557 @app.route('/upload', methods=['GET', 'POST'])
36 unmodified lines
594Redirects and Errors595--------------------596597To redirect a user to somewhere else you can use the603:func:`~flask.redirect` function, to abort a request early with an error604code the :func:`~flask.abort` function. Here an example how this works::598:func:`~flask.redirect` function. To abort a request early with an error599code use the :func:`~flask.abort` function. Here an example how this works::600601 from flask import abort, redirect, url_for602603 @app.route('/')
71 unmodified lines
675676The here mentioned :func:`~flask.escape` does escaping for you if you are677not using the template engine (like in this example).678684.. admonition:: How to generate good Secret Keys679.. admonition:: How to generate good secret keys680681 The problem with random is that it's hard to judge what random is. And682 a secret key should be as random as possible. Your operating system683 has ways to generate pretty random stuff based on a cryptographic
25 unmodified lines
709-------710711.. versionadded:: 0.3712718Sometimes you might be in the situation where you deal with data that719should be correct, but actually is not. For example you have some client720side code that sends an HTTP request to the server, and it's obviously713Sometimes you might be in a situation where you deal with data that714should be correct, but actually is not. For example you may have some client715side code that sends an HTTP request to the server but it's obviously716malformed. This might be caused by a user tempering with the data, or the722client code failed. Most the time, it's okay to reply with ``400 Bad723Request`` in that situation, but other times it is not and the code has to724continue working.717client code failing. Most of the time, it's okay to reply with ``400 Bad718Request`` in that situation, but sometimes that won't do and the code has719to continue working.720726Yet you want to log that something fishy happened. This is where loggers727come in handy. As of Flask 0.3 a logger is preconfigured for you to use.721You may still want to log that something fishy happened. This is where722loggers come in handy. As of Flask 0.3 a logger is preconfigured for you723to use.724725Here are some example log calls::726727 app.logger.debug('A value for debugging')728 app.logger.warning('A warning occurred (%d apples)', 42)729 app.logger.error('An error occurred')730731The attached :attr:`~flask.Flask.logger` is a standard logging736:class:`~logging.Logger`, so head over to the official stdlib737documentation for more information.732:class:`~logging.Logger`, so head over to the official `logging733documentation <http://docs.python.org/library/logging.html>`_ for more734information.735736Hooking in WSGI Middlewares737---------------------------738
7 unmodified lines