zoukankan      html  css  js  c++  java
  • Flask HTTP请求与响应

    设置请求 POST GET

    设置post和get,在route中设置methods参数,除了post,get,还有put ,delete 等

      @app.route('/http_test', methods=['GET', "POST"])

    1 from flask import Flask, url_for, request
    2 @app.route('/http_test', methods=['GET', "POST"]) # 如果没有methods参数,默认只支持get,必须大写
    3 def http_test():
    4     if request.method == 'POST':
    5         print('post')
    6         return 'post'
    7     elif request.method == "GET":
    8         print("GET")
    9         return 'GET'

    获取请求参数

    参数形式包括 from data,json,get的path参数

    from flask import Flask, url_for, request
    @app.route('/http_test1', methods=["GET", "POST"])
    def http_test1():  # post参数{"name":"666"},application/json
        if request.method == 'POST':
            # request.data
            print(request.data)  # b'{"name":"666"}'
            print(type(request.data))  # <class 'bytes'>
            # request.json
            print(request.is_json)  # True
            print(request.json)  # {"name":"666"}
            print(type(request.json))  # <class 'dict'>
            return 'post'
    总结就是:
    request.form.get("xxx") #获取form 数据
    request.args.get("xxx") #获取path 数据
    request.json.get("xxx") #获取json 数据
    request.data #二进制数据
    request.headers.get("z") #获取header数据
    request.is_json() #判断是否是json 数据

    返回响应

    常见返回

    1.return + "String" ,实际上是会调用make_response
    
    2.return + render_template("path/to/temaplate",{}),返回模版
    
    3.return + redirect #重定向,常常与url_for联合用
      return redirect(url_for(view_func))# 重定向到某个视图,url_for为获取视图路径的函数
    4.return + jsonify(**dict) 返回json数据
    flask 可配置返回函数make_response
    def index():
        response = make_response(render_template('index.html', foo=42)) #等效于直接render_template('index.html', foo=42)
        response.headers['X-Parachutes'] = 'parachutes are cool'# 编辑response_headers 信息
        response.set_cookie('key', 'value') #设置session
        response.delete_cookie('key')
        return response
  • 相关阅读:
    简化SpringBoot框架打包体积
    深究1.8版本HashMap源码
    一次面试题,将 字符串 保存在 Byte 数组中
    记一次linux磁盘清理
    Alibaba Cloud Toolkit 使用心得(IDEA版)
    Mybatis 一对多分页踩坑 对collection的分析
    MySQL中update修改数据与原数据相同会再次执行吗?
    与 MySQL 因“CST” 时区协商误解导致时间差了13 小时
    Druid数据源
    mybatis自动生成代码 mybatis-generator
  • 原文地址:https://www.cnblogs.com/guoguojj/p/11543803.html
Copyright © 2011-2022 走看看