因此,我有一个需要从其自身内部的不同视图读取和写入mysql数据库的多个表的应用程序。我目前可以使用以下代码执行一个获取和发布请求:
from flask import Flask
from flask import make_response
from flask import request
import mysql.connector
#opens database connectionto "events" database
try:
mydb = mysql.connector.connect(host="localhost", user="root", passwd="correct horse battery staple", 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 flask.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 flask.request.method == 'GET':
return make_response("Success!", 200)
print("DB is closed")
假设我还需要从相同的数据库创建和访问一张用户表,但是在不同的视图中,如何通过修改此代码来做到这一点。还是使用Flask服务器和ios来实现这些结果。是否可以通过多个@ app.route指向类似/ users等网站的不同页面来实现此目的
最佳答案
route()
装饰器正在将函数绑定到URL
您还可以通过URL传递参数
@app.route('/users/<int:user_id>')
def show_user(user_id):
....
您已经使用创建了一条路线:
@app.route('/', methods=['GET', 'POST'])
def register():
....
如果您希望通过其他途径来获取和更新用户,则可以添加其他类似的功能@app.route('/users', methods=['GET', 'POST'])
def users():
....