【问题标题】:SQLAlchemy error: "TypeError: Additional arguments should be named <dialectname>_<argument>, got 'nullable'"SQLAlchemy 错误:“类型错误:附加参数应命名为 <方言名称>_<参数>,得到 'nullable'”
【发布时间】:2019-11-26 18:26:01
【问题描述】:

问题

我在按照有关使用 Flash 的教程使用 Flask 时遇到错误。 由于我是一名基本的 Python 程序员,我不明白它为什么或有什么问题。

因此,如果您不介意解释它或添加解释链接。

控制台打印错误

(不知道什么是重要的,抱歉)

C:\Users\name\Desktop\Eeverything on this computer\GCSE\Computer Science\free-style\organised\website>python flaskblog.py
C:\Users\name\Anaconda3\lib\site-packages\flask_sqlalchemy\__init__.py:835: FSADeprecationWarning: SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future.  Set it to True or False to suppress this warning.
  'SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and '
Traceback (most recent call last):
  File "flaskblog.py", line 22, in <module>
    class Post(db.Model):
  File "C:\Users\name\Anaconda3\lib\site-packages\flask_sqlalchemy\model.py", line 67, in __init__
    super(NameMetaMixin, cls).__init__(name, bases, d)
  File "C:\Users\name\Anaconda3\lib\site-packages\flask_sqlalchemy\model.py", line 121, in __init__
    super(BindMetaMixin, cls).__init__(name, bases, d)
  File "C:\Users\name\Anaconda3\lib\site-packages\sqlalchemy\ext\declarative\api.py", line 75, in __init__
    _as_declarative(cls, classname, cls.__dict__)
  File "C:\Users\name\Anaconda3\lib\site-packages\sqlalchemy\ext\declarative\base.py", line 131, in _as_declarative
    _MapperConfig.setup_mapping(cls, classname, dict_)
  File "C:\Users\name\Anaconda3\lib\site-packages\sqlalchemy\ext\declarative\base.py", line 160, in setup_mapping
    cfg_cls(cls_, classname, dict_)
  File "C:\Users\name\Anaconda3\lib\site-packages\sqlalchemy\ext\declarative\base.py", line 190, in __init__
    self._setup_table()
  File "C:\Users\name\Anaconda3\lib\site-packages\sqlalchemy\ext\declarative\base.py", line 538, in _setup_table
    **table_kw
  File "C:\Users\name\Anaconda3\lib\site-packages\flask_sqlalchemy\model.py", line 99, in __table_cls__
    return sa.Table(*args, **kwargs)
  File "<string>", line 2, in __new__
  File "C:\Users\name\Anaconda3\lib\site-packages\sqlalchemy\util\deprecations.py", line 128, in warned
    return fn(*args, **kwargs)
  File "C:\Users\name\Anaconda3\lib\site-packages\sqlalchemy\sql\schema.py", line 506, in __new__
    metadata._remove_table(name, schema)
  File "C:\Users\name\Anaconda3\lib\site-packages\sqlalchemy\util\langhelpers.py", line 68, in __exit__
    compat.reraise(exc_type, exc_value, exc_tb)
  File "C:\Users\name\Anaconda3\lib\site-packages\sqlalchemy\util\compat.py", line 153, in reraise
    raise value
  File "C:\Users\name\Anaconda3\lib\site-packages\sqlalchemy\sql\schema.py", line 501, in __new__
    table._init(name, metadata, *args, **kw)
  File "C:\Users\name\Anaconda3\lib\site-packages\sqlalchemy\sql\schema.py", line 600, in _init
    self._init_items(*args)
  File "C:\Users\name\Anaconda3\lib\site-packages\sqlalchemy\sql\schema.py", line 117, in _init_items
    spwd(self)
  File "C:\Users\name\Anaconda3\lib\site-packages\sqlalchemy\sql\base.py", line 457, in _set_parent_with_dispatch
    self.dispatch.after_parent_attach(self, parent)
  File "C:\Users\name\Anaconda3\lib\site-packages\sqlalchemy\event\attr.py", line 322, in __call__
    fn(*args, **kw)
  File "C:\Users\name\Anaconda3\lib\site-packages\sqlalchemy\sql\schema.py", line 2094, in _set_table
    **self._unvalidated_dialect_kw
  File "C:\Users\name\Anaconda3\lib\site-packages\sqlalchemy\sql\schema.py", line 3132, in __init__
    **dialect_kw
  File "C:\Users\name\Anaconda3\lib\site-packages\sqlalchemy\sql\schema.py", line 2711, in __init__
    self._validate_dialect_kwargs(dialect_kw)
  File "C:\Users\name\Anaconda3\lib\site-packages\sqlalchemy\sql\base.py", line 289, in _validate_dialect_kwargs
    "named <dialectname>_<argument>, got '%s'" % k
TypeError: Additional arguments should be named <dialectname>_<argument>, got 'nullable'

我的代码:flaskblog.py

from flask import Flask, escape, request, render_template, url_for, flash, redirect
from flask_sqlalchemy import SQLAlchemy
from forms import RegistrationForm, LoginForm
from datetime import datetime

app = Flask(__name__)
app.config["SECRET_KEY"] = "16ee14ac45b13e16aca29d7827e58366"
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///site.db"
db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(20), unique = True, nullable=False)
    email = db.Column(db.String(120), unique = True, nullable=False)
    image_file = db.Column(db.String(20), nullable=False, default="default.jpg")
    password = db.Column(db.String(60), nullable=False)
    posts = db.relationship("Post", backref="auther", lazy=True)

    def __repr__(self):
        return f"User('{self.username}', '{self.email}', {self.image_file})"

class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100), nullable=False)
    date_posted = db.Column(db.DateTime, nullable=False, default = datetime.utcnow)
    content = db.Column(db.Text, nullable=False)
    user_id = db.Column(db.Integer, db.ForeignKey("user.id", nullable=False))

    def __repr__(self):
        return f"Post('{self.title}', '{self.date_posted}')"

posts = [
{
    "auther": "ed",
    "title": "blog 1",
    "content": "first post",
    "sate_posted": "1/1/79"
},
{
    "auther": " not ed",
    "title": "blog 2",
    "content": "second post",
    "sate_posted": "2/1/79"
}]

@app.route('/')
@app.route('/home')
def home():
    return render_template("home.html", posts=posts)

@app.route('/about')
def about():
    return render_template("about.html", title = "about")

@app.route('/register', methods=["GET", "POST"])
def register():
    form = RegistrationForm()
    if form.validate_on_submit():
        flash(f"Account created for {form.username.data}!", "success")
        return redirect(url_for("home"))
    return render_template("register.html", title = "Register", form = form)

@app.route('/login', methods=["GET", "POST"])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        if form.email.data == "admin@blog.com" and form.password.data == "password":
            flash("You have been logged in!", "success")
            return redirect(url_for("home"))
        else:
            flash("Login Unsuccesful. please check username and password", "danger")
    return render_template("login.html", title = "Login", form = form)


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

相关文件

现在,我不知道您还需要什么,与此关联的其他文件称为:

    forms.py

    about.html
    home.html
    layout.html
    login.html
    register.html
    main.css

我没有添加它们,因为它最终可能会成为太多不必要的代码,但如果您需要任何东西,请留下评论。

【问题讨论】:

    标签: python flask sqlalchemy


    【解决方案1】:

    您似乎在 Post 类的 user_id 字段中打错了字。

    你写道:

        user_id = db.Column(db.Integer, db.ForeignKey("user.id", nullable=False))
    

    正确的时候:

        user_id = db.Column(db.Integer, db.ForeignKey("user.id"), nullable=False)
    

    【讨论】:

    • 谢谢你,先生是个传奇,你是这个网站的活生生的美人,我一定会帮助别人解决我能解决的问题,谢谢你,你让我免于付出起来!!
    • 不客气。我很高兴在我在这里投稿的第一天就读到了这篇文章。这是你开始做同样事情的好机会 =)
    • 感谢@GabrielMelo 的回答,我也犯了同样的错误。
    • 我也犯了同样的错误哈哈
    【解决方案2】:

    在我的情况下,nullable=False 中存在拼写错误

    我写了 nunllable=False

    在修正错字错误 nullable=False 后解决

    【讨论】:

      【解决方案3】:

      您的命名约定或语法存在错误。

      就我而言,在子类中引用外键时,类名 todolists(Parent) 中缺少 s

      【讨论】:

        猜你喜欢
        • 2020-12-27
        • 2019-04-20
        • 1970-01-01
        • 1970-01-01
        • 2021-01-05
        • 1970-01-01
        • 2021-04-26
        • 2021-12-11
        • 1970-01-01
        相关资源
        最近更新 更多