欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

[python、flask] - POST请求

程序员文章站 2024-01-20 19:02:22
...

1. 微信小程序POST传递数据给flask服务器

  • 小程序端
// 提交POST数据
import { request } from "../../request/index.js"
  async handleDetectionPoints() {
    let params = {
      url: "/detect_points",
      data: {
        "points": arr,
        "img_name": this.canvasConfig.imgName
      },
      header: {},
      method: "POST"
    }
    let res = await request(params)
    console.log(res)
  }
  • 上面用到的request函数
// request/index.js

let ajaxTimes = 0

export const baseURL = "http://192.168.0.106:5000";

export const request = params => {
  let header = { ...params.header
  }
  ajaxTimes++;

  wx.showLoading({
    title: '加载中',
    mask: true
  })

  // 定义公共的URL
  params.url = baseURL + params.url

  return new Promise((resolve, reject) => {
    wx.request({
      ...params,
      header,
      success: result => {
        resolve(result)
      },
      fail: err => {
        reject(err)
      },
      complete: () => {
        ajaxTimes--
        if (ajaxTimes == 0) {
          wx.hideLoading()
        }
      }
    })
  })
}
  • flask端接收POST请求数据
from falsk import Flask, request

app = Flask(__name__)
@app.route("/detect_points", methods=["POST"])
def detect_points():
	print(request.json.get("points"))
	print(request.json.get("img_name"))
	return {
	  "msg": "ok"
	}

if __name__ == "__main__":
	app.run(host="192.168.0.106", port=5000)

[python、flask] - POST请求

2. python发送post数据给flask服务器

  • 拿上面的flask做为代理转发POST请求(JSON格式发送)
import json
@app.route("/detect_points", methods=["POST"])
def detect_points():
	payload = json.dumps({
		"points": request.json.get("points"),
		"img_name": request.json.get("img_name")
	})
	r = request.post("http://192.168.0.106:8888/detect_points")
	print(r.text)
	return{
		"msg": "ok"
	}
  • 接收JSON格式POST数据的服务端
from flask import Flask, request
import json

app = Flask(__name__)



@app.route("/detect_points", methods=["POST"])
def hello_world():
    print("来自5000")
    data  = request.get_data()
    print(data)
    data = json.loads(data.decode("utf-8"))
    print(data["img_name"])
    print(data["points"])

    return "Hello Marron1"



if __name__ == "__main__":
    app.run(host="192.168.0.106", port=8888)