从输入创建 SQLAlchemy mysql 连接字符串
Posted
技术标签:
【中文标题】从输入创建 SQLAlchemy mysql 连接字符串【英文标题】:Create SQLAlchemy mysql connection string from input 【发布时间】:2021-07-08 07:08:09 【问题描述】:我是 python 新手。我正在尝试创建一个到 mysql 的连接字符串,但是通过 webform 输入。 我的第一个想法是创建一个函数来调用以传递详细信息。这是我所拥有的:
from flask import Flask, render_template, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
import pymysql
app = Flask(__name__)
def db_connection(user, password, ep, db):
connection = f"mysql+pymysql://user:password@ep/db"
app.config['SQLALCHEMY_DATABASE_URI'] = connection
app.config['SQLALCHEMY_TRACK_MODIFICATION'] = False
db = SQLAlchemy(app)
class Lab(db.Model):
id = db.Column(db.Integer, primary_key=True)
store = db.Column(db.String(80), unique=True, nullable=False)
item = db.Column(db.String(120), unique=True, nullable=False)
quantity = db.Column(db.Integer, nullable=False)
db.create_all()
db_connection 函数的“user”、“password”、“ep”(端点/主机名)、“db”的详细信息通过填写网络表单传入。
我想我可能会以错误的方式解决这个问题。我想要的最终结果是让我的用户转到网络表单,填写有关要连接的数据库的详细信息,单击提交,然后函数(或其他任何内容)将与这些详细信息建立连接。
我传递给app.route的表单来建立调用上述函数
@app.route('/save_settings', methods=["GET", "POST"])
def save_settings():
ep_data = request.form['endpoint']
db_data = request.form['database']
user_data = request.form['username']
password_data = request.form['password']
db_connection(user=user_data, password=password_data, db=db_data, ep=ep_data)
当我尝试时,我收到以下错误:
AssertionError: A setup function was called after the first request was handled. This usually indicates a bug in the application where a module was not imported and decorators or other functionality was called too late.
To fix this make sure to import all your view modules, database models and everything related at a central place before the application starts serving requests.
【问题讨论】:
【参考方案1】:好的,在玩了一些之后,我似乎已经修复了它。我希望这也可以帮助其他陷入困境的人。 我犯的错误:
该类不属于该函数 类之前需要有:db = SQLAlchemy(app)这是我修改后的代码:
from flask import Flask, render_template, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
import pymysql
app = Flask(__name__)
db = SQLAlchemy(app)
def db_connection(user, password, ep, db):
connection = f"mysql+pymysql://user:password@ep/db"
app.config['SQLALCHEMY_DATABASE_URI'] = connection
app.config['SQLALCHEMY_TRACK_MODIFICATION'] = False
class Lab(db.Model):
id = db.Column(db.Integer, primary_key=True)
store = db.Column(db.String(80), unique=True, nullable=False)
item = db.Column(db.String(120), unique=True, nullable=False)
quantity = db.Column(db.Integer, nullable=False)
【讨论】:
在调用上述函数后,我也将 db.create_all() 也移动到了 app.route。以上是关于从输入创建 SQLAlchemy mysql 连接字符串的主要内容,如果未能解决你的问题,请参考以下文章