首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >微信小程序云开发+flask +连接本地mysql失败?

微信小程序云开发+flask +连接本地mysql失败?

提问于 2024-04-07 14:29:05
回答 0关注 0查看 10

微信云开发通过 flask 连接本地mysql数据库 把本地数据库导入云开发的云数据库,最后报错说是request 404 用cpolar穿透后 也验证了 可访问 不知道问题出在哪

flask

代码语言:text
复制
from flask import Flask, render_template, redirect, url_for, flash, request,jsonify
import mysql.connector
from mysql.connector import Error
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired
from flask_cors import CORS


app = Flask(__name__)
app.secret_key = 'your_secret_key'  # 用于 CSRF 保护
CORS(app)

# 数据库配置
db_config = {
    'host': 'localhost',
    'database': 'mydb3',
    'user': 'root',
    'password': '123456'
}

# 假设有一个名为 garbage 的表,其结构如下:
# CREATE TABLE `garbage` (
#   `id` INT AUTO_INCREMENT PRIMARY KEY,
#   `type` VARCHAR(255),
#   `name` VARCHAR(255)
# );

# 创建一个简易的表单类
class GarbageForm(FlaskForm):
    type = StringField('Type', validators=[DataRequired()])
    name = StringField('Name', validators=[DataRequired()])
    submit = SubmitField('Submit')

@app.route('/')
def home():
    return "Hello, Welcome to the App!"
# 返回JSON数据
@app.route('/api/get-garbage-data', methods=['GET','POST'])
def get_garbage_data_api():
    connection = None
    try:
        connection = mysql.connector.connect(**db_config)
        if connection.is_connected():
            dbcursor = connection.cursor()
            query = ("SELECT id, type, name FROM garbage")
            dbcursor.execute(query)
            data = dbcursor.fetchall()
            dbcursor.close()
            return jsonify(list(map(lambda x: {"id": x[0], "type": x[1], "name": x[2]}, data)))
    except Error as e:
        print(f"Error while connecting to MySQL: {e}")
        return jsonify({"status": "error", "message": str(e)}), 500
    finally:
        if connection is not None:
            connection.close()
# 主入口
if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0',port=5000)

微信小程序 云函数 index.js

代码语言:text
复制
// 云函数入口文件
const cloud = require('wx-server-sdk')
const axios = require('axios');

cloud.init({ env: "jingbao-jieshou-9gga02ap3da9654d"}) // 使用当前云环境

// 云函数入口函数
exports.main = async (event, context) => {
  try {
    const response = await axios.get('https://1ab91b21.r20.cpolar.top/api/get-garbage-data');
    if (response.status === 200) {
      const garbageData = response.data;

      const db = cloud.database();
      const result = await Promise.all(garbageData.map(item => {
        return db.collection('garbage').add({
          data: {
            type: item.type,
            name: item.name,
          }
        }).then(res => {
          return res._id; // 返回写入的记录ID
        }).catch(err => {
          console.error('写入数据库失败:', err);
          return null; // 返回null表示写入失败
        });
      }));

      console.log('数据成功保存到云数据库:', result);

      return {
        success: true,
        result: result.filter(id => id !== null), // 过滤掉写入失败的记录ID
        message: '数据已成功保存到云数据库'
      };
    } else {
      console.error('获取数据失败,HTTP状态码:', response.status);
      return {
        success: false,
        message: '获取数据失败,HTTP状态码:' + response.status
      };
    }
  } catch (e) {
    console.error('处理远程请求时发生错误:', e);
    return {
      success: false,
      message: '处理远程请求时发生错误:' + e.message
    };
  }
};
代码语言:text
复制
页面  index.js
// pages/index/index.js
Page({
  data: {
    garbageList: [],
    operationStatus: '',
    errorMessage: '',
    loading: true, // 页面加载状态,默认为 true
  },

  onLoad: function (options) {
    this.main();
  },

  main: function () {
    wx.cloud.callFunction({
      name: 'main',
      data: {}, // 传递给云函数的参数
    }).then(res => {
      if (res.result && res.result.success) {
        this.setData({
          operationStatus: 'success',
          garbageList: res.result.result,
          errorMessage: res.result.message || '',
          loading: false, // 数据加载完成,设置 loading 为 false
        });
        console.log('数据获取并保存成功:', res.result);
      } else {
        this.setData({
          operationStatus: 'error',
          errorMessage: res.result ? res.result.message : '未知错误',
          loading: false, // 数据加载完成,设置 loading 为 false
        });
        console.error('数据获取失败:', res.result ? res.result.message : '未知错误');
      }
    }).catch(err => {
      this.setData({
        operationStatus: 'error',
        errorMessage: '云函数调用失败:' + err.message,
        loading: false, // 数据加载完成,设置 loading 为 false
      });
      console.error('云函数调用失败:', err);
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})

最终报错

回答

和开发者交流更多问题细节吧,去 写回答
相关文章

相似问题

相关问答用户
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档