简体   繁体   中英

Unable to run Flask from Terminal, “No module named 'my_app’”

I was expecting to get the following, but I'm just stuck at this point.

* Serving Flask app "app"
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

In the terminal, I tried running FLASK_APP=run.py flask run , then get

ModuleNotFoundError: No module named 'my_app'

When I tried changing the name in the command to FLASK_APP=__init__.py flask run , I get

Error: Failed to find application in module “myProject”. Are you sure it contains a Flask application? Maybe you wrapped it in a WSGI middleware or you are using a factory function.

Here's my project structure:

myProject/
    |—my_app/
        |— source/
            |— __init__.py
            |— other .py files
        |— static/
        |— templates/
    |— __init__.py
    |— someFile.sqlite
    |— run.py

myProject/run.py contains two lines of code:

from my_app import app 
app.run()

myProject/__init__.py contains nothing, blank.

myProject/source/__init__.py is also blank (but I guess these files just need to be here?)

I'm having trouble running the files under PyCharm, but when I run the file run.py in Spyder Anaconda, I get the expected message stating the server is running. Why is it working on Spyder, but not on PyCharm?

Before entering the topic, you should create a __init__.py under the my_app folder, it will turn it into a python package, so it can be imported.

When you execute flask run , flask will look for app instance in the module you specify with FLASK_APP , so app.run() is not needed in this situation.

What you need do?

  1. Delete run.py .
  2. Set FLASK_APP to the module name/import path where you create the flask app instance (maybe my_app.source ).
  3. Then just do flask run .

Found solution to the problem: PyCharm → preferences → project interpreter → (there wasn't flask installed) so I hit the + button to add package, searched for flask and installed it. After closing preferences, I came back and ran run.py and it worked!

The reason I knew that the package was missing from the interpreter I was using was because when I ran run.py, I would get

…/.conda/envs/python3.6/bin/python: No module named flask.

I had noticed that in the terminal when I ran pip show flask , it gave me the location of where it's installed:

Location: /Users/me/anaconda3/lib/python3.6/site-packages.

Upon looking at the two path locations, I determined that the interpreter wasn't looking in the correct place so when I changed the path, it started working.

Also, I didn't have to use any commands in the terminal to start the server. I only ran the run.py file.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM