AttributeError: 尝试使用 sqlalchemy 创建数据库时无法设置属性

时间:2021-03-17 00:02:57

标签: python sqlalchemy

尝试按照本教程从 freecodecamp 介绍到flask 视频:https://www.youtube.com/watch?v=Z1RJmh_OqeA

视频的相关部分开始于大约 19 分钟

这是我的代码:

    from flask import Flask, render_template
    from flask_sqlalchemy import SQLAlchemy
    from datetime import datetime
    
    
    app = Flask(name)
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///sqlite.db'
    # initialize the database with the settings from app
    db = SQLAlchemy(app)
    
    class Budget_Item(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        name = db.Column(db.String(50), nullable=False)
        cost = db.Column(db.Float, nullable=False)
        date_created = db.Column(db.DateTime, default=datetime.utcnow)
        recurring = db.Column(db.Boolean, nullable=False)
        due_date = db.Column(db.DateTime, nullable=True)
    
        def __repr__(self):
            return '<Budget_Item %r>' % self.id
    
    
    
    
    
    @app.route('/')
    def index():
        return render_template('index.html')
    
    if name == "main":
        app.run(debug=True)

当在终端中我从 app import db 运行时我没有问题,但是当我运行 db.create_all() 时我得到 AttributeError: can't set attribute。我已经尝试将类名更改为 BudgetName 以防问题出在下划线,并且我已经尝试完全重新创建视频中编写的代码,但我遇到了同样的错误。

错误回溯:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/mcamp/.local/share/virtualenvs/Python-docker-built-challenge-VYztjUFt/lib/python3.9/site-packages/flask_sqlalchemy/__init__.py", line 1039, in create_all
    self._execute_for_all_tables(app, bind, 'create_all')
  File "/home/mcamp/.local/share/virtualenvs/Python-docker-built-challenge-VYztjUFt/lib/python3.9/site-packages/flask_sqlalchemy/__init__.py", line 1031, in _execute_for_all_tables
    op(bind=self.get_engine(app, bind), **extra)
  File "/home/mcamp/.local/share/virtualenvs/Python-docker-built-challenge-VYztjUFt/lib/python3.9/site-packages/flask_sqlalchemy/__init__.py", line 962, in get_engine
    return connector.get_engine()
  File "/home/mcamp/.local/share/virtualenvs/Python-docker-built-challenge-VYztjUFt/lib/python3.9/site-packages/flask_sqlalchemy/__init__.py", line 555, in get_engine
    options = self.get_options(sa_url, echo)
  File "/home/mcamp/.local/share/virtualenvs/Python-docker-built-challenge-VYztjUFt/lib/python3.9/site-packages/flask_sqlalchemy/__init__.py", line 570, in get_options
    self._sa.apply_driver_hacks(self._app, sa_url, options)
  File "/home/mcamp/.local/share/virtualenvs/Python-docker-built-challenge-VYztjUFt/lib/python3.9/site-packages/flask_sqlalchemy/__init__.py", line 914, in apply_driver_hacks
    sa_url.database = os.path.join(app.root_path, sa_url.database)
AttributeError: can't set attribute

0 个答案:

没有答案