When I run flask run
in the VS Code terminal an error shows saying
flask run
* Serving Flask app 'app.py' (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
Usage: flask run [OPTIONS]
Try 'flask run --help' for help.
Error: While importing 'app', an ImportError was raised.
I think its due to the way the project is structured and that possibly its giving errors when doing this sort of import.
from backend.config.dbconfig import pg_config
This is the project structure I'm currently using.
system
├───.github
├───.venv
├───.vscode
├───backend
│ ├───config
│ │ ├───__init__.py
│ │ └───dbconfig.py
│ ├───controller
│ │ ├───__init__.py
│ │ └───account.py
│ ├───model
│ │ ├───__init__.py
│ │ └───account.py
│ └───app.py
├───Documents
└───frontend
├───public
└───src
All the __init__.py are empty and from what I understand they are required.
I noticed that when I remove the backend.
from the import from backend.config.dbconfig import pg_config
, and add this to my app.py...
import sys
sys.path.append('./')
it works in VS Code and Heroku but PyCharm is now throwing errors saying Unresolved reference 'model'
Below are samples of my app after doing the "fixes" to have it run on Heroku and VS Code. The imports still show as errors in PyCharm but it runs in PyCharm. Since it's throwing errors I'm assuming that I'm going about it the wrong way, but I don't know what else to do to fix it.
This is a sample of my app.py
import sys
sys.path.append('./')
from flask import Flask, request, jsonify
from flask_cors import CORS
from controller.account import BaseAccount
app = Flask(__name__)
CORS(app)
@app.route('/account', methods=['GET', 'POST'])
def handleAccounts():
if request.method == 'GET':
return BaseAccount().getAllAccounts()
elif request.method == 'POST':
return BaseAccount().insertAccount(request.json)
else:
return jsonify("Method Not Allowed"), 405
controller/account.py
from flask import jsonify
from model.account import AccountDAO
class BaseAccount:
Is it possible to fix these errors without changing the structure of the project?
CodePudding user response:
This is because The Pycharm can add the workspace folder(system folder in your project) in the PYTHONPATH
automatically, but in the VSCode you need to add it manually.
You can add this in the settings.json file to solve the problem:
"terminal.integrated.env.windows": {
"PYTHONPATH": "${workspaceFolder};"
},