简体   繁体   English

Flask-SQLAlchemy创建SQLite数据库但不创建表

[英]Flask-SQLAlchemy creating SQLite database but not tables

I've had a look at a very similar issue , but the solution isn't working for me, and I was wondering if I could get some guidance. 我已经看过一个非常相似的问题 ,但是该解决方案对我而言不起作用,我想知道是否可以得到一些指导。

This is my application structure: 这是我的应用程序结构:

mosiman/
  __init__.py
  blog/
    __init__.py
    blogconfig.py
    blog.py
    static/
      ...
    templates/
      ...

I really wanted a way to build separate apps but manage them from one application instance so I wouldn't have to touch the WSGI layer, and blueprints seemed like the best way. 我真的很想一种方法来构建单独的应用程序,但可以从一个应用程序实例管理它们,这样我就不必接触WSGI层,而蓝图似乎是最好的方法。

Here's what I think the relevant files are: 我认为相关文件如下:

# mosiman/__init__.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import blog.blog as blog
...
...
db = SQLAlchemy()
...
...
def create_app():
    app = Flask(__name__)
    db_path = os.path.join(os.path.dirname(__file__), 'mosiman.db')
    app.config["SQLALCHEMY_DATABASE_URI"] = 'sqlite:///{}'.format(db_path)
    app.config["SQLALCHEMY_BINDS"] = {'blog': os.path.join(os.path.dirname(__file__), 'blog/blog.db')
    db.init_app(app)
    app.register_blueprint(blog.blog, url_prefix='/blog')
    return app
if __name__ == '__main__':
    app = create_app()
    app.run(debug=True)

I also have in my mosiman/blog/blog.py file: 我的mosiman/blog/blog.py文件中也包含:

#mosiman/blog/blog.py
<<< all of the usual flask imports and SQLAlchemy, etc >>>
from .__init__ import db
blog = Blueprint('blog', __name__)
...
...
class Entry(db.Model):
    __bind_key__ = "blog"
    id = db.Column(db.Integer, primary_key = True)
    title = db.Column(db.String(150))
    ...
    ...

Here is my problem: I actually don't have a "default" database, so I have no classes for it. 这是我的问题:我实际上没有“默认”数据库,因此没有适用的类。 But I do want to initialize my blog database with the class Entry . 但是我确实想使用类Entry初始化我的博客数据库。

The default procedure for initializing the database seems to be to pop into the python REPL, import the database, and run db.create_all() 初始化数据库的默认过程似乎是弹出python REPL,导入数据库,然后运行db.create_all()

Well, I can't just import db and run db.create_all() because db hasn't been attached to an app yet (done in create_app() ) This is how I proceed: 好吧,我不能只导入db并运行db.create_all()因为db尚未附加到应用程序(在create_app() ),这是我的处理方式:

# pop open a REPL at mosiman/
>>> from __init__ import db
>>> from __init__ import create_app
>>> app = create_app()
>>> db.init_app(app)
>>> from blog.blog import Entry
>>> db.init_app(app)
# At this point, db still isn't attached to an engine?
>>> db
<SQLAlchemy engine=None>
>>> with app.app_context():
...     db.create_all()
...
>>>

Now, when I go to mosiman/blog/ I find that blog.db has been created, but when I check the schema and tables in SQLite3 nothing turns up. 现在,当我转到mosiman/blog/我发现已经创建了blog.db ,但是当我在SQLite3中检查架构和表时,没有任何反应。

1 solved their problem by changing from __init__ import db to from mosiman import db 1通过将from __init__ import db更改为from mosiman import db解决了他们的问题

If I try to do that inside mosiman/ : 如果我尝试在mosiman/执行此mosiman/

>>> from mosiman import db
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'mosiman'

even though I've got an __init__.py in there. 即使我在那里有一个__init__.py

If I run it from ../ (the directory above mosiman ): 如果我从运行../ (上面的目录mosiman ):

>>> from mosiman import db
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/users/d49chan/mosiman/__init__.py", line 3, in <module>
    import blog.blog as blog
ModuleNotFoundError: No module named 'blog'

I'm not sure how to proceed. 我不确定如何进行。 Maybe it's because I need sleep, but I've been trying to understand why nothing works for the past many hours. 也许是因为我需要睡觉,但是我一直在试图理解为什么在过去的几个小时里没有任何反应。 If you could point me in the right direction or possibly clear up some of my misunderstandings I'd be very grateful. 如果您能指出正确的方向或消除我的一些误解,我将不胜感激。

1) You don't namely import __init__.py . 1)您不是导入__init__.py You should import it with the name of the directory (package) it's in. 您应该使用其中的目录(包)的名称导入它。

2) You shouldn't import like this: import blog.blog . 2)您不应该这样导入: import blog.blog Instead you should: from blog import blog . 相反,您应该: from blog import blog

3) Be sure you have an __init__.py file in every directory so that the python importer can treat it as a package (directory) it can import from. 3)确保每个目录中都有一个__init__.py文件,以便python导入器将其视为可以从中导入的包(目录)。

4) There's a difference between relative importing and absolute importing. 4)相对导入和绝对导入之间有区别。

Relative importing: 相对导入:

# l3_module.py in l3_package
from ..l1_package import l1_module

This imports a module located two packages (directories) up in relation to the module importing it. 这将导入一个模块,该模块相对于导入模块位于两个包(目录)的上方。

Now assuming l3_package is in an l2_package which is in an l1_module, You can also import it as such 现在假设l3_package在l1_module的l2_package中,您也可以这样导入它

Absolute importing: 绝对导入:

# l3_moudle.py in l3_package
from l1_package import l1_module

This will also work, but then it sometimes messes stuff up, depending on your env. 这也可以工作,但是有时会把东西弄乱,具体取决于您的环境。 Here's an excellent answer that can clear some stuff up for you: Relative imports for the billionth time . 这是一个很好的答案,可以为您清除一些麻烦: 相对进口量为十亿次

Hope that helped :) 希望有帮助:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM