简体   繁体   中英

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. 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.

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:

app.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:

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. A simple and typical way for retrieving data from database is to define an API for that. 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.

an API example in flask

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM