gpt4 book ai didi

python - Flask:导入错误:无法导入名称 'db'

转载 作者:行者123 更新时间:2023-12-01 09:34:06 25 4
gpt4 key购买 nike

我是 Flask 新手。我正在尝试编写一个非常简单的应用程序。由于我来自 MVC 世界,所以我尝试按照简约的 MVC 结构来组织我的代码。所以我有以下内容:

priceChecker/
core/
controllers/
__init__.py
ItemController.py
models/
model.py
item.py
__init__.py
services
__init__.py
static/
templates/
__init__.py
priceChecker.py

价格检查器.py:

import os
from flask import Flask, request, session, g, redirect, url_for, abort, render_template, flash
from cassandra.cluster import Cluster

app = Flask(__name__)

# load config from this file, app.py
app.config.from_object(__name__)

#app.run(debug=True, use_debugger=False, use_reloader=False)

cluster = Cluster()

keyspace = 'testdb'
db = cluster.connect(keyspace)

from priceChecker.core.controllers.ItemController import ItemController

app.debug = True
@app.route('/search', methods=['GET', 'POST'])
def show_search_form():
item = ItemController()
if request.method == 'POST':
return 'post'
else:
a='get'

first_order = item.retrieveItems
for order in first_order:
print(order.shipname)

return render_template('search.html')

模型.py

from priceChecker.priceChecker import db


class Model(db):

def __init__(self, tableName):
self.__tablename__ = tableName

def getAll(self, conditions=[]):
try:
result = db.execute("SELECT * FROM " + self.__tablename__)
return result
except ValueError:
print("Oops, something went wrong!...")

项目.py

from priceChecker.core.models.model import Model as db

class Item(db):

def __init__(self):
super().__init__('orders')

def getAllItems(self):
return db.getAllItems()

ItemController.py

from priceChecker.core.models.item import Item

class ItemController:

def __init__(self):
self.item = Item()

def retrieveItems(self):
allItms = self.item.getAllItems()
return allItms

运行应用程序时,我遇到一些错误:

AttributeError: 'str' object has no attribute 'profile_manager'

如果我将以下行移动到顶部

from priceChecker.core.controllers.ItemController import ItemController

我懂了

ImportError: cannot import name 'db'

建议?

编辑:

屏幕上打印的错误:

    builtins.ImportError
ImportError: cannot import name 'db'

Traceback (most recent call last)

File "/Users/bigweld/Desktop/priceChecker/priceChecker/priceChecker.py", line 5, in <module>
from priceChecker.core.controllers.ItemController import ItemController
File "/Users/bigweld/Desktop/priceChecker/priceChecker/core/controllers/ItemController.py", line 1, in <module>
from priceChecker.core.models.item import Item
File "/Users/bigweld/Desktop/priceChecker/priceChecker/core/models/item.py", line 1, in <module>
Open an interactive python shell in this framefrom priceChecker.core.models.model import Model as db
File "/Users/bigweld/Desktop/priceChecker/priceChecker/core/models/model.py", line 2, in <module>
from priceChecker.priceChecker import db
ImportError: cannot import name 'db'
The debugger caught an exception in your WSGI application. You can now look at the traceback which led to the error.
To switch between the interactive traceback and the plaintext one, you can click on the "Traceback" headline. From the text traceback you can also create a paste of it. For code execution mouse-over the frame you want to debug and click on the console icon on the right side.

You can execute arbitrary Python code in the stack frames and there are some extra helpers available for introspection:

dump() shows all variables in the frame
dump(obj) dumps all that's known about the object

最佳答案

想通了!这个问题与我扩展类(class)的方式有关。

priceChecker.py 和 ItemController.py 都很好。

现在,让我们从 model.py 开始,我有:

from priceChecker.priceChecker import db

class Model(db):

def __init__(self, tableName):
self.__tablename__ = tableName

def getAll(self, conditions=[]):
try:
result = db.execute("SELECT * FROM " + self.__tablename__)
return result
except ValueError:
print("Oops, something went wrong!...")

当它应该是:

from priceChecker.priceChecker import db

class Model():

def __init__(self, tableName):
self.__tablename__ = tableName

def getAll(self, conditions=[]):
try:
result = db.execute("SELECT * FROM " + self.__tablename__)
return result
except ValueError:
print("Oops, something went wrong!...")

我猜它在这里失败了,因为我试图从 db 扩展 Model(),它是一个属性而不是一个类。

现在,item.py 应该是:

from priceChecker.core.models.model import Model

class Item(Model):

def __init__(self):
print('\n\nInitializing Item model...')
super().__init__('orders')

def getAllItems(self):
return Model.getAll(self)

此时一切工作正常,这最初是问题所在,但正如您所看到的,我使用了“模型”一词,因为我无法将其导入为“db”作为我的初始语句。

关于python - Flask:导入错误:无法导入名称 'db',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49684813/

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