微信小程序post请求Python Flask数据

1、微信小程序端:

(1)index.js

//index.js
//获取应用实例
const app = getApp()

Page({
  data: {
    motto: '检测结果:',
    value: '0',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    userImage: "/images/jia.png",
    img_arr: [],
  },
  //事件处理函数
  bindViewTap: function() {
    var that = this //!!!!!!!!!“搭桥”

    //利用API从本地读取一张图片
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        var tempFilePaths = res.tempFilePaths
        //将读取的图片替换之前的图片
        that.setData(
          { userImage: tempFilePaths[0],
            img_arr: that.data.img_arr.concat(tempFilePaths[0]),
          }
          )//通过that访问
          console.log(that.data.userImage)
      }
    })
  },
  changeName: function (e) {
    this.setData({
      value: "xiao",
    })

  },
  upload: function () {
    var that = this
   wx.uploadFile({
        url: 'http://127.0.0.1:8090/postdata',
        // filePath: that.data.img_arr[0],
        filePath: that.data.userImage,
        name: 'content',
        // formData: adds,
        success: function (res) {
          console.log(res.data);
          that.setData({
            value: JSON.parse(res.data)['value'],
            userImage: JSON.parse(res.data)['resurl']
          })
          
          if (res) {
            wx.showToast({
              title: '检测完成!',
              duration: 3000
            });
          }
        }
      })
    this.setData({
      formdata: ''
    })
  }, 
  takePhoto() {
    var that = this
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'],
      sourceType: ['camera'],
      success: function (res) {
        var tempFilePaths = res.tempFilePaths
        that.setData(
          {
            userImage: res.tempFilePaths[0],

          })
        console.log("res.tempImagePath" + tempFilePaths[0])
      }
    })
  },
  onLoad: function () {
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse){
      // 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }
  },
  getUserInfo: function(e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  }

 
  
})

(2)index.wxml

<!--index.wxml-->
<view class="container">
  <view class='imagesize'>
    <image src='{{userImage}}'></image>
    
  </view>
  <view class="usermotto">
    <text>{{motto}}</text>
    <text>{{value}}</text>
  </view>
  <view class='userbtn'>
        <button bindtap='bindViewTap'>选择图像</button>
        <button bindtap="takePhoto">相机拍照</button>
        <button bindtap="upload"> 开始检测 </button>
  </view>
</view>

(3)index.wxss

/**index.wxss**/
.imagesize{
 display:flex;
 width:100%;
 height: 800rpx;
 justify-content: center;
}
.imagesize image { 
  width:90%;
  height: 800rpx;
}

.usermotto {
  width:100%;
  height: 50rpx;
  text-align: left;
  margin-top: 100px;
}
.userbtn
{
   display:flex;
   width: 92%;
   margin-top: 20rpx;
   justify-content: center;
}
.userbtn button
{
   background-color: #ff8719;
   color: white;
   border-radius: 25rpx;
}

2、Python Flask端

from flask import  Flask
from flask import request
import json
import os
import uuid
import cv2

app = Flask(__name__)

@app.route("/")
def index():
    return "Hello"

resSets = {}
@app.route('/postdata', methods=['POST'])
def postdata():
    f = request.files['content']
    user_input = request.form.get("name")
    basepath = os.path.dirname(__file__)  # 当前文件所在路径
    src_imgname = str(uuid.uuid1()) + ".jpg"
    upload_path = os.path.join(basepath, 'static/srcImg/')
    if os.path.exists(upload_path)==False:
        os.makedirs(upload_path)
    f.save(upload_path + src_imgname)
    im = cv2.imread(upload_path + src_imgname, 0)
    save_path = os.path.join(basepath, 'static/resImg/')
    if os.path.exists(save_path) == False:
        os.makedirs(save_path)
    save_imgname = str(uuid.uuid1()) + ".jpg"
    cv2.imwrite(save_path + save_imgname, im)
    resSets["value"] = 10
    resSets["resurl"] = "http://127.0.0.1:8090" +'/static/resImg/' + save_imgname
    return json.dumps(resSets, ensure_ascii=False)



if __name__=="__main__":
    app.run(host="0.0.0.0", port=8090)

3、结果

 

使用Flask开发微信小程序后端的步骤如下: 1.安装Flask框架和微信开发工具包 ```shell pip install Flask pip install Flask-Wx ``` 2.创建Flask应用程序 ```python from flask import Flask, request from flask_wx import WxApp app = Flask(__name__) wxapp = WxApp(app) @app.route('/wechat', methods=['GET', 'POST']) def wechat(): if request.method == 'GET': return request.args.get('echostr', '') else: msg = wxapp.parse_message(request.data) return wxapp.response_text(msg, content='Hello, World!') ``` 3.配置微信公众号 在微信公众平台上配置服务器地址为`http://yourdomain.com/wechat`,并将Token设置为Flask应用程序中的Token。 4.运行Flask应用程序 ```shell export FLASK_APP=app.py flask run ``` 使用Tornado开发微信小程序后端的步骤如下: 1.安装Tornado框架和微信开发工具包 ```shell pip install tornado pip install tornado-wechat ``` 2.创建Tornado应用程序 ```python import tornado.ioloop import tornado.web from tornado_wechat import WeChatMixin, parse_message, response_text class WeChatHandler(tornado.web.RequestHandler, WeChatMixin): def prepare(self): self.parse_request_body() def get(self): self.write(self.get_argument('echostr')) def post(self): msg = parse_message(self.request.body) self.write(response_text(msg, content='Hello, World!')) app = tornado.web.Application([ (r'/wechat', WeChatHandler), ]) if __name__ == '__main__': app.listen(80) tornado.ioloop.IOLoop.current().start() ``` 3.配置微信公众号 在微信公众平台上配置服务器地址为`http://yourdomain.com/wechat`,并将Token设置为Tornado应用程序中的Token。 4.运行Tornado应用程序 ```shell python app.py ```
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

LoveWeeknd

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值