我用烧瓶和 MySQL 编写了一个 CRUD Python API。源代码位于本地系统,MySQL 数据库位于真实网络主机上。
是否可以将本地 python 代码连接到真实网络主机上的 MySQL?
这是 config.py
from app import app
from flask_mysqldb import MySQL
mysql = MySQL()
app.config['MYSQL_HOST'] = 'http://test.com:5000'
app.config['MYSQL_USER'] = 'guest'
app.config['MYSQL_PASSWORD'] = '12345'
app.config['MYSQL_DB'] = 'school'
mysql.init_app(app)
主要.py:
from flask import request, jsonify, redirect, url_for
from app import app
from config import MySQL
@app.route('/list')
def home():
try:
cursor = mysql.connection.cursor()
cursor.execute("SELECT * FROM student")
row_headers = [x[0] for x in cursor.description]
studentsRows = cursor.fetchall()
json_data = []
for result in studentsRows:
json_data.append(dict(zip(row_headers, result)))
response = jsonify(student_list=json_data, status=120)
response.status_code = 200
return response
except Exception as e:
print(e)
@app.errorhandler(404)
def not_found(error=None):
message = {
'status': 404,
'message': 'Record not found: ' + request.url,
}
response = jsonify(message)
response.status_code = 404
return response
if __name__ == '__main__':
app.run(host="0.0.0.0")