- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我。前言:应用目录结构和模块在文末列出。
二。问题陈述:如果未设置 PYTHONPATH,应用程序会运行,但单元测试失败并显示 ImportError: No module named models.transactions。尝试导入时会发生这种情况app.py 中的事务。如果 PYTHONPATH 设置为 /sandbox/app
应用程序和unittest 运行没有错误。解决方案的约束是不必设置 PYTHONPATH,并且不应以编程方式修改 sys.path。
三。详细信息:考虑设置 PYTHONPATH 并且 test_app.py
作为包 /sandbox$ python -m unittest tests.test_app
运行的情况。查看 __main__
的打印语句散布在整个代码中:
models : app.models.transactions
models : models.transactions
resources: app.resources.transactions
app : app.app
test : tests.test_app
单元测试首先导入应用程序,因此有 app.models.transactions
。接下来导入那个appattempts 是 resources.transactions
。导入时,它会自己导入 models.transactions
,并且然后我们看到 app.resources.transactions
的 __name__
。接下来是 app.app
导入,最后是单元测试模块 tests.test.app
。设置 PYTHONPATH 允许应用程序解析 models.transactions!
一种解决方案是将 models.transactions
放在 resources.transaction
中。但是还有另一种方法来处理这个问题吗?
为了完整起见,当应用程序运行时,__main__
的打印语句是:
models : models.transactions
resources: resources.transactions
app : __main__
这是预期的,并且没有尝试在 /sandbox/app
之上或横向导入。
四。附录
A.1 目录结构:
|-- sandbox
|-- app
|-- models
|-- __init__.py
|-- transactions.py
|-- resources
|-- __init__.py
|-- transactions.py
|-- __init__.py
|-- app.py
|-- tests
|-- __init__.py
|-- test_app.py
A.2 模块:
(1) 应用:
from flask import Flask
from models.transactions import TransactionsModel
from resources.transactions import Transactions
print ' app : ', __name__
def create_app():
app = Flask(__name__)
return app
app = create_app()
if __name__ == '__main__':
app.run(host='127.0.0.1', port=5000, debug=True)
(2) 模型.交易
print ' model : ', __name__
class TransactionsModel:
pass
(3) 资源.事务:
from models.transactions import TransactionsModel
print ' resources: ', __name__
class Transactions:
pass
(4) 测试.test_app
import unittest
from app.app import create_app
from app.resources.transactions import Transactions
print ' test : ', __name__
class DonationTestCase(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_transactions_get_with_none_ids(self):
self.assertEqual(0, 0)
if __name__ == '__main__':
unittest.main()
最佳答案
值得一提的是,Flask 文档说将应用程序作为一个包运行,并设置环境变量:FLASK_APP
.然后应用程序从项目根目录运行:$ python -m flask run
.现在导入将包括应用程序根目录,例如 app.models.transactions
.由于 unittest 以相同的方式运行,作为项目根目录中的包,所有导入也在那里解析。
问题的症结可以用下面的方式来描述。 test_app.py 需要访问横向导入,但如果它作为脚本运行,例如:
/sandbox/test$ python test_app.py
它有<code>__name__</code>==<code>__main__</code>
.这意味着导入,例如 from models.transactions import TransactionsModel
, 将不会被解决,因为它们在横向上并且在层次结构中不较低。要解决此问题,可以将 test_app.py 作为一个包运行:
/sandbox$ python unittest -m test.test_app
-m
switch 告诉 Python 这样做。现在包可以访问 app.model
因为它在 /sandbox
中运行. test_app.py
中的进口必须反射(reflect)这种变化并变成类似这样的东西:
from app.models.transactions import TransactionsModel
要使测试运行,应用程序中的导入现在必须是相对的。例如,在 app.resources 中:
from ..models.transactions import TransactionsModel
所以测试成功运行,但如果应用程序运行失败!这就是问题的症结所在。当应用程序作为脚本从 /sandbox/app$ python app.py
运行时它达到了这个相对进口 ..models.transactions
并返回程序试图导入顶层以上的错误。修复一个,破坏另一个。
如何在不设置 PYTHONPATH 的情况下解决这个问题?一个可能的解决方案是在包中使用条件 <code>__init__</code>.py
做有条件的进口。 resources
的示例包是:
if __name__ == 'resources':
from models.transactions import TransactionsModel
from controllers.transactions import get_transactions
elif __name__ == 'app.resources':
from ..models.transactions import TransactionsModel
from ..controllers.transactions import get_transactions
要克服的最后一个障碍是我们如何将其拉入 resources.py
.在 <code>__init__</code>.py
中完成的进口绑定(bind)到该文件并且不可用于 resources.py
.通常一个人会在 resources.py
中包含以下导入:
import resources
但是,再一次,是resources
吗?或 app.resources
?对我们来说,困难似乎已经越走越远了。 importlib
提供的工具可以在这里提供帮助,例如以下内容将进行正确的导入:
from importlib import import_module
import_module(__name__)
还有其他方法可以使用。例如,
TransactionsModel = getattr(import_module(__name__), 'TransactionsModel')
这修复了当前上下文中的错误。
另一个更直接的解决方案是在模块本身中使用绝对导入。例如,在资源中:
models_root = os.path.join(os.path.dirname(__file__), '..', 'models')
fp, file_path, desc = imp.find_module(module_name, [models_root])
TransactionsModel = imp.load_module(module_name, fp, file_path,
desc).TransactionsModel
TransactionType = imp.load_module(module_name, fp, file_path,
desc).TransactionType
关于使用 sys.path.append(app_root)
更改 PYTHONPATH 的注意事项在 resources.py
.这很好用,只需几行代码就可以了。此外,它只更改执行文件的路径并在完成后恢复。似乎是单元测试的一个很好的用例。一个问题可能是何时将应用程序移动到不同的环境。
关于Python 运行 Unittest 作为包导入错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47935707/
我已经使用 vue-cli 两个星期了,直到今天一切正常。我在本地建立这个项目。 https://drive.google.com/open?id=0BwGw1zyyKjW7S3RYWXRaX24tQ
您好,我正在尝试使用 python 库 pytesseract 从图像中提取文本。请找到代码: from PIL import Image from pytesseract import image_
我的错误 /usr/bin/ld: errno: TLS definition in /lib/libc.so.6 section .tbss mismatches non-TLS reference
我已经训练了一个模型,我正在尝试使用 predict函数但它返回以下错误。 Error in contrasts<-(*tmp*, value = contr.funs[1 + isOF[nn]])
根据Microsoft DataConnectors的信息我想通过 this ODBC driver 创建一个从 PowerBi 到 PostgreSQL 的连接器使用直接查询。我重用了 Micros
我已经为 SoundManagement 创建了一个包,其中有一个扩展 MediaPlayer 的类。我希望全局控制这个变量。这是我的代码: package soundmanagement; impo
我在Heroku上部署了一个应用程序。我正在使用免费服务。 我经常收到以下错误消息。 PG::Error: ERROR: out of memory 如果刷新浏览器,就可以了。但是随后,它又随机发生
我正在运行 LAMP 服务器,这个 .htaccess 给我一个 500 错误。其作用是过滤关键字并重定向到相应的域名。 Options +FollowSymLinks RewriteEngine
我有两个驱动器 A 和 B。使用 python 脚本,我在“A”驱动器中创建一些文件,并运行 powerscript,该脚本以 1 秒的间隔将驱动器 A 中的所有文件复制到驱动器 B。 我在 powe
下面的函数一直返回这个错误信息。我认为可能是 double_precision 字段类型导致了这种情况,我尝试使用 CAST,但要么不是这样,要么我没有做对...帮助? 这是错误: ERROR: i
这个问题已经有答案了: Syntax error due to using a reserved word as a table or column name in MySQL (1 个回答) 已关闭
我的数据库有这个小问题。 我创建了一个表“articoli”,其中包含商品的品牌、型号和价格。 每篇文章都由一个 id (ID_ARTICOLO)` 定义,它是一个自动递增字段。 好吧,现在当我尝试插
我是新来的。我目前正在 DeVry 在线学习中级 C++ 编程。我们正在使用 C++ Primer Plus 这本书,到目前为止我一直做得很好。我的老师最近向我们扔了一个曲线球。我目前的任务是这样的:
这个问题在这里已经有了答案: What is an undefined reference/unresolved external symbol error and how do I fix it?
我的网站中有一段代码有问题;此错误仅发生在 Internet Explorer 7 中。 我没有在这里发布我所有的 HTML/CSS 标记,而是发布了网站的一个版本 here . 如您所见,我在列中有
如果尝试在 USB 设备上构建 node.js 应用程序时在我的树莓派上使用 npm 时遇到一些问题。 package.json 看起来像这样: { "name" : "node-todo",
在 Python 中,您有 None单例,在某些情况下表现得很奇怪: >>> a = None >>> type(a) >>> isinstance(a,None) Traceback (most
这是我的 build.gradle (Module:app) 文件: apply plugin: 'com.android.application' android { compileSdkV
我是 android 的新手,我的项目刚才编译和运行正常,但在我尝试实现抽屉导航后,它给了我这个错误 FAILURE: Build failed with an exception. What wen
谁能解释一下?我想我正在做一些非常愚蠢的事情,并且急切地等待着启蒙。 我得到这个输出: phpversion() == 7.2.25-1+0~20191128.32+debian8~1.gbp108
我是一名优秀的程序员,十分优秀!