zoukankan      html  css  js  c++  java
  • 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()
    

  • 相关阅读:
    Mac配置docker阿里云加速器
    Docker初学笔记
    Mac下载安装Tomcat
    MySQL
    monkey
    Git基本使用
    yaml语法
    PAT_B数素数 (20)
    PAT_B1002数字分类
    PAT基础编程练习
  • 原文地址:https://www.cnblogs.com/big-handsome-guy/p/8540578.html
Copyright © 2011-2022 走看看