我正在尝试访问一个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函数中应该放什么参数。
任何见解将不胜感激。
1条答案
按热度按时间py49o6xq1#
为了从SwiftUI应用程序接收POST请求,您需要运行一个类似flask的python Web服务器。
1.创建一个python模块(文件),如下所示:
app.py
2.确保安装了所需的库:
您需要确保MySQL数据库已启动,并且在代码中填写了数据库的真实的凭据。(默认MySQL端口= 3306)
3.启动 flask 开发Web服务器
您的服务器应启动于:
http://localhost:5000
将swift代码示例中的:
http://YOUR FILE PATH
替换为http://localhost:5000/
和viola!更新:我测试了这个,它的工作。下面是我在postman中生成的swiftUI代码: