【发布时间】: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.
【问题讨论】:
标签: mysql python-3.x flask sqlalchemy pymysql