gpt4 book ai didi

python - Flask 和 SQLAlchemy : No module named 'app' and NameError

转载 作者:太空宇宙 更新时间:2023-11-03 17:03:29 24 4
gpt4 key购买 nike

这里是菜鸟级别。看来我的 models.py 文件无法导入 init.py 中创建的 db 对象,但仍在创建 db 文件(blog.db)。由于我无法使用我的模型类(Entry(db.Model))从控制台内添加到数据库(db 对象本身在控制台中工作),我认为我从 models.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?)

__init__.py:

#!fakepy/bin/python3 (error happens with or without shebang(s))
from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config.from_object('config')
db = SQLAlchemy(app)

from app import models

models.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

config.py:

import os

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

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

数据库已创建...(控制台在/folder/打开,blog.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'
>>>

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

(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)

错误:直接运行 init.py 时没有名为“config”的模块。我认为这可能是一个单独的问题。

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.")

最佳答案

从 app.models 导入条目

您必须从应用程序的模型模块导入 Entry。

您可能还需要在 __init__ 中为任何自定义模块添加相对导入。

添加到您的__init__

从.models导入*

编辑:另一个有用的调试技巧 - 是使用dir()函数来查看包中包含的内容。在您的情况下,导入正在运行,因此您可以运行类似的东西

目录(应用程序)

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

例如,这里是我编写的 Flask 应用程序的返回列表。如果您在此处看不到您的模块,请添加导入。

enter image description here

关于python - Flask 和 SQLAlchemy : No module named 'app' and NameError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34817911/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com