Flask和SQLAlchemy:没有名为“app”和NameE的模块

2024-10-01 15:40:20 发布

您现在位置:Python中文网/ 问答频道 /正文

这里是无人区。好像是我的模型.py文件无法导入在中创建的db对象初始py,但是是一个db文件(博客.db)仍在创建中。因为我不能使用我的模型类(Entry(数据库模型))要从控制台中添加到数据库(db对象本身在控制台中工作),我认为我从模型.py. 在Python3(venv),Linux上。在

目录结构(仅限相关文件夹,例如无缓存):

/folder/
/folder/app/
/folder/app/__init__.py
/folder/app/models.py
/folder/config.py (only includes the sqlite uri naming variable)
/folder/fakepy/etc (venv, with flask and flask_sqlalchemy)
/folder/run.py (starts server fine, but does show that 'common' sql track modifications warning twice after a restart. normal?)

初始页:

^{pr2}$

模型.py:

#!fakepy/bin/python3
from app import db
import re
import datetime

class Entry(db.Model):
    __tablename__ = "post"
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(80))
    slug = db.Column(db.String, unique=True)
    content = db.Column(db.Text)
    timestamp = db.Column(db.DateTime)
    def __init__(self, title, content, slug=None, timestamp=None):
        self.title = title
        self.content = content
        if slug is None:
            self.slug = re.sub('[^\w]+', '-', self.title.lower())
        if timestamp is None:
            timestamp = datetime.utcnow()
        self.timestamp = timestamp

配置.py:

import os

basedir = os.path.abspath(os.path.dirname(__file__))

SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'blog.db')

数据库已创建。。。(控制台在/folder/打开,博客.db创建于/folder/):

>>> from app import db
>>> db.create_all()
>>>

错误:从控制台导入应用程序时未定义名称“Entry”

(fakepy) cha0@skyrim:~/folder$ python3
Python 3.4.3+ (etc removed for brevity)
>>> from app import app
(common sql track modifications warning, removed it for brevity)
>>> Entry()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'Entry' is not defined
>>> 
>>> from app import models
>>> Entry()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'Entry' is not defined
 >>>
 >>> from app import Entry
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: cannot import name 'Entry'
>>> 

错误:没有名为“app”的模块模型.py直接运行。

(fakepy) cha0@skyrim:~/folder/app$ python3 models.py 
Traceback (most recent call last):
  File "models.py", line 2, in <module>
    from app import db
ImportError: No module named 'app'
(fakepy)

错误:当初始py直接运行。 不过,我认为这可能是另一个问题。在

python3 __init__.py
Traceback (most recent call last):
  File "/home/cha0/folder/fakepy/lib/python3.4/site-packages/werkzeug/utils.py", line 418, in import_string
    __import__(import_name)
ImportError: No module named 'config'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "__init__.py", line 6, in <module>
    app.config.from_object('config')
  File "/home/cha0/folder/fakepy/lib/python3.4/site-packages/flask/config.py", line 162, in from_object
    obj = import_string(obj)
  File "/home/cha0/folder/fakepy/lib/python3.4/site-packages/werkzeug/utils.py", line 443, in import_string
    sys.exc_info()[2])
  File "/home/cha0/folder/fakepy/lib/python3.4/site-packages/werkzeug/_compat.py", line 137, in reraise
    raise value.with_traceback(tb)
  File "/home/cha0/folder/fakepy/lib/python3.4/site-packages/werkzeug/utils.py", line 418, in import_string
    __import__(import_name)
werkzeug.utils.ImportStringError: import_string() failed for 'config'. Possible reasons are:

- missing __init__.py in a package;
- package or module path not included in sys.path;
- duplicated package or module name taking precedence in sys.path;
- missing module, class, function or variable;

Debugged import:

- 'config' not found.

Original exception:

ImportError: No module named 'config'

我想要的:

From flask website.
>>>from yourapplication import User
>>> admin = User('admin', 'admin@example.com')

In my case-
>>>from app import Entry
>>>entry = Entry("title", "this is a post.")

Tags: infrompy模型importconfigappdb
1条回答
网友
1楼 · 发布于 2024-10-01 15:40:20

from app.models import Entry

您必须从应用程序的“模型”模块导入条目。在

{cd2>可能还需要添加任何自定义模块。在

添加到您的__init__

from .models import *

编辑:另一个有用的调试技巧是使用dir()函数查看包中包含的内容。在您的例子中,导入正在工作,因此您可以运行类似

dir(app)

With an argument, attempt to return a list of valid attributes for that object.

例如,这里是一个flask app I的返回列表写了。如果你在这里看不到你的模型,添加导入。在

enter image description here

相关问题 更多 >

    热门问题