Python VSCode 环境搭建


Flask请求

路由变量类型

type description
string (default) accepts any text without a slash
int accepts positive integers
float accepts positive floating point values
path like string but also accepts slashes
uuid accepts UUID strings

路径变量

from flask import url_for

@app.route('/user/<username>')
def profile(username):
    return f'{username}\'s profile'

print(url_for('profile', username='John')) # /user/John

请求方法

在route()里面指定methods

from flask import request

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

请求

request 对象对请求进行了解析。
比如request.method是请求的方法
request.form是post请求的表单
request.file是post请求所上传的文件
request.cookies获取到请求的cookie

form表单

from flask import request
@app.route('/login', methods=['POST', 'GET'])
def login():
    error = None
    if request.method == 'POST':
        if valid_login(request.form['username'],
                       request.form['password']):
            return log_the_user_in(request.form['username'])
        else:
            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)

文件上传

文件保存在request对象里面

from flask import request

@app.route('/upload', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        f = request.files['the_file']
        f.save('/var/www/uploads/uploaded_file.txt')

获取cookie

from flask import request

@app.route('/')
def index():
    username = request.cookies.get('username')

错误处理和重定向

from flask import abort, redirect, url_for
@app.route('/')
def index():****
    return redirect(url_for('login'))

@app.route('/login')
def login():
    abort(401)
    this_is_never_executed()

错误指定跳转到某个页面,errorhandler用于捕捉错误

from flask import render_template

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

响应

响应的类型必须是string, dict, tuple, Response instance, or WSGI callable。
|type|return|
|—|—|
|string|使用字符串和默认参数转化生成的响应对象|
|dict| dic 经过jsonify 转化后的响应对象|
|tuple|元组必须是这种格式(body, status, headers), (body, status), or (body, headers)才能被转化为响应对象|
|other|返回一个有效的WSGI应用对象转化而成的响应对象|


文章作者: 彭峰
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 彭峰 !
 上一篇
2021-07-29 彭峰
下一篇 
2021-07-24 彭峰
  目录