6. Flask请求和响应

一、请求相关信息

1. 请求参数

1. request.method    - 请求方法
2. request.args      - get请求的参数
3. request.form	     - post请求的参数
4. request.values    - 所有的请求参数
5. request.cookies
6. request.headers
7. request.path
8. request.full_path
9. request.script_root
10.request.url
11.request.base_url
12.request.url_root
13.request.host_url
14.request.host
15.request.remote_addr - 获取ip

2. 示例

1. 获取单个值 
    request.args.get('id')
    
2. 获取多个值
    request.args.getlist('ids')
    
3. 将参数转换为字典
    data = request.args
    data_dict = data.to_dict()
    
4. 获取文件
    f = request.files['the_file']
    f.save('/var/www/uploads/uploaded_file.txt')
    
5. 如果想要知道文件上传之前其在客户端系统中的名称,使用filename属性
    f = request.files['the_file']
    f.save('/var/www/uploads/' + secure_filename(f.filename))

二、响应相关信息

1. 返回模式

1. return '字符串' - 实际上是调用make_response

2. return render_template('html模板路径', {})

3. return redirect('/index.html')

4. jsonify - 返回json数据
    from flask import jsonify
    return jsonify(**dict)

2. make_response

1. 响应中加入信息,基于make_response

from flask import make_response, render_template
# response是flask.wrappers.Response类型

response = make_response(render_template('index.html'))
response.set_cookie('key', 'value')
response.delete_cookie('key')
response.headers['X-Something'] = 'A value'
from flask import Flask, make_response

app = Flask(__name__)

def auth_decorator(func):
    def inner(*args, **kwargs):
        print('装饰器')
        return func(*args, **kwargs)

    return inner

@app.route('/index', endpoint='index', methods=['GET'])
@auth_decorator
def index():
    response = make_response('index')
    response.headers['hhhh'] = 'asdsad'
    return response

if __name__ == '__main__':
    app.run()
posted @ 2020-04-06 12:58  qi.hu  阅读(170)  评论(0编辑  收藏  举报