Error: when I run flask app in visual studio code - python

I write a minimum demo flask app in vscode:
from flask import Flask
app = Flask(__name__)
#app.route('/')
def index():
return "Hello World!"
When I run it in vscode, it give me an error:
Error: Could not import "D".
The problem is I don't import any "D" packages, so I have no idea where this error come from and how to debug it.
I try to run this app in powershell, and it works as expected. So I think there may be some problem in my personal configurations of vscode. Below is my launch.json file of this project:
{
"name": "Python: Flask (0.11.x or later)",
"type": "python",
"request": "launch",
"module": "flask",
"env": {
"FLASK_APP": "${workspaceFolder}/hello.py"
},
"args": [
"run",
"--no-debugger",
"--no-reload"
]
}
My user settings:
{
"workbench.startupEditor": "newUntitledFile",
"explorer.confirmDelete": false,
"git.enableSmartCommit": true
}
My workspace settings:
{
"python.pythonPath": "${workspaceRoot}/venv/Scripts/python.exe",
"python.formatting.provider": "yapf",
}
Thanks in advance for Any suggestions on where the problem is or how to debug it.

I did two things two work around this:
I renamed my app to app.py (so in your case, rename "hello.py" to "app.py").
I set my launch config "FLASK_APP" entry to:
"FLASK_APP": "PATH_FROM_CWD_TO_APP_FOLDER\\app.py"
What is PATH_FROM_CWD_TO_APP_FOLDER? Suppose you are running your app in the folder \foo, and app.py is in \foo\bar\baz.* Then PATH_FROM_CWD_TO_APP_FOLDER is bar\baz, and your "FLASK_APP" entry would be
"FLASK_APP": "bar\\baz\\app.py"
*How do you know which folder you're running your app from? Check the terminal and see what directory the commands to run flask are being run from. That's the directory your app is being run from.

Related

Run Flask/Dash App with VSCode Debugger not working

When I run my Dash app from the command line using
export PYTHONPATH=./src/ && python ./src/pdv/app.py
it runs properly, however, when I try to run it with the debugger (using the following configuration in my launch.json
{
"name": "Python: Current File",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal",
"env": { "PYTHONPATH": "${workspaceRoot}/src/"}
},
I get the following error:
Dash is running on http://127.0.0.1:8050/
* Serving Flask app 'app' (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: on
No module named app
Any ideas what's wrong with my debug configuration?
The file you are referring to is the launch.json, if the content of that file is contained within the settings.json file it cannot work.
I leave you an example of how the settings.json and launch.json files should be configured to debug a python application in visual studio code:
settings.json
{
"python.defaultInterpreterPath": "<YOUR_PYTHON_EXE_IN_VIRTUALENV_PATH>",
"python.analysis.extraPaths": [
"src"
]
}
launch.json
{
"version": "0.2.0",
"configurations" : [
{
"name": "local",
"type": "python",
"stopOnEntry": false,
"request": "launch",
"program": "${workspaceFolder}/src/app.py",
"console": "integratedTerminal",
"justMyCode": false,
"cwd": "${workspaceFolder}/src"
}
]
}
At the following link you can find the documentation on how to set the debugger in visual studio code for a flask application
the code snippet in your article should belong to launch.json, paste it into setting.json will cause this error.You could create a new launch.json in the debug tab.
For anyone with same issue, I ended up just using the native Flask server instead of the Dash wrapper, by adding the following to my launch.json
{
"name": "Debug pdv plots",
"type": "python",
"request": "launch",
"module": "flask",
"env": {
"PYTHONPATH": "${workspaceRoot}/src/",
"FLASK_APP": "${workspaceRoot}/src/pdv/app",
"FLASK_ENV": "development",
"FLASK_DEBUG": "1"
},
"args": [
"run",
],
}

VS Code: Unable to debug Connexion/Flask app?

I'm developing an API running on a Connexion-Flask app using Visual Studio Code. When started with flask run it works fine.
But when I'm trying to debug this app using the VS Code debugger I get the following error message:
Traceback (most recent call last):
File "d:\QT_Code\itk-demo-configdb\source\app.py", line 3, in <module>
from connexion import FlaskApp
ModuleNotFoundError: No module named 'connexion'
The launch.json that I use for debugging is the following (which I found in this thread which asks a very similar question (but I can't make a comment there):
{
"version": "0.2.0",
"configurations": [
{
"name": "Python: Connexion",
"type": "python",
"request": "launch",
"module": "connexion",
"env": {
"FLASK_APP": "app.py",
"FLASK_ENV": "development",
"FLASK_DEBUG": "1"
},
"args": [
"run",
"./db_api",
"--port",
"8080"
],
"jinja": true
}
]
}
My app.py Is the following:
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from connexion import FlaskApp
from .config import APIConfig
app = FlaskApp(__name__, specification_dir='db_api/', options={"swagger_ui": True})
flask_app = app.app
flask_app.config.from_object(APIConfig)
db = SQLAlchemy(flask_app)
migrate = Migrate(flask_app, db)
app.add_api('db_openapi.yml')
if __name__ == '__main__':
app.run(host="0.0.0.0", port=8080,debug=True)
I'm using the same virtual environment when starting via flask run and the debugger. So I don't understand why it says that there is no connexion module. Before I implemented Connexion the VS Code debugger worked fine, but now I can't seem to get it working.
Thanks in advance for any help!
Just in case anybody else has the same problem in the future.
This seems to be some kind of VS Code bug.
I tried starting my app via the command line and it did work. After that, I reinstalled all python packages in my VS Code venv (via my requirements.txt) but it didn't help.
Ultimately removing the virtual environment I used in VS code and making a new one solved my problem.

No module named app , While running Flask app

I'm new to using flask, I tried to execute a basic flask app in Visual-Studio-code . but I'm getting,
No Module named app
My code is:
from flask import Flask
app = Flask(__name__)
#app.route('/')
def index():
return "Hello, World"
if __name__ == "__main__":
app.run(debug=True)
path :
The output terminal:
PS C:\Users\Rakesh\Desktop\The project copy> c:; cd 'c:\Users\Rakesh\Desktop\The project copy'; & 'C:\Python39\python.exe' 'c:\Users\Rakesh\.vscode\extensions\ms-python.python-2021.5.926500501\pythonFiles\lib\python\debugpy\launcher' '52116' '--' 'c:\Users\Rakesh\Desktop\The project copy\env\app.py'
Serving Flask app 'app' (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: on
Restarting with stat
No module named app
You probably haven't set the settings.json file to allow visual studio code to run the application via virtualenv. Check out this link: https://code.visualstudio.com/docs/python/tutorial-flask (spoiler: you have to configure the variabile python.pythonPath to specify to vs code where is your python installation).
A possible example of the settings.json file to configure visual studio code to use virtualenv:
{
"python.pythonPath": "Scripts\\python.exe",
"files.exclude" : {
"**/.git" : true,
"Lib" : true,
"lib" : true,
"Include" : true,
"Scripts" : true,
"**/__pycache__": true
}
}
P.S. as mentioned by Edo Akse in the comment, it would be good practice not to put your own py files directly in the virtual environment folder
The path of app.py was inside the virtual environment , thus it is not working.
Moving it out of that folder woks.

Deploying django channels on heroku

I have created a standard django application with startproject, startapp, etc. and I want to deploy it on heroku. When I was using gunicorn I solved the directory issue like so:
web: gunicorn --pythonpath enigma enigma.wsgi
with the --pythonpath option. But now I am using django channels and so it is daphne. Is there an equivalent? I have tried everything but for the life of me I can't get the project to start. I always get issues with the settings file, apps not loaded or another assortment of cwd-related issues.
As given in the Heroku Django channels tutorial, I have tried:
daphne enigma.asgi:channel_layer --port 8888
This led to a variety of module not found errors with asgi and settings.
I also tried
daphne enigma.enigma.asgi:channel_layer --port 8888
This led to module not found enigma.settings errors.
I also tried
cd enigma && daphne enigma.asgi:channel_layer --port 8888
Which led to Django apps not ready errors.
I also tried moving the Procfile and pipfiles into the project directory and deploying that subdirectory but once again I got apps not ready errors.
I have now started temporarily using
cd enigma && python manage.py runserver 0.0.0.0:$PORT
But I know that you're not supposed to do this in production.
Try this:
Procfile
web: daphne enigma.asgi:application --port $PORT --bind 0.0.0.0 -v2
chatworker: python manage.py runworker --settings=enigma.settings -v2
settings.py
if DEBUG:
CHANNEL_LAYERS = {
"default": {
"BACKEND": "channels_redis.core.RedisChannelLayer",
"CONFIG": {
"hosts": [("localhost", 6379)],
},
},
}
else:
CHANNEL_LAYERS = {
"default": {
"BACKEND": "channels_redis.core.RedisChannelLayer",
"CONFIG": {
"hosts": [os.environ.get('REDIS_URL', 'redis://localhost:6379')],
},
},
}
asgi.py
import os, django
from channels.routing import get_default_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'enigma.settings')
django.setup()
application = get_default_application()

channels.asgi.InvalidChannelLayerError: no BACKEND specified for default

I'm trying to use channels for a django app.I have installed all the required dependencies (i think). I have listed 'channels' on INSTALLED_APPS of myapp/settings.py.However,I run daphne ( daphne chat.asgi:channel_layer --port 8888)-( no error message on cmd), then when i run python manage.py runworker which gives an Error message that says - "channels.asgi.InvalidChannelLayerError: no BACKEND specified for default". . I'm novice for django, i have asgi.py as
import os
import channels.asgi
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "chat.settings")
channel_layer = channels.asgi.get_channel_layer()
But in my myapp/settings.py, i have specified the BACKEND specified for default.Can you please suggest a solution to this error? Here is a probable solution,but the asgi_redis was current in my django1.10. I'm trying to run myapp on my local machine.
CHANNEL_LAYERS = {
"default": {
"BACKEND": "asgi_redis.RedisChannelLayer",
"CONFIG": {
#"hosts": [os.environ.get('REDIS_URL', 'redis://localhost:6379')],
},
"ROUTING": "myproject.myapp.routing.channel_routing",
},
}
Add this to the top of your settings.py
import asgi_redis
Also, make sure that you have installed Redis
pip install asgi_redis

Categories

Resources