简体   繁体   English

如何使用 flask 脚本将 mysql 数据库连接到我的 ios 应用程序

[英]How to use flask script to connect mysql data base to my ios app

I have an app with which I can write data to my database but cannot read data from the database.我有一个应用程序,我可以使用它将数据写入我的数据库,但不能从数据库中读取数据。 I'd like to be able to send data from the database to my app whenever I want which I think is done by the get and post http methods in flask.我希望能够随时将数据从数据库发送到我的应用程序,我认为这是通过 flask 中的 get 和 post http 方法完成的。 Should this be done with the same script or separate scripts?这应该使用相同的脚本还是单独的脚本来完成? If separate scripts, how should I go about writing them?如果单独的脚本,我应该如何编写它们? If not I am not sure what to add to my swift and python files.如果不是,我不确定要向我的 swift 和 python 文件添加什么。

The code I am working with uses flask and mysql-connector to make database connections, any help modifying to read data from the database would be greatly appreciated:我正在使用的代码使用 flask 和 mysql-connector 进行数据库连接,任何修改以从数据库读取数据的帮助将不胜感激:

app.py应用程序.py

from flask import Flask
from flask import make_response
from flask import request
import mysql.connector

#opens database connectionto "events" database
try:
    mydb = mysql.connector.connect(host="localhost", user="root", passwd="Proteus^5", database = "events")
    print("Connection OK")

except e:
    print("Connection failed: ", e)
#prepare a cursor object using cursor() method

mycursor = mydb.cursor()

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def register():
    event_id = request.form['a']
    poi = request.form['b']
    address = request.form['c']
    start_time = request.form['d']
    end_time = request.form['e']

    sql = "INSERT INTO events (event_id, poi, address, start_time, end_time) VALUES (%s, %s, %s, %s, %s)"
    val = (event_id, poi, address, start_time, end_time)


    try:
       # Execute the SQL command
       mycursor.execute(sql, val)
       # Commit your changes in the database
       mydb.commit()
       mydb.close()
    except e:
       # Rollback in case there is any error
       print("Error: ", e)
       mydb.rollback()

    return make_response("Success!", 200)

print("DB is closed")

swift file that sends data to database on a button press: swift 文件在按下按钮时将数据发送到数据库:

import Foundation
import SwiftUI

 struct CreateEventButton: View {
    @State private var isPresentedEvent = false
    @State private var eventid: Int = 3
    @State private var eventName: String = ""
    @State private var eventDescription: String = ""
    @State private var selectedStartTime = Date()
    @State private var selectedEndTime = Date()
    @Binding var annotationSelected: Bool

    func send(_ sender: Any) {
        let request = NSMutableURLRequest(url: NSURL(string: "http://localhost:5000/")! as 
URL)
            request.httpMethod = "POST"

        let postString = "a=\(self.eventid)&b=\(self.eventName)&c=\. 
 (self.eventDescription)&d=\. 
    (self.selectedStartTime)&e=\(self.selectedEndTime)"


            request.httpBody = postString.data(using: String.Encoding.utf8)

            let task = URLSession.shared.dataTask(with: request as URLRequest) {
                data, response, error in

                if error != nil {
                    print("error=\(String(describing: error))")
                    return
                }

                print("response = \(String(describing: response))")

                let responseString = NSString(data: data!, encoding: 
String.Encoding.utf8.rawValue)
                print("responseString = \(String(describing: responseString))")
            }
            task.resume()

            self.eventName = ""
            self.eventDescription = ""
            self.selectedStartTime = Date()
            self.selectedEndTime = Date()
        }



    var body: some View {

      Button(action: {
            self.isPresentedEvent.toggle() //trigger modal presentation
        }, label: {
            Text("Create Event").font(.system(size: 18))
            }).padding(EdgeInsets(top: 8, leading: 6, bottom: 8, trailing: 6
                .sheet(isPresented: $isPresentedEvent, content:{
            VStack{
                TextField("Event Name", text: self.$eventName).padding()
                TextField("Event Description", text: self.$eventDescription).padding()
                Form {
                    DatePicker("When your event starts: ", selection: 
self.$selectedStartTime, 
    in: Date()...)
                }
                Form {
                    DatePicker("When your event ends:   ", selection: self.$selectedEndTime, 
in: 
    Date()...)
                }
                HStack{
                Button(action: {
                    self.isPresentedEvent.toggle()
                    self.annotationSelected = false
                    self.eventid += 1
                    print("Start: \(self.selectedStartTime)")
                    print("End: \(self.selectedEndTime)")
                    self.send((Any).self)
                    }, label: {
                        Text("Create Event")
                    })
                Button(action: {
                    self.isPresentedEvent.toggle()
                   }, label: {
                       Text("Cancel")
                   })
                }
                Text("Create Event Button (Non Functional)").padding()
            }
        } )
     }
}

I do not know anything about swifts but I have worked with flask.我对 swifts 一无所知,但我使用过 flask。 A simple and typical way for retrieving data from database is to define an API for that.从数据库中检索数据的一种简单而典型的方法是为此定义一个 API。 In this API you query the database (eg Select * From user Where user_id =... ) and then serialize the results (convert retrieved data from database in a form that is proper for sending to the client application. eg create a dictionary/json object) and send the response to the client.在此 API 中,您查询数据库(例如Select * From user Where user_id =... ),然后序列化结果(将检索到的数据从数据库转换为适合发送到客户端应用程序的形式。例如创建字典/json object) 并将响应发送给客户端。

an API example in flask flask 中的 API 示例

@app.route('.../get_user', methods=['GET'])
def get_user_api:
   # query database
   data = { 'username': username,
            'level: level,
            ...
           }
   return data, 200

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 SQLAlchemy 将数据库连接到我们的 flask 应用程序 - How to connect data base to our flask app using SQLAlchemy 如何使用 mysql 数据库 dockerize 我的 Flask web 应用程序? 无法连接 mysql 并且找不到渲染模板 - How to dockerize my flask web app with mysql database?Cannot connect mysql and cannot found render templete 如何将我的 flask 应用程序连接到 MongoDB(VSCode)? - How to connect my flask app to MongoDB (VSCode)? 如何让我的 Python Flask 应用程序在 Ubuntu ec2 上连接到 Z62A94414B4591DCCABB762A9414B45946A - How do I get my Python Flask app on an Ubuntu ec2 to connect with a MySQL db with RDS? 如何使用SQLAlchemy将远程MySQL数据库连接到flask应用程序? - How to connect remote mySQL db to flask app using SQLAlchemy? 如何在我的 flask 应用程序中连接浏览器的麦克风? - How do I connect browser's microphone in my flask app? 如何将我的 fastai model 与我的 flask 应用程序一起使用? - How can I use my fastai model with my flask app? 如何使用 Python 代替 Z2FEC392304A54C23AC138FDA22 将 ios 应用程序与 mysql 数据库连接 - How to Connect an ios App With mysql Database Using Python Instead of PHP 如何从Flask应用程序中的MySQL查询返回数据? - How to return data from a MySQL query in a Flask app? 如何使用 flask 应用程序中的 MySQL 将用户输入的数据存储在我的数据库中。 我收到一个错误 - How to store data in my database from a user Input using MySQL in flask app. I am getting an Error
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM