explain escape at top of quickstart
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* introduce escape, and explain why it's omitted in examples * clean up imports in examples
authored by David Lord · committed by David Lord · parent db061cf · Browse files · 1 file·+50 added−49 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+50 added−49 removed
- other:+50 added−49 removed
Provenance
- Commit
413778a- Tree
8df760c- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
db061cf
1 file changed+50 added−49 removed
modified:docs/quickstart.rst+50 added-49 removed
1 unmodified line2 3 Quickstart4 ==========5 6-Eager to get started? This page gives a good introduction to Flask. It7-assumes you already have Flask installed. If you do not, head over to the8-:ref:`installation` section.6+Eager to get started? This page gives a good introduction to Flask.7+Follow :doc:`installation` to set up a project and install Flask first.8 9 10 A Minimal Application11 ---------------------12 14-A minimal Flask application looks something like this::13+A minimal Flask application looks something like this:14 15+.. code-block:: python16+17 from flask import Flask18+ from markupsafe import escape19+20 app = Flask(__name__)21 19- @app.route('/')22+ @app.route("/")23 def hello_world():21- return 'Hello, World!'24+ return f"<p>Hello, {escape(name)}!</p>"25 26 So what did that code do?27 25-1. First we imported the :class:`~flask.Flask` class. An instance of this26- class will be our WSGI application.27-2. Next we create an instance of this class. The first argument is the name of28- the application's module or package. If you are using a single module (as29- in this example), you should use ``__name__`` because depending on if it's30- started as application or imported as module the name will be different31- (``'__main__'`` versus the actual import name). This is needed so that32- Flask knows where to look for templates, static files, and so on. For more33- information have a look at the :class:`~flask.Flask` documentation.34-3. We then use the :meth:`~flask.Flask.route` decorator to tell Flask what URL35- should trigger our function.36-4. The function is given a name which is also used to generate URLs for that37- particular function, and returns the message we want to display in the38- user's browser.28+1. First we imported the :class:`~flask.Flask` class. An instance of29+ this class will be our WSGI application.30+2. Next we create an instance of this class. The first argument is the31+ name of the application's module or package. ``__name__`` is a32+ convenient shortcut for this that is appropriate for most cases.33+ This is needed so that Flask knows where to look for resources such34+ as templates and static files.35+3. We then use the :meth:`~flask.Flask.route` decorator to tell Flask36+ what URL should trigger our function.37+4. The function returns the message we want to display in the user's38+ browser. The default content type is HTML, so HTML in the string39+ will be rendered by the browser.40 41+.. note:: HTML escaping42+43+ When returning HTML (the default response type in Flask), any user44+ input rendered in the output must be escaped to protect from45+ injection attacks. HTML templates in Jinja, introduced later, will46+ do this automatically. :func:`~markupsafe.escape`, shown above, can47+ be used manually. It's omitted for brevity in the examples below.48+40-Just save it as :file:`hello.py` or something similar. Make sure to not call49+Save it as :file:`hello.py` or something similar. Make sure to not call50 your application :file:`flask.py` because this would conflict with Flask51 itself.52 44-To run the application you can either use the :command:`flask` command or45-python's ``-m`` switch with Flask. Before you can do that you need53+To run the application, use the :command:`flask` command or54+:command:`python -m flask`. Before you can do that you need55 to tell your terminal the application to work with by exporting the47-``FLASK_APP`` environment variable::56+``FLASK_APP`` environment variable:57 58+.. code-block:: text59+60 $ export FLASK_APP=hello.py61 $ flask run62 * Running on http://127.0.0.1:5000/63 5 unmodified lines69 And on PowerShell::70 71 PS C:\path\to\app> $env:FLASK_APP = "hello.py"72 62-Alternatively you can use :command:`python -m flask`::63-64- $ export FLASK_APP=hello.py65- $ python -m flask run66- * Running on http://127.0.0.1:5000/67-73 This launches a very simple builtin server, which is good enough for testing74 but probably not what you want to use in production. For deployment options see75 :ref:`deployment`.76 130 unmodified lines207 208 @app.route('/user/<username>')209 def show_user_profile(username):210 # show the user profile for that user206- return 'User %s' % escape(username)211+ return f'User {username}'212 213 @app.route('/post/<int:post_id>')214 def show_post(post_id):215 # show the post with the given id, the id is an integer211- return 'Post %d' % post_id216+ return f'Post {post_id}'217 218 @app.route('/path/<path:subpath>')219 def show_subpath(subpath):220 # show the subpath after /path/216- return 'Subpath %s' % escape(subpath)221+ return f'Subpath {subpath}'222 223 Converter types:224 225 ========== ==========================================59 unmodified lines285 Python shell. See :ref:`context-locals`.286 287 .. code-block:: python288 284- from flask import Flask, escape, url_for289+ from flask import url_for290 286- app = Flask(__name__)287-291 @app.route('/')292 def index():293 return 'index'294 2 unmodified lines297 return 'login'298 299 @app.route('/user/<username>')300 def profile(username):298- return '{}\'s profile'.format(escape(username))301+ return f'{username}\'s profile'302 303 with app.test_request_context():304 print(url_for('index'))305 print(url_for('login'))112 unmodified lines418 Automatic escaping is enabled, so if ``name`` contains HTML it will be escaped419 automatically. If you can trust a variable and you know that it will be420 safe HTML (for example because it came from a module that converts wiki421 markup to HTML) you can mark it as safe by using the419-:class:`~jinja2.Markup` class or by using the ``|safe`` filter in the422+:class:`~markupsafe.Markup` class or by using the ``|safe`` filter in the423 template. Head over to the Jinja 2 documentation for more examples.424 425 Here is a basic introduction to how the :class:`~jinja2.Markup` class works::426 424- >>> from flask import Markup427+ >>> from markupsafe import Markup428 >>> Markup('<strong>Hello %s!</strong>') % '<blink>hacker</blink>'429 Markup(u'<strong>Hello <blink>hacker</blink>!</strong>')430 >>> Markup.escape('<blink>hacker</blink>')431 Markup(u'<blink>hacker</blink>')65 unmodified lines497 498 The other possibility is passing a whole WSGI environment to the499 :meth:`~flask.Flask.request_context` method::500 498- from flask import request499-501 with app.request_context(environ):502 assert request.method == 'POST'503 504 The Request Object77 unmodified lines582 of the client to store the file on the server, pass it through the583 :func:`~werkzeug.utils.secure_filename` function that584 Werkzeug provides for you::585 585- from flask import request586 from werkzeug.utils import secure_filename587 588 @app.route('/upload', methods=['GET', 'POST'])589 def upload_file():115 unmodified lines705 you can use the :func:`~flask.make_response` function.706 707 Imagine you have a view like this::708 709+ from flask import render_template710+711 @app.errorhandler(404)712 def not_found(error):713 return render_template('error.html'), 404714 715 You just need to wrap the return expression with716 :func:`~flask.make_response` and get the response object to modify it, then717 return it::718 719+ from flask import make_response720+721 @app.errorhandler(404)722 def not_found(error):723 resp = make_response(render_template('error.html'), 404)724 resp.headers['X-Something'] = 'A value'25 unmodified lines750 more complex applications.751 752 .. code-block:: python753 754+ from flask import jsonify755+756 @app.route("/users")757 def users_api():758 users = get_all_users()759 return jsonify([user.to_json() for user in users])13 unmodified lines773 774 In order to use sessions you have to set a secret key. Here is how775 sessions work::776 771- from flask import Flask, session, redirect, url_for, escape, request777+ from flask import session778 773- app = Flask(__name__)774-779 # Set the secret key to some random bytes. Keep this really secret!780 app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'781 782 @app.route('/')783 def index():784 if 'username' in session:781- return 'Logged in as %s' % escape(session['username'])785+ return f'Logged in as {session["username"]}'786 return 'You are not logged in'787 788 @app.route('/login', methods=['GET', 'POST'])789 def login():12 unmodified lines802 # remove the username from the session if it's there803 session.pop('username', None)804 return redirect(url_for('index'))805 802-The :func:`~flask.escape` mentioned here does escaping for you if you are803-not using the template engine (as in this example).804-806 .. admonition:: How to generate good secret keys807 808 A secret key should be as random as possible. Your operating system has809 ways to generate pretty random data based on a cryptographic random85 unmodified lines