如何使用Python而不是PHP连接iOS应用程序与MySQL数据库

cwtwac6a  于 2023-04-28  发布在  PHP
关注(0)|答案(1)|浏览(93)

我正在尝试访问一个ios应用程序中的mysql数据库,我想用python在我的应用程序中调用数据库时读写。
PHP Code I would like to turn into a python script
我不知道如何使用mysql-connector从我的应用程序中写入或读取数据。我相信这是用$_POST[a]完成的;但我不知道如何使用Python获得相同的结果。
我也有一个样本,我是如何试图发送数据从我的应用程序到我的数据库写在swiftui。
'''

import Foundation
import SwiftUI

struct CreateEventButton: View {
    @State private var isPresentedEvent = false
    @State private var eventid: Int = 0
    @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://YOUR FILE PATH")! 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 
        }, label: {
            Text("Create Event")})
                .foregroundColor(.secondary)
                .background(Color(.secondarySystemBackground))
                .cornerRadius(50.0)
                .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)")
                    //send()
                    }, label: {
                        Text("Create Event")
                    })
                Button(action: {
                    self.isPresentedEvent.toggle()
                   }, label: {
                       Text("Cancel")
                   })
                }
                Text("Create Event Button (Non Functional)").padding()
            }
        } )
     }
}

'''
我不确定在这里创建的sender函数中应该放什么参数。
任何见解将不胜感激。

py49o6xq

py49o6xq1#

为了从SwiftUI应用程序接收POST请求,您需要运行一个类似flask的python Web服务器。

1.创建一个python模块(文件),如下所示:

app.py

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

server_name = "localhost"
username = "flask"
password = "flask"
dbname = "flask"

# Create and check connection
try:
    conn = mysql.connector.connect(
        host=server_name,
        user=username,
        passwd=password,
        database=dbname
    )
    print("Connection OK")
except e:
    print("Connection failed: ", e)

mycursor = conn.cursor()

app = Flask(__name__)

@app.route('/', methods=['POST'])
def register():
    name = request.form['a']
    age = request.form['b']

    sql = "INSERT INTO users (name, age) VALUES (%s, %s)"
    val = (name, age)

    try:
        mycursor.execute(sql, val)
        conn.commit()
        conn.close()
    except e:
        print("Error: ", e)

    return make_response("Success!", 200)

2.确保安装了所需的库:

pip install flask
pip install mysql-connector-python

您需要确保MySQL数据库已启动,并且在代码中填写了数据库的真实的凭据。(默认MySQL端口= 3306)

3.启动 flask 开发Web服务器

export FLASK_APP=app.py # OR set FLASK_APP=app.py (for Windows)
python -m flask run

您的服务器应启动于:http://localhost:5000
将swift代码示例中的:http://YOUR FILE PATH替换为http://localhost:5000/和viola!
更新:我测试了这个,它的工作。下面是我在postman中生成的swiftUI代码:

import Foundation

var semaphore = DispatchSemaphore (value: 0)

let parameters = "a=Lance&b=35"
let postData =  parameters.data(using: .utf8)

var request = URLRequest(url: URL(string: "http://localhost:5000/")!,timeoutInterval: Double.infinity)
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")

request.httpMethod = "POST"
request.httpBody = postData

let task = URLSession.shared.dataTask(with: request) { data, response, error in 
  guard let data = data else {
    print(String(describing: error))
    return
  }
  print(String(data: data, encoding: .utf8)!)
  semaphore.signal()
}

task.resume()
semaphore.wait()

相关问题