在 Flask 中使用 SQLAlchemy 创建数据库 [英] Creating database with SQLAlchemy in Flask

查看:24
本文介绍了在 Flask 中使用 SQLAlchemy 创建数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道,我需要做什么才能在 Flask 中创建 SQLAlchemy 数据库.根据 documentation 我应该在我的 Flask 应用程序中创建模型,然后转到 Python shell 和只需使用 db.create_all() 来创建它.但这不起作用.

我的 Flask 应用:

导入操作系统进口烧瓶导入设置从flask_sqlalchemy 导入SQLAlchemyapp = flask.Flask(__name__)app.config['SESSION_TYPE'] = '文件系统'app.secret_key = os.urandom(24)app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////database.db'db = SQLAlchemy(应用程序)(...)

型号:

 from app import db类用户(db.Model):id = db.Column(db.Integer, primary_key = True)用户名 = db.Column(db.String(15), unique = True)密码 = db.Column(db.String(15), unique = True)任务 = db.relationship('Task', backref='author', lazy='dynamic')def __init__(self, 用户名, 密码):self.username = 用户名self.password = 密码类任务(db.Model):id = db.Column(db.Integer, primary_key = True)场景 = db.Column(db.String(140), nullable = False)状态 = db.Column(db.Integer(1), nullable = False)进度 = db.Column(db.Integer(3), nullable = False)add_date = db.Column(db.DateTime, nullable = False)start_date = db.Column(db.DateTime, nullable = False)完成日期 = db.Column(db.DateTime, nullable = False)渲染场景 = db.Column(db.String(140))user_id = db.Column(db.Integer, db.ForeignKey('user.id'))

错误代码:

<预><代码>>>>从应用程序导入数据库>>>db.create_all()回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中文件C:Python27libsite-packagesflask_sqlalchemy\__init__.py",第 895 行,在 create_all 中self._execute_for_all_tables(app, bind, 'create_all')文件C:Python27libsite-packagesflask_sqlalchemy\__init__.py",第 887 行,在 _execute_for_all_tables操作(绑定=self.get_engine(应用程序,绑定),**额外)文件C:Python27libsite-packagessqlalchemysqlschema.py",第 3420 行,在 create_all 中表=表)文件C:Python27libsite-packagessqlalchemyenginease.py",第 1727 行,in_run_visitor使用 self._optional_conn_ctx_manager(connection) 作为连接:文件C:Python27libcontextlib.py",第 17 行,在 __enter__返回 self.gen.next()文件C:Python27libsite-packagessqlalchemyenginease.py",第 1720 行,in_optional_conn_ctx_manager使用 self.contextual_connect() 作为连接:文件C:Python27libsite-packagessqlalchemyenginease.py",第 1910 行,incontextual_connectself.pool.connect(),文件C:Python27libsite-packagessqlalchemypool.py",第 338 行,在连接中返回 _ConnectionFairy._checkout(self)_checkout 中的文件C:Python27libsite-packagessqlalchemypool.py",第 645 行仙女 = _ConnectionRecord.checkout(pool)文件C:Python27libsite-packagessqlalchemypool.py",第 440 行,结帐时rec = pool._do_get()文件C:Python27libsite-packagessqlalchemypool.py",第 1058 行,在 _do_get返回 self._create_connection()_create_connection 中的文件C:Python27libsite-packagessqlalchemypool.py",第 285 行返回 _ConnectionRecord(self)文件C:Python27libsite-packagessqlalchemypool.py",第 411 行,在 __init__ 中self.connection = self.__connect()文件C:Python27libsite-packagessqlalchemypool.py",第 539 行,在 __connect连接 = self.__pool._creator()文件C:Python27libsite-packagessqlalchemyenginestrategies.py",第 96 行,在连接中connection_invalidated=失效文件C:Python27libsite-packagessqlalchemyutilcompat.py",第 199 行,在 raise_from_cause 中重新加注(类型(异常),异常,tb=exc_tb)文件C:Python27libsite-packagessqlalchemyenginestrategies.py",第 90 行,在连接中return dialect.connect(*cargs, **cparams)文件C:Python27libsite-packagessqlalchemyenginedefault.py",第 377 行,在连接中返回 self.dbapi.connect(*cargs, **cparams)sqlalchemy.exc.OperationalError: (OperationalError) 无法打开数据库文件无 无

解决方案

您在数据库 uri 中的 / 太多了.格式为dialect+driver://user:pass@host:port/db_name.对于 SQLite,db_name 是数据库的路径.您已指定绝对路径 /database.db,这意味着您正在尝试在文件系统的根目录中创建数据库.

使用sqlite:///database.db(相对路径)将在(相对于)当前工作目录中创建数据库.

您可能想要指定绝对路径,但基于项目位置构建它,因为您可以从另一个文件夹运行应用程序.假设您要在与应用程序设置代码相同的目录中创建数据库,请构建一个相对于 __file__ 的路径.

db_path = os.path.join(os.path.dirname(__file__), 'app.db')db_uri = 'sqlite:///{}'.format(db_path)app.config['SQLALCHEMY_DATABASE_URI'] = db_uri

I'd like to know, what I need to do to create SQLAlchemy database in Flask. According to documentation I should create model in my Flask app and then go to the Python shell and just create this by using db.create_all(). But that doesn't work.

My Flask app:

import os
import flask
import settings
from flask_sqlalchemy import SQLAlchemy

app = flask.Flask(__name__)
app.config['SESSION_TYPE'] = 'filesystem'
app.secret_key = os.urandom(24)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////database.db'
db = SQLAlchemy(app)
(...)

Model:

from app import db

class User(db.Model):
    id = db.Column(db.Integer, primary_key = True)
    username = db.Column(db.String(15), unique = True)
    password = db.Column(db.String(15), unique = True)
    tasks = db.relationship('Task', backref='author', lazy='dynamic')

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

class Task(db.Model):
    id = db.Column(db.Integer, primary_key = True)
    scene = db.Column(db.String(140), nullable = False)
    state = db.Column(db.Integer(1), nullable = False)
    progress = db.Column(db.Integer(3), nullable = False)
    add_date = db.Column(db.DateTime, nullable = False)
    start_date = db.Column(db.DateTime, nullable = False)
    finish_date = db.Column(db.DateTime, nullable = False)
    rendered_scene = db.Column(db.String(140))
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))

Error code:

>>> from app import db
>>> db.create_all()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:Python27libsite-packagesflask_sqlalchemy\__init__.py", line 895, in create_all
    self._execute_for_all_tables(app, bind, 'create_all')
  File "C:Python27libsite-packagesflask_sqlalchemy\__init__.py", line 887, in _execute_for_all_tables
    op(bind=self.get_engine(app, bind), **extra)
  File "C:Python27libsite-packagessqlalchemysqlschema.py", line 3420, in create_all
    tables=tables)
  File "C:Python27libsite-packagessqlalchemyenginease.py", line 1727, in_run_visitor
    with self._optional_conn_ctx_manager(connection) as conn:
  File "C:Python27libcontextlib.py", line 17, in __enter__
    return self.gen.next()
  File "C:Python27libsite-packagessqlalchemyenginease.py", line 1720, in_optional_conn_ctx_manager
    with self.contextual_connect() as conn:
  File "C:Python27libsite-packagessqlalchemyenginease.py", line 1910, incontextual_connect
    self.pool.connect(),
  File "C:Python27libsite-packagessqlalchemypool.py", line 338, in connect
    return _ConnectionFairy._checkout(self)
  File "C:Python27libsite-packagessqlalchemypool.py", line 645, in _checkout
    fairy = _ConnectionRecord.checkout(pool)
  File "C:Python27libsite-packagessqlalchemypool.py", line 440, in checkout

    rec = pool._do_get()
  File "C:Python27libsite-packagessqlalchemypool.py", line 1058, in _do_get

    return self._create_connection()
  File "C:Python27libsite-packagessqlalchemypool.py", line 285, in _create_connection
    return _ConnectionRecord(self)
  File "C:Python27libsite-packagessqlalchemypool.py", line 411, in __init__

    self.connection = self.__connect()
  File "C:Python27libsite-packagessqlalchemypool.py", line 539, in __connect
    connection = self.__pool._creator()
  File "C:Python27libsite-packagessqlalchemyenginestrategies.py", line 96, in connect
    connection_invalidated=invalidated
  File "C:Python27libsite-packagessqlalchemyutilcompat.py", line 199, in raise_from_cause
    reraise(type(exception), exception, tb=exc_tb)
  File "C:Python27libsite-packagessqlalchemyenginestrategies.py", line 90, in connect
    return dialect.connect(*cargs, **cparams)
  File "C:Python27libsite-packagessqlalchemyenginedefault.py", line 377, in connect
    return self.dbapi.connect(*cargs, **cparams)
sqlalchemy.exc.OperationalError: (OperationalError) unable to open database file
 None None

解决方案

You have one too many / in the database uri. The format is dialect+driver://user:pass@host:port/db_name. With SQLite, db_name is the path to the database. You've specified the absolute path /database.db, which means you're trying to create the database in the filesystem's root directory.

Using sqlite:///database.db (a relative path) will create the database in (relative to) the current working directory.

You probably want to specify an absolute path, but build it based on the project location, since you could run the application from another folder. Assuming you want to create the db in the same directory as the app setup code, build a path relative to __file__.

db_path = os.path.join(os.path.dirname(__file__), 'app.db')
db_uri = 'sqlite:///{}'.format(db_path)
app.config['SQLALCHEMY_DATABASE_URI'] = db_uri

这篇关于在 Flask 中使用 SQLAlchemy 创建数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆