首页 > 解决方案 > SQLAlchemy OperationalError no such table - 与 sqlite uri 混淆

问题描述

帮助!我对烧瓶真的很陌生,我一直在混淆我能找到的所有教程,但我遇到了一个我无法弄清楚的问题。

这是我的错误:

sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: User
[SQL: SELECT "User"."userId" AS "User_userId", "User".email AS "User_email", "User".password AS "User_password", "User".username AS "User_username", "User".lastlogin AS "User_lastlogin", "User".isauthenticated AS "User_isauthenticated" 
FROM "User" 
WHERE "User".email = ?
 LIMIT ? OFFSET ?]
[parameters: ('test@example.com', 1, 0)]
(Background on this error at: http://sqlalche.me/e/13/e3q8)

所以我正在处理注册表单,我已经解决了所有其他错误。但是在这里我可以从这个错误中看出我的数据库或表没有被创建。

这是我的代码:

初始化.py:

import os
from flask import Flask, render_template, redirect, session
from flask_login import LoginManager
from flask_bcrypt import Bcrypt
from flask_sqlalchemy import SQLAlchemy
from werkzeug.utils import import_string
from complete.app import redirect_url

db = SQLAlchemy()
login_manager = LoginManager()

def create_app():
    """Create Flask application."""
    
    app = Flask(__name__, instance_relative_config=False)

    @app.context_processor
    def inject_global_vars():
        return dict(appname="Ebay Listing Viewer")

    app.config.from_pyfile('configfile.py')    

    db.init_app(app)
    login_manager.init_app(app)

    with app.app_context():

        from .userauth.auth import auth_bp
        app.register_blueprint(auth_bp)

        db.create_all()

        from .models import User

        @login_manager.user_loader
        def load_user(user_id):
            return User.get(user)
        
        return app

模型.py:

"""Data Models"""
from flask_login import UserMixin
from . import db


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

    userid = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(100), unique=True)
    password = db.Column(db.String(200))
    username = db.Column(db.String(1000))
    lastlogin = db.Column(db.DateTime)
    isauthenticated = db.Column(db.Boolean, default=False)

    def is_active(self):
        return True

    def get_id(self):
        return chr(self.userId)

    def is_authenticated(self):
        return self.isauthenticated

    def is_anonymous(self):
        return False

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

    def set_password(self, password):
        self.password = generate_password_hash(
            password,
            method='sha256'
        )
    
    def check_password(self, password):
        return check_password_hash(self.password, password)

配置文件:

class Config(object):
    """Base config."""
    SECRET_KEY = environ.get('SECRET_KEY')
    STATIC_FOLDER = 'static'
    TEMPLATES_FOLDER = 'templates'

class DevelopmentConfig(Config):
    FLASK_ENV = 'development'
    SQLALCHEMY_DATABASE_URI = environ.get('DEV_DATABASE_URI')

.env:

#among other things...
DEV_DATABASE_URI=sqlite:///db.sqlite

在我的根文件夹(即与 init.py 相同的目录)中有一个名为 db.sqlite 的文件,但我不确定其中是否包含任何内容。当我尝试打开它时,它显示The file is not displayed in the editor because it is either binary or uses an unsupported text encoding.(我正在使用 VSCode)。

我不太确定数据库 uri 是如何工作的——我在 Google 周围看了很多遍,每个人似乎都认为这很明显。它是我的数据库文件的文件路径吗?我是创建数据库文件还是自动创建?

我认为问题很可能是数据库 uri 错误,但我不知道,我没有足够的经验,所以可能是完全不同的东西。

感谢您花时间阅读和帮助!

标签: pythonflasksqlalchemyflask-sqlalchemy

解决方案


推荐阅读