Flask之request对象

概述


本文介绍request对象,在web开发中,都会有request对象的概念,表示 浏览器 向 服务器 发出的请求,将 请求信息 封装到request对象中

导入request

from flask import request

request对象封装的信息

属性名 说明
args 封装GET请求参数,获取方式 request.args.get('id')
form 封装POST请求参数,获取方式 request.form.get('name')
method 浏览器发请求的方法,如:GET或者POST
url 请求的url
files 上传文件
cookies 封装cookie信息,dict类型
headers 封装请求头信息
data 获取未经处理过的原始数据,如果浏览器发来的数据格式是json的,则data是json字符串,排序和请求参数一致
get_json() 当浏览器发来的数据格式是json时,使用该方法,返回 dict类型

request对象封装url的信息

假设浏览器访问url:http://127.0.0.1:5000/static/a/b/c/e.html?name=1

属性名 说明
request.path /static/a/b/c/e.html
request.base_url http://127.0.0.1:5000/static/a/b/c/e.html
request.url http://127.0.0.1:5000/static/a/b/c/e.html?name=1
request.url_root http://127.0.0.1:5000/

感受GET请求

# coding=utf-8

from flask import Flask,request

app = Flask(__name__)

@app.route('/article',methods=['GET','POST'])
def article():
    print('-'*50)
    print('id:',request.args.get('id'))
    print('method:',request.method)
    print('url:',request.url)
    print('cookies:',request.cookies)
    print('headers-------------')
    print(request.headers)
    return 'Hello, World!'

if __name__ == "__main__":
    app.run(debug=True)

操作如下图:
打开浏览器,在地址栏里输入http://127.0.0.1:5000/?id=2,是GET请求,只能通过request.args获取 URL 上的参数,
打印如下:

感受POST请求

html代码
在浏览器中只有通过表单才能发送POST请求,编写登录页面如下:

<form action="/login" method="post">
    用户名: <input type="text" name="username"><br/>
    密码: <input type="password" name="password"><br/>
    <input type="submit" value="登录">
</form>

要指定method="post",否则仍然是 GET 请求

python代码

# coding=utf-8

from flask import Flask,request

app = Flask(__name__)

@app.route('/login',methods=['POST'])
def login():
    print('-'*50)
    print('username:',request.form.get('username'))
    print('password:',request.form.get('password'))
    print('method:',request.method)
    print('url:',request.url)
    print('cookies:',request.cookies)
    print('headers-------------')
    print(request.headers)
    return '登录'

if __name__ == "__main__":
    app.run(debug=True)

打印如下:

username: mayumin
password: 12345
method: POST
url: http://127.0.0.1:5000/login
cookies: {}
headers-------------
Host: 127.0.0.1:5000
Connection: keep-alive
Content-Length: 31
Cache-Control: max-age=0
Origin: http://127.0.0.1:5000
Upgrade-Insecure-Requests: 1
Content-Type: application/x-www-form-urlencoded
User-Agent: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3
Referer: http://127.0.0.1:5000/static/login.html
Accept-Encoding: gzip, deflate, br
Accept-Language: zh-CN,zh;q=0.9,en;q=0.8

处理浏览器发来json数据

前端代码:
https://www.malaoshi.top/show_1IX71XNeq3C3.html

<script src="js/jquery-1.11.0.js"></script>

<script>
function login(){
    $.ajax({
        url:'http://127.0.0.1:5000/login',   
        type:'post', // 必须是post请求
        data: JSON.stringify({ //发给服务器端的数据,必须将json数据转成字符串
            username:"admin",
            password:"admin"
        }),
        contentType : "application/json", // 必须指定提交json格式数据
        xhrFields: { // 带上cookie,不携带则删除
            withCredentials: true
        },
        dataType:'json',//服务器端返回的数据格式是json
        success:function(data){   //data:服务器端返回给浏览器端的数据
            console.log(data);
        },
        error:function (XMLHttpRequest, textStatus, errorThrown) {
            alert(XMLHttpRequest.responseText);
            // alert(textStatus);
            // console.log(errorThrown);
        }
       });
}
login();//加载页面后直接调用init()函数
</script>

flask代码:

@app.route('/login',methods=['POST'])
def login():
    # data_str = request.data.decode('utf-8')
    # path_obj = json.loads(data_str)
    path_obj = request.get_json()
    username = path_obj['username']
    password = path_obj['password']

原文出处:/show_1EF3URsgIbjI.html