我用flask和MySQL编写了一个crudpythonapi。源代码位于本地系统中,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或postgresql一样。 将其与类似sqlite的东西进行比较,sqlite是一个简单的基于文件的数据库系统
对它只有一个简单的要求——服务器必须可以从当前网络访问
这意味着几件事:
请看mysql manual,还有一些教程如何设置这个,简单的谷歌搜索应该可以工作
编辑: 至于您的代码示例,请参阅关于如何连接到服务器的flask_mysql文档,您可能最感兴趣的是
'MYSQL_HOST'
值,尽管所有其他值(user、pass、port、dbname)必须与服务器上配置的值相匹配相关问题 更多 >
编程相关推荐