当我尝试在数据库中使用密码创建一个新列时发生错误

发布于 2025-01-28 04:22:43 字数 2461 浏览 2 评论 0原文

from flask import Flask, redirect, url_for, render_template, request
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
import uuid


app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///passwords.db'

db = SQLAlchemy(app)


class Passwords(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(200), nullable=False)
    key = db.Column(db.String(200), nullable=False)
    date_created = db.Column(db.DateTime, default=datetime.utcnow)

    def __repr__(self):
    return '<Name %r>' % self.id


@app.route("/passwords")
def passwords():
return render_template("passwords.html")


@app.route("/")
def home():
    return render_template("index.html")


@app.route("/signup", methods=["POST", "GET"])
def new_user():
    if request.method == "POST":
        a = str(uuid.uuid4())
        print(a)
        key = Passwords(key=a)
        username = request.form["nm"]
        newuser = Passwords(name=username)
        try:
            db.session.add(newuser)
            db.session.commit()
            db.session.add(key)
            db.session.commit()
            return redirect(url_for("new_user"))
        except:
            return "There was an error with your registration"
    else:
        passcodes = Passwords.query.order_by(Passwords.date_created)
        return render_template("signup.html", passcodes=passcodes)


@app.route("/login", methods=["POST", "GET"])
def login():
    a = str(uuid.uuid4())
    print(a)
    if request.method == "POST":
        user = request.form["pw"]
        if user == a:
            return redirect(url_for("user", usr='Η Ακύρωση κράτησης ολοκληρώθηκε'))
        else:
            return render_template("login.html")
    else:

        return render_template("login.html")


@ app.route("/<usr>")
def user(usr):
    return "<h1>{}</h1>".format(usr)


if __name__ == "__main__":
    app.run(debug=True)

我可以启动并运行我的网站,但是当我转到/Inbeup时,发生错误:

sqlalchemy.exc.operationalerror :( sqlite3.operationalerror)否这样的列:passwords.key
[sql:选择passwords.id作为passwords_id,passwords.name为passwords_name,密码。“键”为passwords_key,passworgss.date_created as passworgs_date_created 从密码订单。date_created]
(此错误的背景: https://sqlalche.me/e/14/e3q8

任何帮助都非常感谢

from flask import Flask, redirect, url_for, render_template, request
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
import uuid


app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///passwords.db'

db = SQLAlchemy(app)


class Passwords(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(200), nullable=False)
    key = db.Column(db.String(200), nullable=False)
    date_created = db.Column(db.DateTime, default=datetime.utcnow)

    def __repr__(self):
    return '<Name %r>' % self.id


@app.route("/passwords")
def passwords():
return render_template("passwords.html")


@app.route("/")
def home():
    return render_template("index.html")


@app.route("/signup", methods=["POST", "GET"])
def new_user():
    if request.method == "POST":
        a = str(uuid.uuid4())
        print(a)
        key = Passwords(key=a)
        username = request.form["nm"]
        newuser = Passwords(name=username)
        try:
            db.session.add(newuser)
            db.session.commit()
            db.session.add(key)
            db.session.commit()
            return redirect(url_for("new_user"))
        except:
            return "There was an error with your registration"
    else:
        passcodes = Passwords.query.order_by(Passwords.date_created)
        return render_template("signup.html", passcodes=passcodes)


@app.route("/login", methods=["POST", "GET"])
def login():
    a = str(uuid.uuid4())
    print(a)
    if request.method == "POST":
        user = request.form["pw"]
        if user == a:
            return redirect(url_for("user", usr='Η Ακύρωση κράτησης ολοκληρώθηκε'))
        else:
            return render_template("login.html")
    else:

        return render_template("login.html")


@ app.route("/<usr>")
def user(usr):
    return "<h1>{}</h1>".format(usr)


if __name__ == "__main__":
    app.run(debug=True)

I get my website up and running but when I go to /signup, an error occurs:

sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such column: passwords.key
[SQL: SELECT passwords.id AS passwords_id, passwords.name AS passwords_name, passwords."key" AS passwords_key, passwords.date_created AS passwords_date_created
FROM passwords ORDER BY passwords.date_created]
(Background on this error at: https://sqlalche.me/e/14/e3q8)

Any help is much appreciated

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

稚气少女 2025-02-04 04:22:43

Sqlalchemy只能处理创建和丢弃桌子;除执行RAW SQL Alter Table语句外,它不支持添加,删除或修改列。如果您需要执行此类操作,您的选项是在难度的上升顺序*

  • 放下整个数据库(或删除sqlite文件)并运行db.create_all()重新创建它
    • 除非您备份数据库
    • ,否则所有数据将丢失

  • 删除受影响的表并运行db.create_all()以重新创建它, 否则所有数据将丢失
    • 使用数据库的控制台或其他一些数据库管理应用程序删除表
    • 如果表通过外国密钥与其他表相关,则可能需要删除相关表格
    • 表中的所有数据都将丢失,除非备份
  • 表必要的Alter Table在数据库的控制台或其他数据库管理应用程序中的语句(S)
    • 您将需要确保结果与SQLalchemy所创建的内容匹配
  • 使用迁移实用程序将模型更改应用于数据库

< sup>>*所有选项都假定您已更新了模型类

SQLAlchemy only handles creating and dropping tables; it has no support for adding, removing or amending columns, other than executing raw SQL ALTER TABLE statements. If you need to perform such an action your options are, in ascending order of difficulty*:

  • Drop the entire database (or delete the SQLite file) and run db.create_all() to recreate it
    • all data will be lost unless you back up the database
  • Drop the affected table and run db.create_all() to recreate it
    • Use your database's console or some other database management application to drop the table
    • If the table is related to other tables via foreign keys then the related tables may need to be deleted too
    • All data in the table will be lost unless it's backed up
  • Manually execute the necessary ALTER TABLE statement(s) in your database's console or some other database management application
    • You will need to ensure that the results match what SQLAlchemy would have created
  • Use a migration utility to apply model changes to the database

* All options assume you have updated the model class

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文