本文介绍了AttributeError:使用flask-sqlalchemy连接到sqlite数据库时无法设置属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在学习flask Web应用程序框架,并且对此感到很自在.之前,我已经构建了一个简单易用的应用程序,该应用程序可以完美运行.我在同一个项目上工作,但尝试使用TDD实施它.我遇到了一个以前从未见过且不知道如何解决的数据库错误.

I've been learning the flask web application framework and feel quite comfortable with it. I've previously built a simple to do app that worked perfectly. I was working on the same project, but trying to implement it using TDD. I've encountered an error with the database that I've never seen before and don't know how to fix.

当我检查代码时,看不到任何问题.它看起来也与工作项目中的代码相同,所以我真的不知道自己在做什么错.

When I examine my code, I cant see any issue. It also looks identical to the code of the working project, so I really don't know what I am doing wrong.

以下是错误:

(env) PS C:\coding-projects\task-master-tdd> flask shell
Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:43:08) [MSC v.1926 32 bit (Intel)] on win32
App: project [development]
Instance: C:\coding-projects\task-master-tdd\instance
>>> from project import db
>>> db
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "c:\coding-projects\task-master-tdd\env\lib\site-packages\flask_sqlalchemy\__init__.py", line 1060, in __repr__
    self.engine.url if self.app or current_app else None
  File "c:\coding-projects\task-master-tdd\env\lib\site-packages\flask_sqlalchemy\__init__.py", line 943, in engine
    return self.get_engine()
  File "c:\coding-projects\task-master-tdd\env\lib\site-packages\flask_sqlalchemy\__init__.py", line 962, in get_engine
    return connector.get_engine()
  File "c:\coding-projects\task-master-tdd\env\lib\site-packages\flask_sqlalchemy\__init__.py", line 555, in get_engine
    options = self.get_options(sa_url, echo)
  File "c:\coding-projects\task-master-tdd\env\lib\site-packages\flask_sqlalchemy\__init__.py", line 570, in get_options
    self._sa.apply_driver_hacks(self._app, sa_url, options)
  File "c:\coding-projects\task-master-tdd\env\lib\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
>>>

我的config.py文件:

my config.py file:

import os

# load the environment variables from the .env file
from dotenv import load_dotenv
load_dotenv()

# Determine the folder of the top-level directory of this project
BASEDIR = os.path.abspath(os.path.dirname(__file__))


class Config:
    FLASK_ENV = 'development'
    TESTING = False
    DEBUG = False
    SECRET_KEY = os.getenv('SECRET_KEY', default='A very terrible secret key.')
    SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL',
                                        default=f"sqlite:///{os.path.join(BASEDIR, 'instance', 'app.db')}")
    SQLALCHEMY_TRACK_MODIFICATIONS = False

class DevelopmentConfig(Config):
    DEBUG = True

class TestingConfig(Config):
    TESTING = True
    SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL',
                                        default=f"sqlite:///{os.path.join(BASEDIR, 'instance', 'test.db')}")

class ProductionConfig(Config):
    FLASK_ENV = 'production'

我的用户模型:

from project import db, login_manager
from flask_login import UserMixin
from werkzeug.security import generate_password_hash, check_password_hash

class User(db.Model, UserMixin):
    __tablename__ = 'users'

    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String, unique=True)
    hashed_password = db.Column(db.String)

    def __init__(self, username, password):
        self.username = username
        self.hashed_password = generate_password_hash(password)

    def is_password_valid(self, password):
        return check_password_hash(self.hashed_password, password)

    def __repr__(self):
        return '<User {}>'.format(self.id)

@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))

推荐答案

编辑

如果遇到这种情况,将Flask-SQLAlchemy升级到> = 2.5应该按照 https://github.com/pallets/flask-sqlalchemy/issues/910#issuecomment-802098285 .

不再需要将SQLAlchemy固定为〜1.3.

Pinning SQLAlchemy to ~1.3 should no longer be necessary.

我早些时候遇到了这个问题,但我想我已经知道发生了什么事.

I ran into this issue a little earlier, but think I've figured out what's going on.

SQLAlchemy作为Flask-SQLAlchemy的依赖项自动安装,其最新版本(1.4.0)引入了以下重大更改:

SQLAlchemy is automatically installed as a dependency for Flask-SQLAlchemy and its latest release (1.4.0) introduces the following breaking change:

我能够通过简单地安装SQL Alchemy的早期版本(1.3.23)来解决此问题.

I was able to fix this issue by simply installing the previous version of SQL Alchemy (1.3.23).

这篇关于AttributeError:使用flask-sqlalchemy连接到sqlite数据库时无法设置属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 19:23