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
@app.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__
    app.run()

Browser access: http://127.0.0.1:5000/

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'

USERS = {
    1:{'name':'derek','age':18},
    2:{'name':'tom','age':20},
    3:{'name':'jack','age':22},
}

@app.route('/detail/<int:nid>',methods=['GET'])
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)

@app.route('/index',methods=['GET'])
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')
    else:
        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__':
    app.run()

(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">
        {{error}}
    </form>

(3) templates/index.html

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

(4) templates/detail.html

    {{info.name}}
    {{info.age}}

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,                          
        'PRESERVE_CONTEXT_ON_EXCEPTION': None,
        'SECRET_KEY': None,
        'PERMANENT_SESSION_LIFETIME': timedelta(days=31),
        'USE_X_SENDFILE': False,
        'LOGGER_NAME': None,
        'LOGGER_HANDLER_POLICY':'always',
        'SERVER_NAME': None,
        'APPLICATION_ROOT': None,
        'SESSION_COOKIE_NAME':'session',
        'SESSION_COOKIE_DOMAIN': None,
        'SESSION_COOKIE_PATH': None,
        'SESSION_COOKIE_HTTPONLY': True,
        'SESSION_COOKIE_SECURE': False,
        'SESSION_REFRESH_EACH_REQUEST': True,
        'MAX_CONTENT_LENGTH': None,
        'SEND_FILE_MAX_AGE_DEFAULT': timedelta(hours=12),
        'TRAP_BAD_REQUEST_ERRORS': False,
        'TRAP_HTTP_EXCEPTIONS': False,
        'EXPLAIN_TEMPLATE_LOADING': False,
        'PREFERRED_URL_SCHEME':'http',
        'JSON_AS_ASCII': True,
        'JSON_SORT_KEYS': True,
        'JSONIFY_PRETTYPRINT_REGULAR': True,
        'JSONIFY_MIMETYPE':'application/json',
        'TEMPLATES_AUTO_RELOAD': None,
    }

(1) Method one

app.debug = True

(2) Method two

app.config['DEBUG'] = True

(3) Method three (most commonly used)

app.config.from_object("settings.DevelopmentConfig")

settings.py

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('/user/<username>')
@app.route('/post/<int:post_id>')
@app.route('/post/<float:post_id>')
@app.route('/post/<path:path>')
@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: 
                    """
                    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: 
                    :return: 
                    """
                    val = super(RegexConverter, self).to_url(value)
                    return val

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


            @app.route('/index/<regex("\d+"):nid>')
            def index(nid):
                print(url_for('index', nid='888'))
                return'Index'


            if __name__ =='__main__':
                app.run()

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)
        #rule=/
        #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

2.@decorator
    decorator(index)
'''

@app.route('/',methods=['GET','POST'],endpoint='index')
def index():
    return'Hello word'

def login():
    return'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__':
    app.run()

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):
        return'Index.GET'

    def post(self):
        return'Index.POST'


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

if __name__ =='__main__':
    app.run()

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:
                                            @app.route('/index',strict_slashes=False),
                                                Visit http://www.xx.com/index/or http://www.xx.com/index either
                                            @app.route('/index',strict_slashes=True)
                                                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>')
                                            or
                                            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__':
                                                    app.run()
        

(1) The most basic ways of url

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


#The first
@app.route('/',methods=['GET','POST'],endpoint='index')
def index():
    return'Hello World!'

def login():
    return'login'

#Second
app.add_url_rule('/login','login',login,methods=['GET','POST'])




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):
        return'Detail.GET'

    def post(self):
        return'Detail.POST'

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


if __name__ == '__main__':
    app.run()

(2)参数defaults

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
http://www.xx.com/index/
http://www.xx.com/index


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

#This can only be accessed
http://www.xx.com/index 

(4) redirect_to=None

Redirect to the specified address

@app.route('/index',methods=['GET','POST'],endpoint='index1',redirect_to="/index2")
def index():
    return'Company old website'

@app.route('/index2',methods=['GET','POST'],endpoint='index2',)
def index():
    return'Company's new website'

Visit: http://127.0.0.1:5000/index will be redirected directly to http://127.0.0.1:5000/index2

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)

@app.route('/')
def index():
    return render_template('index.html',func1=func1)

if __name__ =='__main__':

    app.run()

index.html

{{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__':
        app.run()

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'


@app.route('/get')
def get():
    data = get_flashed_messages()
    print(data)
    return'hello world'

@app.route('/set')
def set():
    #Set a value to somewhere
    flash('Access once, set once')
    return'hello world'

if __name__ =='__main__':
    app.run()

Visit: http://127.0.0.1:5000/set When one visits one, the value will be set once

 Visit: http://127.0.0.1:5000/get 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