【发布时间】:2021-03-31 07:35:59
【问题描述】:
我使用烧瓶和 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)
main.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")
【问题讨论】:
-
是什么阻止您将主机更改为真实的网络主机?
-
代码位于本机但Mysql数据库位于真实主机。我想在本地调试和测试我的代码。可能吗?还是我必须将 Python 部署到真正的主机上?
-
当然可以,只要您的生产数据库防火墙没有阻止您的 ip
标签: python mysql flask server pycharm