首页 > 解决方案 > 使用flask get方法从mysql数据库获取数据到ios应用程序的问题

问题描述

我正在尝试使用烧瓶的 http get 方法向我的 ios 应用程序发送一个包含我的整个 mysql 数据库的 josn 文件。当我调用我的服务器时,我收到此错误:

127.0.0.1 - - [29/May/2020 20:40:43] "GET / HTTP/1.1" 500 -
[2020-05-29 20:40:43,694] ERROR in app: Exception on / [GET]
Traceback (most recent call last):
  File "/Users/tjdalessandro/Desktop/ROOT/MEEP/PythonTests/app.py", line 52, in register
    result = mycursor.execute(result)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/mysql/connector/cursor_cext.py", line 234, in execute
    self._cnx.handle_unread_result()
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/mysql/connector/connection_cext.py", line 712, in handle_unread_result
    raise errors.InternalError("Unread result found")
mysql.connector.errors.InternalError: Unread result found 

我想知道如何修改以下 app.py 文件和 swift 文件以在我的 ios 应用程序中接收我的数据库的 json 文件

app.py(还包含一个工作后的方法)

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

#opens database connectionto "events" database
try:
    mydb = mysql.connector.connect(host="localhost", user="root", passwd="Pass", 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():

    if request.method == 'POST':
        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)

    elif request.method == 'GET':

        result = "SELECT * FROM events;"

        try:
           # Execute the SQL command
           result = mycursor.execute(result)
           # 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(jsonify(result=result), 200)

print("DB is closed")

数据提取器.swift

import Foundation
import SwiftUI

let apiUrl = "http://localhost:5000/"

class DataFetcher: ObservableObject {

    @Published var events: [eventdata] = []

    func fetchEvents(){
        events.removeAll()
        let url = NSMutableURLRequest(url: NSURL(string: apiUrl)! as URL)

        url.httpMethod = "GET"

        URLSession.shared.dataTask(with: url as URLRequest) { (data, response, err) in
            if let err = err {
                print(err.localizedDescription)
                return
            }

            guard let response = response as? HTTPURLResponse else { return }
            if response.statusCode == 200 {
                guard let data = data else { return }
                DispatchQueue.main.async {
                    do{
                        self.events = try JSONDecoder().decode([eventdata].self, from: data)
                    }catch let err {
                        print("Error: \(err)")
                    }
                }
            } else {
                print("HTTPURLResponse code: \(response.statusCode)")
            }
        }.resume()
    }
}

任何帮助将不胜感激!

标签: iosmysqljsonswiftflask

解决方案


推荐阅读