[flask notes] Basic

Time:2020-5-30

preface

Some time ago, flask was used to write microservices. Later, spring boot was used, so it was useless. Now I want to review and improve it by taking notes while reading official documents.

Basic process of Web Framework:

-Client initiates HTTP request
-The web application finds the corresponding processing function according to the URL route 
-Analyze the data passed in the request
-Return to client response

Flask snooping

1. Create a flask web application

from flask import Flask,
app = Flask(__name__)

2. Route routing setting & request mode

@app.route('/', method=['POST', 'GET'])
def handle():
    pass

3. HTTP request request parameter analysis

@app.route('/', method=['POST', 'GET'])
def handler():
    args =  request.args         #Parameters following the URL
    form =  request.form         #Form form parameters
    data =  request.get_ Json() (request body parameter)
    file =  request.files        #File data

4. HTTP response basic form

You can use (response, state_ Code)

@app.route('/')
def handler():
    #1. return to the rendered template
    response = render_template('index', name=name))
    #2. Return string
    response = 'hello...'
    #3. Return the jsonify of the object 
    response = jsonify([1, 2, 3])

5. HTTP request request redirection

@app.route('/')
def handler():
    # url_ For ('a ') returns the route address of the function named a
    return redirect(url_for('login'))
@app.route('/')
def handler():
    abort(404)

6. HTTP status exception handling

@app.errorhandler(404)
def page_not_found(error):
    return render_template('page_not_found.html'), 404

7. HTTP Cookies

@app.route('/')
def handler():
    #Get cookies
    username = request.cookies.get('username')
    
    #Set cookies
    resp = make_response(render_template(...))
    resp.set_cookie('username', 'the username')
    return resp

8. HTTP Session

@app.route('/')
def handler():
    session.get('username', None)
    session.pop('username', None)
    return redirect(url_for('index'))

9. Flask Flashed

@app.route('/login', methods=['GET', 'POST'])
def login():
    error = None
    if request.method == 'POST':
        if request.form['username'] != 'admin' or \
           request.form['password'] != 'secret':
            error = 'Invalid credentials'
        else:
            #"Buffer page" to jump on page
            flash('You were successfully logged in')
            return redirect(url_for('index'))
    return render_template('login.html', error=error)

10. Flask Log

app.logger.dubug()
app.logger.warning()
app.logger.error()

reference resources

https://dormousehole.readthed…

Recommended Today

Looking for frustration 1.0

I believe you have a basic understanding of trust in yesterday’s article. Today we will give a complete introduction to trust. Why choose rust It’s a language that gives everyone the ability to build reliable and efficient software. You can’t write unsafe code here (unsafe block is not in the scope of discussion). Most of […]