When I try to run my very simple Flask application using flask run
it does not work but when I cd src
and python server.py
it does work.
File structure:
my_project
|____init__.py
|
|__src
| |____init__.py
| |__server.py
| |__chat.py
|
|__test
| |____init__.py
| |__test_server.py
| |__test_chat.py
|
|__FLASK_ENV_VARS.sh
server.py
from flask import Flask, jsonify
import chat
api = Flask(__name__)
@api.route('/')
def root():
message = chat.say_hello()
return jsonify(message=message)
if __name__ == '__main__':
api.run(debug=True)
In order to get the tests to pass, I need to from src import chat
. When I leave it as import chat
the server runs when I try python server.py
but not flask run
(which doesn't run either way of importing chat). Interestingly, I get a red squggly line under chat from my IDE when import chat
that goes away with from src import chat
.
test_server.py
import pytest
from src.server import api
def test_route(client):
response = client.get('/')
assert response.status_code == 200
expected_data = b'{"message":"Welcome message here"}\n'
assert response.data == expected_data
@pytest.fixture
def client():
api.testing = True
client = api.test_client()
return client
The content of the environment variables shell script is
export FLASK_ENV=development
export FLASK_DEBUG=1
export FLASK_APP=server.py
I have tried making FLASK_APP
both src.server.py
and server.py
, neither currently works. Of course I remember to run the shell script and echo the variables to ensure that they have changed.
The error I get from flask run
is flask.cli.NoAppException: Could not import "my_project.server".
When I cd src
and flask run
I get flask.cli.NoAppException: While importing "my_project.src.server", an ImportError was raised:
The problem, I suspect lies with the way chat is imported. The tests only run with from src import chat
. When I run python server.py
I have to have only import chat
or it doesn't work. I get ModuleNotFoundError: No module named 'chat'
as part of the stack trace or ModuleNotFoundError: No module named 'src'
depending on which style of import was used. I'm not sure what I am getting wrong here. I am inclined to think that from src import chat
is correct since this is what makes the tests pass, however I can't get this to work at all.
Did you try $env:FLASK_APP = "server.py"
try Something like this too , export FLASK_APP=my_project/src/server.py; flask run
export FLASK_APP=my_project/src/server.py; flask run
You can also mention app = Flask (__name__) in __init__.py and then execute flask run
通过将server.py中有问题的导入更改为
from my_project.src import chat
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.