Basic knowledge of Flask

Keywords: Python Session JSON Django

Introduction:

Flask is based on python and relies on jinjia2 and werkzeug WSGI services as a micro framework

Werkzeug is essentially a Socket server, which is used to receive http requests and preprocess them, then trigger the Flask framework,

Developers process the request based on the functions provided by the Flask framework and return it to the user. If they want to return complex content to the user,

We need to use jinjia2 template to process the template, that is, rendering the template and data, and then returning the string to the user

We use python to write Web services directly. For the rest of the TCP connections, the original HTTP request and response formats need a unified interface protocol,

This interface is wsgi (Web Server Gateway Interface), and wsgiref is the service module developed by python based on wsgi protocol. The code is as follows:

from wsgiref.simple_server import make_server

def mya(environ, start_response):
    print(environ)
    start_response('200 OK', [('Content-Type', 'text/html')])
    if environ.get('PATH_INFO') == '/index':
        with open('index.html','rb') as f:
            data=f.read()

    elif environ.get('PATH_INFO') == '/login':
        with open('login.html', 'rb') as f:
            data = f.read()
    else:
        data=b'<h1>Hello, web!</h1>'
    return [data]

if __name__ == '__main__':
    myserver = make_server('', 8011, mya)
    print('Monitor 8010')
    myserver.serve_forever()

wsgiref Simple application

//In fact, we are rewriting the function of mya when we write the code of flask

 

 

1. Install Flask:

pip install flask

2.Werkzeug

Werkzeug is a toolkit of WSGI, which can be used as the bottom Library of web framework

code:

from werkzeug.wrappers import Request, Response

@Request.application
def hello(request):
    return Response('Hello World!')

if __name__ == '__main__':
    from werkzeug.serving import run_simple
    run_simple('localhost', 4000, hello)

 

3. Simple use of flash

from flask import Flask
# Instantiation produces a Flask object
app = Flask(__name__)
# take '/'And view functions hello_workd The corresponding relationship of is added to the route,flask All routes are added to the decoration
@app.route('/') # 1. v=app.route('/') 2. v(hello_world)
def hello_world():
    return 'Hello World!'

if __name__ == '__main__':
    app.run() # Finally called run_simple()

 

Example: login, display user information

Main file (xxx.py):

from flask import Flask,render_template,request,redirect,session,url_for
app = Flask(__name__)
app.debug = True
app.secret_key = 'sdfsdfsdfsdf'

USERS = {
    1:{'name':'Zhang San','age':18,'gender':'male','text':"Thousands of roads"},
    2:{'name':'Li Si','age':28,'gender':'male','text':"Safety first"},
    3:{'name':'Wang Wu','age':18,'gender':'female','text':"Nonstandard driving"},
}

@app.route('/detail/<int:nid>',methods=['GET'])
def detail(nid):
    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():
    user = session.get('user_info')
    if not user:
        # return redirect('/login')
        url = url_for('l1')
        return redirect(url)
    return render_template('index.html',user_dict=USERS)


@app.route('/login',methods=['GET','POST'],endpoint='l1')
def login():
    if request.method == "GET":
        return render_template('login.html')
    else:
        # request.query_string
        user = request.form.get('user')
        pwd = request.form.get('pwd')
        if user == 'cxw' and pwd == '123':
            session['user_info'] = user
            return redirect('http://www.baidu.com')
        return render_template('login.html',error='Wrong user name or password')

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

 

 

front end:

Three front-end values:

①dic.name

②dic['name']

③dic.get('name')

 

html file:

detail.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>detailed information {{info.name}}</h1>
    <div>
        {{info.text}}
    </div>
</body>
</html>

 

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>detailed information {{info.name}}</h1>
    <div>
        {{info.text}}
    </div>
</body>
</html>

 

 

login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>User login</h1>
    <form method="post">
        <input type="text" name="user">
        <input type="text" name="pwd">
        <input type="submit" value="Sign in">{{error}}
    </form>
</body>
</html>

 

4. Configuration file of flask:

 {
        'DEBUG':                                get_debug_flag(default=False),  Open or not Debug Pattern
        'TESTING':                              False,                          Whether to turn on 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,
    }

 

 

When configuring the above configuration, write in the function of the main file:

Law 1:

   app.config['DEBUG'] = True
   
   app.debug=True Also do
    
   PS:  Because Config Objects are essentially dictionaries, so you can also use app.config.update(...)

 

Method 2:

#adopt py File configuration
app.config.from_pyfile("python File name")
//Such as:
settings.py
DEBUG = True

app.config.from_pyfile("settings.py")
#Configuration through environment variables
app.config.from_envvar("Environment variable name")
#app.config.from_pyfile(os.environ['YOURAPPLICATION_SETTINGS'])
The value of the environment variable is python File name name, internal call from_pyfile Method

app.config.from_json("json File name")
JSON File name, must be json Format, because internal execution json.loads

app.config.from_mapping({'DEBUG': True})
//Dictionary format

app.config.from_object("python Class or path to class")

app.config.from_object('pro_flask.settings.TestingConfig')

settings.py


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


PS: from sys.path Path already exists in start write

PS: settings.py File default path to be placed in program root_path Table of contents, if instance_relative_config by True,That is instance_path Table of contents( Flask object init Method)

 

5.flask routing

Standard syntax:
    @app.route('/detail/<int:nid>',methods=['GET'],endpoint='detail')

Default converter

DEFAULT_CONVERTERS = {
    'default':          UnicodeConverter,
    'string':           UnicodeConverter,
    'any':              AnyConverter,
    'path':             PathConverter,
    'int':              IntegerConverter,
    'float':            FloatConverter,
    'uuid':             UUIDConverter,
}

 

Nature of routing system:

"""
1. decorator = app.route('/',methods=['GET','POST'],endpoint='n1')
    def route(self, rule, **options):
        # app object
        # rule= /
        # options = {methods=['GET','POST'],endpoint='n1'}
        def decorator(f):
            endpoint = options.pop('endpoint', None)
            self.add_url_rule(rule, endpoint, f, **options)
            return f
        return decorator
2. @decorator
    decorator(index)
"""
#Empathy
def login():
    return 'Sign in'
app.add_url_rule('/login', 'n2', login, methods=['GET',"POST"])
#And django Similar routing
#django And flask route: flask Routing is based on decorator, and its essence is based on: add_url_rule
#add_url_rule In the source code, endpoint If empty, endpoint = _endpoint_from_view_func(view_func),Final take view_func.__name__(Function name)

 

6. Formwork

Rendering variables:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>User list</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>
</body>
</html>


Variable cycle:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>User list</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>
</body>
</html>


Logical judgment:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>User list</h1>
    <table>
        {% if name %}
          <h1>Hello {{ name }}!</h1>
        {% else %}
          <h1>Hello World!</h1>
        {% endif %}
    </table>
</body>
</html>

 

Parameter passing: directly add comma in the slogan after return, and write the parameter directly

Master file:
from flask import Flask,render_template,Markup,jsonify,make_response
app = Flask(__name__)

def func1(arg):
    return Markup("<input type='text' value='%s' />" %(arg,))
    #Markup and django Of make_safe equally
@app.route('/')
def index():
    return render_template('index.html',ff = func1)#parameter func1 It's passed on

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

    
    
 html In file:
    
 <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

    {{ff('65')}}  #Use ff variable
    {{ff('65')|safe}}

</body>
</html>

 

extends,include and django are the same

7. Request 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 relevant information
        # request.method  Method of submission
        # request.args  get Requested data
        # request.form   post Requested data
        # request.values  post and get Total submitted data
        # request.cookies  Brought by the client cookie
        # request.headers  Request header
        # request.path     Without domain name, request path
        # request.full_path  Request path without domain name and with parameters
        # request.script_root  
        # request.url           Request path with domain name and parameters
        # request.base_url        With domain name request path
        # request.url_root      domain name
        # request.host_url        domain name
        # request.host            127.0.0.1:500
        # request.files
        # obj = request.files['the_file_name']
        # obj.save('/var/www/uploads/' + secure_filename(f.filename))

        # Response related information
        # return "character string"
        # return render_template('html Template path',**{})
        # return redirect('/index.html')
        #return jsonify({'k1':'v1'})

        # response = make_response(render_template('index.html'))
        # response yes 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()

Posted by lessthanthree on Tue, 28 Apr 2020 01:53:50 -0700