首页 > 解决方案 > 我们如何从文件夹导入子文件夹?

问题描述

我有一个文件夹结构如下。我正在尝试有一个测试文件夹并在其中导入应用程序

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

我做错了什么?

标签: pythonflask

解决方案


我想你需要一个相对进口。如果您编写 module.app Python 尝试从同一目录导入。我的情况是您需要从上述目录导入。

尝试这个:

from ..server.app import app

推荐阅读