Python 如何从文件夹导入子文件夹?

Python 如何从文件夹导入子文件夹?,python,flask,Python,Flask,我有一个文件夹结构如下。我正在尝试有一个测试文件夹和导入应用程序内 (base) xadr-a01:redis-example adrianlee$ tree . ├── Dockerfile ├── README.md ├── __pycache__ │ └── app.cpython-37.pyc ├── config ├── deployment.yaml ├── redis.yaml ├── requirements.txt ├── server │ ├── __pycache_

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

(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
在my 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中,我正在尝试导入服务器/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'
文件“app.test”,第4行,在
从server.app导入应用程序
ModuleNotFoundError:没有名为“服务器”的模块

我错了什么?

我想你需要相对导入。如果编写module.app,Python将尝试从同一目录导入。我需要从上面的目录导入您的案例

试试这个:

from ..server.app import app

这回答了你的问题吗?