Get started quickly with Python-Flask

refer to :

1 minimal application

Here the author uses PyCharm to develop Flask, so you can see this simplest application after creating the project.

from flask import Flask

app = Flask(__name__)

def hello_world():  # put application's code here
    return 'Hello World!'

Code meaning:

  1. Import the Flask class. An instance of this class will be our WSGI application.
  2. Then create an instance of this class. The first parameter is the name of the application module or package. __name__ is a shortcut that works in most cases. With this parameter, Flask knows where to find things like templates and static files.
  3. Then we call the route() decorator to tell Flask the URL to trigger the function.
  4. The function returns the information that needs to be displayed in the user's browser. The default content is HTML, so the HTML in the string will be rendered by the browser.

After running it looks like this:

FLASK_ENV = development
In folder E:/PythonWeb_new/flaskFasttry
C:\Users\LENOVO\AppData\Local\Programs\Python\Python38\python.exe -m flask run

  • Serving Flask app ''
  • Debug mode: off
    WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
  • Running on
    Press CTRL+C to quit

You can click on the URL to see the program.
Check FLASK_DEBUG in the editing configuration to modify the real-time update content of the program in real time.

2 HTML escaping

To prevent injection attacks, all user-supplied values ​​must be escaped before output rendering. use Jinja rendered HTML This is done automatically.

It is also possible to escape manually using escape.

from markupsafe import escape

def hello_world(name):  # put application's code here
    return f'Hello {escape(name)}!'

3 routing

URL s for modern Web applications are meaningful and easy to remember.
Use the route() decorator to bind the function to the URL:

def hello_world(name):  # put application's code here
    return f'Hello {escape(name)}!'

def hello():  # put application's code here
    return f'Hello!'

4 Variable Rules

Variables can be added to a URL by marking part of the URL as <variable_name>. The marked part is passed to the function as a keyword. Using converter:variable_name , you can add converters to variables.

def show_post(post_id):
    # show the post with the given id, the id is an integer
    return f'Post {post_id}'

def show_subpath(subpath):
    # show the subpath after /path/
    return f'Subpath {escape(subpath)}'

Converter type:

stringaccepts any text that does not contain slashes
intpositive integer
floatpositive floating point number
pathstring-like, allows to contain /
uuidaccepts UUID strings

5 Redirect behavior

The following two rules differ in whether or not a trailing slash is used. :

def projects():
    return 'The project page'

def about():
    return 'The about page'
projects of URL It is quite satisfactory, with a trailing slash, and it looks like a folder. access a string without a trailing slash URL ( /projects )Time Flask redirects automatically, helping you add a trailing slash ( /projects/ ). 

The about URL does not have a trailing slash, so it behaves like a file. If you access this URL with a trailing slash (/about/ ) you get a 404 "Not Found" error. This keeps the URL unique and helps search engines index the same page repeatedly.

6 URL Construction

The url_for() function is used to construct the URL of the specified function. The first parameter is the function name. Accepts any number of keyword arguments, each of which corresponds to a variable in the URL.

7 HTTP methods

Web applications use different HTTP methods to handle URL s. GET requests are used by default. Cocoa uses the routes() decorator methods parameter to handle different HTTP methods.

from flask import request

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        return do_the_login()
        return show_the_login_form()

8 Static files

Dynamic web applications also require static files, typically CSS and JavaScript files. Static files are located in /static of the application.
The response URL can be generated using a specific 'static' endpoint.

url_for('static', filename='style.css')

9 Rendering templates

Flask automatically configures the Jinjia2 template engine.
Templates can be rendered using the render_template() method,

  • The file in the template file to redirect.
  • variables in the file.

10 Request object

First, you need to import the request object.

from flask import request

The current request method can be manipulated by using the method attribute, and form data (data transmitted in a POST or PUT request) can be manipulated by using the form attribute. The following is an example of using the above two properties:

@app.route('/login', methods=['POST', 'GET'])
def login():
    error = None
    if request.method == 'POST':
        if valid_login(request.form['username'],
            return log_the_user_in(request.form['username'])
            error = 'Invalid username/password'
    # the code below is executed if the request method
    # was GET or the credentials were invalid
    return render_template('login.html', error=error)

11 File upload

Don't forget to set enctype="multipart/form-data" in the HTML form, otherwise the browser will not deliver your file.
Uploaded files are stored in a temporary location in memory or on the file system. You can access uploaded files through the files property of the request object. Each uploaded file is stored in this typography attribute. This attribute is basically the same as the standard Python file object, with the addition of a save() method for saving the uploaded file to the server's file system. The following example shows how it works:

from flask import request

@app.route('/upload', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        f = request.files['the_file']'/var/www/uploads/uploaded_file.txt')
If you want to know the name of the file on the client system before it was uploaded, you can use filename Attributes. But keep in mind that this value can be faked and never trust this value. If you want to use the file name of the client as the file name on the server, you can pass Werkzeug which provided secure_filename() function:
from werkzeug.utils import secure_filename

@app.route('/upload', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        file = request.files['the_file']"/var/www/uploads/{secure_filename(file.filename)}")

12 Cookies

To access cookies, use the cookies property. cookies can be set using the set_cookie method of the response object. The cookies property of the request object is a dictionary containing all cookies transmitted by the client. In Flask, if you use sessions, then don't use cookies directly, because sessions are more secure.
Read cookies:

from flask import request

def index():
    username = request.cookies.get('username')
    # use cookies.get(key) instead of cookies[key] to not get a
    # KeyError if the cookie is missing.
store cookies: 
from flask import make_response

def index():
    resp = make_response(render_template(...))
    resp.set_cookie('username', 'the username')
    return resp

13 Redirects and errors

Use the redirect() function to redirect. Use abort() to abort the request earlier with an error code:

from flask import abort, redirect, url_for

def index():
    return redirect(url_for('login'))

def login():
use errorhandler() The decorator can customize the error page:
def page_not_found(error):
    return render_template('page_not_found.html'), 404

14 API in JSON format

Writing such an API in Flask is easy to get started with. If a dict is returned from the view, then it will be converted to a JSON response.

def me_api():
    user = get_current_user()
    return {
        "username": user.username,
        "theme": user.theme,
        "image": url_for("user_image", filename=user.image),

You can also use jsonify().

def users_api():
    users = get_all_users()
    return jsonify([user.to_json() for user in users])

15 sessions

In addition to the request object, there is an object called a session that can be used to store information between requests. This object is equivalent to a cookie encrypted with a key, i.e. a user can view your cookie, but cannot modify it without the key.
You must set a key before using the session. for example:

from flask import session

# Set the secret key to some random bytes. Keep this really secret!
app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'

def index():
    if 'username' in session:
        return f'Logged in as {session["username"]}'
    return 'You are not logged in'

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        session['username'] = request.form['username']
        return redirect(url_for('index'))
    return '''
        <form method="post">
            <p><input type=text name=username>
            <p><input type=submit value=Login>

def logout():
    # remove the username from the session if it's there
    session.pop('username', None)
    return redirect(url_for('index'))

Tags: Back-end Python Flask

Posted by jackmn1 on Fri, 11 Nov 2022 04:07:21 +1030