【问题标题】:Create Api for MySQL database and connect to mobile App using Python为 MySQL 数据库创建 Api 并使用 Python 连接到移动应用程序
【发布时间】:2018-11-04 09:29:50
【问题描述】:

我使用 React Native 开发了一个简单的应用程序,我正在尝试连接到数据库。我在网上查了一下,发现很多公司,比如 Facebook、Instagram、YouTube 等等都在使用 MySQL + Python。

我想使用 Python 来操作(插入/删除和更新)数据库,但为了做到这一点,我需要创建一个 API。使用 NodeJS + Express 我会做这样的事情:

    import express from 'express';
import mysql from 'mysql';

const app = express();

app.listen(port, ()=> {
  console.log('server started');
  // do stuff
});


//database
const database = mysql.createConnection({
  host : 'localhost',
  user : 'root',
  password : 'password12345',
  database : 'database_app'
});

//create 
app.get('/create', (req, res)=> {
  // check error
  // create query
});

//delete 
app.get('/delete', (req, res)=> {
  // check error
  // delete query
});

//update 
app.get('/update', (req, res)=> {
  // check error
  // update query
});

我如何用 Python 做同样的事情?以及如何将其连接到我的应用?

【问题讨论】:

    标签: python mysql node.js database


    【解决方案1】:

    您需要DjangoFlask 之类的东西来提供数据以供前端使用。

    在 Flask 中,您制作一个蓝图,然后使用该蓝图为路由提供服务,这类似于您在 Node.js 代码中所做的事情。

    app.get('/update', (req, res)=> {
      // check error
      // update query
    });
    

    Flask 版本如下所示:

    users_blueprint = Blueprint('users', __name__, template_folder='./templates')
    
    
    @users_blueprint.route('/users/', methods={'GET'})
    def getUsers():
      return jsonify({
        'status': 'success',
        'message': 'test response msg',
        'data' : mydata
      })
    

    您可以在注册用户蓝图并创建模型后使用这样的代码。

    【讨论】:

      【解决方案2】:

      首先,我没有强大的 Python 背景,但我知道人们使用 flask 来构建 REST API,并且您可以通过 URL 将 API 连接到您的应用程序,您只需要启动您的服务器并在您的 RN 应用程序fetch 的客户端中,来自安装了 REST API 的 URL(在开发模式下,可能通过 localhost:$PORT)中的数据。

      【讨论】:

      • 这不是用普通python用mysql库就能实现的吗?
      猜你喜欢
      • 1970-01-01
      • 2019-03-08
      • 2021-03-17
      • 1970-01-01
      • 2020-11-02
      • 1970-01-01
      • 2012-11-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多