Flask quick start Flask quick start

Flask quick start Flask quick start

Getting started with flask

1.1. Comparison of the three frameworks

Django: a heavy weapon, it contains a lot of components: ORM, Form, ModelForm, cache, Session, middleware, signal, etc.

Flask: Short and sharp, there are not many internal components, and the third-party components are very rich. The routing is special and is implemented based on decorators, but the essence is still implemented through add_url_rule

Tornado: Asynchronous and non-blocking

1.2. Installation and operation

(1) Installation

Create a virtual environment and install directly

mkvirtualenv flask_project

pip install -i https://pypi.douban.com/simple flask

(2) Operation

Basic use

from flask import Flask

#Instantiate flask object
app = Flask(__name__)

#Add the correspondence between'/' and function index to the route
def index():
    return'Hello World!'

if __name__ =='__main__':
    #Monitor user requests
    #If a user request comes, execute the __call__ method of app, app.__call__

Browser access:

1.3. Quick start example

(1) view.py

from flask import Flask,render_template,request,redirect,session,url_for

app = Flask(__name__)
app.debug = True
app.secret_key ='abcdef'


def detail(nid):
    # Cannot access without login
    user = session.get('user_info')
    if not user:
        return redirect('/login')
    info = USERS.get(nid)
    return render_template('detail.html',info=info)

def index():
    #No access without login
    user = session.get('user_info')
    if not user:
        # return redirect('/login')
        #Reversely generate url according to the set alias
        url = url_for('login11')
        return redirect(url)
    return render_template('index.html',user_dict=USERS)

@app.route('/login',methods=['GET','POST'],endpoint='login11') #endpoint start alias
def login():
    if request.method =='GET':
        return render_template('login.html')
        user = request.form.get('user')
        pwd = request.form.get('pwd')
        if user =='derek' and pwd == '123':
            #Add session value
            user = session['user_info'] = user
            return redirect('/index')
        return render_template('login.html',error='Username or password error')

if __name__ =='__main__':

(2) templates/login.html

   <h1>User login</h1>
    <form method="post">
        <input type="text" name="user">
        <input type="text" name="pwd">
        <input type="submit" value="login">

(3) templates/index.html

   <h1>User login</h1>
    {% for k,v in user_dict.items() %}
        <td><a href="/detail/{{k}}">View details</a></td>
    {% endfor %}

(4) templates/detail.html


1.4. Configuration file

The configuration file in flask is a flask.config.Config object (inherited dictionary), the default configuration is:
        'DEBUG': get_debug_flag(default=False), whether to enable Debug mode
        'TESTING': False, whether to open the test mode
        'PROPAGATE_EXCEPTIONS': None,                          
        'SECRET_KEY': None,
        'PERMANENT_SESSION_LIFETIME': timedelta(days=31),
        'USE_X_SENDFILE': False,
        'LOGGER_NAME': None,
        'SERVER_NAME': None,
        'APPLICATION_ROOT': None,
        'SESSION_COOKIE_PATH': None,
        'MAX_CONTENT_LENGTH': None,
        'SEND_FILE_MAX_AGE_DEFAULT': timedelta(hours=12),
        'TRAP_HTTP_EXCEPTIONS': False,
        'JSON_AS_ASCII': True,
        'JSON_SORT_KEYS': True,

(1) Method one

app.debug = True

(2) Method two

app.config['DEBUG'] = True

(3) Method three (most commonly used)



A parent class, other subclasses inherit, override a method of the parent class     

class Config(object):
    DEBUG = False
    TESTING = False
    DATABASE_URI ='sqlite://:memory:'

class ProductionConfig(Config):
    DATABASE_URI ='mysql://user@localhost/foo'

class DevelopmentConfig(Config):
    DEBUG = True

class TestingConfig(Config):
    TESTING = True

1.5. The nature of the routing system

(1) There are the following five types of commonly used routing systems

@app.route('/login', methods=['GET','POST'])

Basically these five ways meet most needs, and you can also customize regular routing

from flask import Flask, views, url_for
            from werkzeug.routing import BaseConverter

            app = Flask(import_name=__name__)

            class RegexConverter(BaseConverter):
                Custom URL matching regular expression
                def __init__(self, map, regex):
                    super(RegexConverter, self).__init__(map)
                    self.regex = regex

                def to_python(self, value):
                    When the route is matched, the value of the parameter passed to the view function after the match is successful
                    :param value: 
                    return int(value)

                def to_url(self, value):
                    When using url_for to generate a URL in reverse, the passed parameters are processed by this method, and the returned value is used to generate the parameters in the URL
                    :param value: 
                    val = super(RegexConverter, self).to_url(value)
                    return val

            # Add to flask
            app.url_map.converters['regex'] = RegexConverter

            def index(nid):
                print(url_for('index', nid='888'))

            if __name__ =='__main__':

b. Customized regular route matching

(2) The nature of the routing system

from flask import Flask,render_template,request,redirect,session,url_for

app = Flask(__name__)
app.debug = True
app.secret_key ='abcdef'

#Source code analysis
The essence of routing, by looking at the source code analysis, its essence is realized by add_url_rule

1.decorator = app.route('/',methods=['GET','POST'],endpoint='index')

    def route(self, rule, **options):
        #appobject (ie self)
        #option = methods=['GET','POST'],endpoint='index'
        def decorator(f):
            endpoint = options.pop('endpoint', None)
            self.add_url_rule(rule, endpoint, f, **options)
            return f
        return decorator


def index():
    return'Hello word'

def login():

#By analyzing the source code, routing can be implemented in the following way
app.add_url_rule('/login','login11',login,methods=['GET','POST'],) #The second parameter is the alias, and the third parameter is the view function. If the endpoint is not written, then Default endpoint='view function name'

if __name__ =='__main__':

1.6. CBV of flask

from flask import Flask,render_template,request,redirect,session,url_for,views

app = Flask(__name__)
app.debug = True
app.secret_key ='abcdef'

def auth(func):
    def inner(*args, **kwargs):
        result = func(*args, **kwargs)
        return result
    return inner

class IndexView(views.MethodView):
    methods = ['GET']
    decorators = [auth,]

    def get(self):

    def post(self):

app.add_url_rule('/index', view_func=IndexView.as_view(name='index')) # name=endpoint

if __name__ =='__main__':

1.7.add_url_role parameter introduction

@app.route and app.add_url_rule parameters:
            rule, URL rule
            view_func, view function name
            defaults=None, the default value, when there are no parameters in the URL and the function requires parameters, use defaults={'k':'v'} to provide parameters for the function
            endpoint=None, name, used to generate URL in reverse, namely: url_for('name')
            methods=None, allowed request methods, such as: ["GET","POST"]

            strict_slashes=None, is it strictly required for the/symbol at the end of the URL,
                                        Such as:
                                                Visit http://www.xx.com/index/or http://www.xx.com/index either
                                                Visit only http://www.xx.com/index 
            redirect_to=None, redirect to the specified address
                                        Such as:
                                            @app.route('/index/<int:nid>', redirect_to='/home/<nid>')
                                            def func(adapter, nid):
                                                return "/home/888"
                                            @app.route('/index/<int:nid>', redirect_to=func)
            subdomain=None, subdomain access
                                                from flask import Flask, views, url_for

                                                app = Flask(import_name=__name__)
                                                app.config['SERVER_NAME'] ='wupeiqi.com:5000'

                                                @app.route("/", subdomain="admin")
                                                def static_index():
                                                    """Flask supports static subdomains
                                                    This is available at static.your-domain.tld"""
                                                    return "static.your-domain.tld"

                                                @app.route("/dynamic", subdomain="<username>")
                                                def username_index(username):
                                                    """Dynamic subdomains are also supported
                                                    Try going to user1.your-domain.tld/dynamic"""
                                                    return username + ".your-domain.tld"

                                                if __name__ =='__main__':

(1) The most basic ways of url

from flask import Flask,views
app = Flask(__name__)
app.debug = True
app.secret_key ='abcdef'

#The first
def index():
    return'Hello World!'

def login():


def auth(func):
    def inner(*args, **kwargs):
        result = func(*args, **kwargs)
        return result
    return inner

#CBV's pattern
class DetailView(views.MethodView):
    methods = ['GET']
    decorators = [auth,]

    def get(self):

    def post(self):

app.add_url_rule('/detail', view_func=DetailView.as_view(name='detail'))  # name=endpoint

if __name__ == '__main__':


Default value, when there are no parameters in the URL and the function requires parameters, use defaults={'k':'v'} to provide parameters for the function

 (3) Parameter strict_slashes=None

#Whether the/symbol at the end of the URL is strictly required, the default is False, such as:
@app.route('/index', strict_slashes=False)

#The following two ways can be accessed

#If set to True
@app.route('/index', strict_slashes=True)

#This can only be accessed

(4) redirect_to=None

Redirect to the specified address

def index():
    return'Company old website'

def index():
    return'Company's new website'

Visit: will be redirected directly to

1.8. Template language

The template syntax of flask is similar to that of Django. Here is a simple example

Markup is equivalent to Django's mark_safe

The front end also uses |safe

from flask import Flask,render_template,Markup

app = Flask(__name__)
app.debug = True
app.secret_key ='abcdef'

def func1(arg):
    return Markup("<input type='text' value='%s'/>"%arg)

def index():
    return render_template('index.html',func1=func1)

if __name__ =='__main__':



{{func1('zhang')}} <!-- Passing parameter arg -->

 1.9. Request and response

from flask import Flask
    from flask import request
    from flask import render_template
    from flask import redirect
    from flask import make_response

    app = Flask(__name__)

    @app.route('/login.html', methods=['GET', "POST"])
    def login():

        # Request related information
        # request.method
        # request.args
        # request.form
        # request.values
        # request.cookies
        # request.headers
        # request.path
        # request.full_path
        # request.script_root
        # request.url
        # request.base_url
        # request.url_root
        # request.host_url
        # request.host
        # request.files
        # obj = request.files['the_file_name']
        # obj.save('/var/www/uploads/' + secure_filename(f.filename))

        # Respond to related information
        # return "string"
        # return render_template('html template path',**{})
        # return redirect('/index.html')

        # response = make_response(render_template('index.html'))
        # response is flask.wrappers.Response type
        # response.delete_cookie('key')
        # response.set_cookie('key','value')
        # response.headers['X-Something'] ='A value'
        # return response

        return "content"

    if __name__ =='__main__':

1.10. flash introduction

(1) Simple usage

from flask import Flask,flash,get_flashed_messages

app = Flask(__name__)
app.debug = True
app.secret_key ='abcdef'

def get():
    data = get_flashed_messages()
    return'hello world'

def set():
    #Set a value to somewhere
    flash('Access once, set once')
    return'hello world'

if __name__ =='__main__':

Visit: When one visits one, the value will be set once

 Visit: get all the values ​​from somewhere and clear them

Reference: https://cloud.tencent.com/developer/article/1139361 Flask Quick Start Flask Quick Start-Cloud + Community-Tencent Cloud