在开发中(所以sqlite3),在任何数据库访问中都出现此错误:
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: ujs ...
我是来这里
export FLASK_ENV=development
export FLASK_APP=my_app.py
flask db init
flask db migrate
flask db upgrade
flask run
,然后针对该开发服务器执行HTTP GET。
我相信迁移工作流程成功了,因为当我使用sqlite3命令行客户端时,可以看到带有合理的架构的(空)表。
╭╴ (get-db-working *%=)╶╮
╰ jeff@starshine:TN_flask_web $ sqlite3 dev.db
SQLite version 3.27.2 2019-02-25 16:06:06
Enter ".help" for usage hints.
sqlite> .table
alembic_version ujs
sqlite> .quit
╭╴ (get-db-working *%=)╶╮
╰ jeff@starshine:TN_flask_web $
因此,我认为我犯了编码错误。但是我没看到。
我有以下代码(缩减为我认为必不可少的部分):
my_app.py:
from app import create_app, db, cli
from app.models import UJS
app = create_app()
cli.register(app)
@app.shell_context_processor
def make_shell_context():
return {'db': db,
'UJS': UJS}
app / models.py:
from app import db
import time
def now_in_microseconds():
"""Return the current time in microseconds since the epoch.
"""
return time.time() * 1000 * 1000
class UJS(db.Model):
id = db.Column(db.Integer, primary_key=True)
timestamp_microseconds = db.Column(db.BigInteger, default=now_in_microseconds)
ip_hash = db.column(db.String(40))
# And then some more columns, all quite boring.
def __repr__(self):
return '<[{tag}]/[{ip}] {microsec}/{city}>'.format(
tag=self.tag, ip=self.ip_hash,
microsec=self.timestamp_microseconds, city=self.city)
app / __ init __。py:
from flask import Flask, request, current_app
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from config import Config
db = SQLAlchemy()
migrate = Migrate()
def create_app(config_class=Config):
app = Flask(__name__)
app.config.from_object(config_class)
try:
app.config.from_pyfile("../config_local.py")
except FileNotFoundError:
print('No local config found.')
except:
print('Unexpected error on app.config.from_pyfile()')
db.init_app(app)
migrate.init_app(app, db)
...
return app
from app import models
和 app / main / routes.py:
from flask import request, g, current_app, session
from app import db
from app.main import bp
from app.models import UJS
@bp.before_app_request
def before_request():
if 'static' == request.endpoint:
# This should only happen in dev. Otherwise, nginx handles static routes directly.
return
# I expect this to return an empty list, but it throws a 500.
print(UJS.query.all())
有什么建议我想念的吗?
答案 0 :(得分:1)
对于以后可能会发现此问题的任何人:问题是关于在SQLALCHEMY_DATABASE_URI
配置值中具有正确的数据库绝对路径。
此外(这里不是这种情况,但是可能会有相同的症状)-如果在模型声明中省略__tablename__
,SQLAlchemy可能会自动生成您不会期望的内容。如果您使用的是已存在某种模式的现有数据库,那么请记住这一点。