Fork me on GitHub

Flask的请求与响应

Flask的请求与响应


1 请求相关信息

request.method   # 请求方法
request.args      # get 请求的参数
request.form      # post请求的参数
request.values  # 所有的请求参数

          request.args.get('id')
          request.args.getlist('ids')    # 获取多个值

      data = request.args
      data_dict = data.to_dict()     # 通过to_dict() 方法 转化成 字典

      from urllib.parse import urlencode,quote,unquote
      url = urlencode(data_dict)    # 转换成 url
          quote -->> url编码

request.cookies
request.headers
request.path
request.full_path
request.script_root
request.url
request.base_url
request.url_root
request.host_url
request.host
    
    # 获取 ip
    request.remote_addr

    # 文件
request.files
obj = request.files['the_file_name']
obj.save('/var/www/uploads/' + secure_filename(f.filename))

2 响应相关信息

(1)return "字符串" 实际上是调用make_response

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

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

(4)jsonify 返回json数据

from flask import jsonfy

return jsonfy(**dict)

(5)响应中加入信息,基于make_response

from flask import make_response

response = make_response(render_template('index.html'))

        response是flask.wrappers.Response类型

response.set_cookie('key', 'value')
response.delete_cookie('key')

response.headers['X-Something'] = 'A value'

return response

小例子

from flask import Flask,views,redirect,url_for,make_response,jsonify

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 @ 2018-03-10 16:41  派对动物  阅读(1376)  评论(0编辑  收藏  举报
Top