python - 我们如何从文件夹导入子文件夹?
问题描述
我有一个文件夹结构如下。我正在尝试有一个测试文件夹并在其中导入应用程序
(base) xadr-a01:redis-example adrianlee$ tree
.
├── Dockerfile
├── README.md
├── __pycache__
│ └── app.cpython-37.pyc
├── config
├── deployment.yaml
├── redis.yaml
├── requirements.txt
├── server
│ ├── __pycache__
│ │ ├── __init__.cpython-37.pyc
│ │ └── app.cpython-37.pyc
│ ├── app.py
│ ├── config.py
│ └── templates
│ └── index.html
└── tests
└── app.test
在我的 server/app.py 中,这是我的代码
#!/usr/bin/python
from flask import Flask, render_template, jsonify
from redis import Redis
import os
import json
app = Flask(__name__)
host = os.environ['REDIS_SERVICE']
redis = Redis(host=host, port=6379)
@app.route("/", methods=["GET"])
@app.route("/index", methods=["GET", "POST"])
def index():
counter = redis.incr("hits")
return render_template("index.html",counter=counter)
@app.route("/getdata", methods=["GET"])
def get_data():
data = redis.get("hits")
result = int(data)
return jsonify({'count': result})
if __name__ == "__main__":
app.run(
host="0.0.0.0",
port=8000,
debug=True
)
在我的测试/app.test 中,我正在尝试导入 server/app.py。
import unittest
import fakeredis
import json
from server.app import app
import app
from mock import patch, MagicMock
class BasicTestCase(unittest.TestCase):
counter = 1
def setUp(self):
self.app = app.app.test_client()
app.redis = fakeredis.FakeStrictRedis()
app.redis.set('hits',BasicTestCase.counter)
def create_redis(self):
return fakeredis.FakeStrictRedis()
def test_getdata(self):
response = self.app.get('/getdata', content_type='html/text')
data = json.loads(response.get_data(as_text=True))
expected = {'count': BasicTestCase.counter}
assert expected == data
def test_increment(self):
response = self.app.get('/', content_type='html/text')
result = self.app.get('/getdata', content_type='html/text')
data = json.loads(result.get_data(as_text=True))
expected = {'count': BasicTestCase.counter +1 }
assert expected == data
def test_index(self):
response = self.app.get('/', content_type='html/text')
self.assertEqual(response.status_code, 200)
if __name__ == '__main__':
unittest.main()
但是,我不断收到 modulenotfounderror。我不确定为什么我不能在子文件夹中导入我的应用程序
File "app.test", line 4, in <module>
from server.app import app
ModuleNotFoundError: No module named 'server'
我做错了什么?
解决方案
我想你需要一个相对进口。如果您编写 module.app Python 尝试从同一目录导入。我的情况是您需要从上述目录导入。
尝试这个:
from ..server.app import app
推荐阅读
- spring-boot - 如何在 H2 嵌入式数据库中创建虚拟函数以进行集成测试
- angular - 如何以角度为服务页面编写单元测试用例?
- google-apps-script - 在 Google 表格中通过 HYPERLINK 以编程方式检索数据
- java - ClassCastException getOrDefault 用于返回值对象
- java - 如何在 Java-8 中连接 2 个列表,以便 2 个列表中相同索引处的元素在结果列表中聚集在一起
- sql - SQL Server - 报告产生错误的查询
- qt - 如何在 qml.xml 中设置组件的大小和位置。这样它就可以支持不同的设备
- reactjs - 如何使用 create-react-app 部署 React 应用程序
- c# - MVVM中的窗口淡出
- c++ - 将 cuda 对象文件 .cu.o 与 CMake 链接原因:在函数 `__sti____cudaRegisterAll()' * 未定义引用 `__cudaRegisterLinkedBinary *