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.
Related
When I try to send a request from the client to my socketio flask server that is deployed on app engine I recieve the following error:
has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I did put the following line in my python server script:
socketio = SocketIO(app, cors_allowed_origins='*')
I also added the folling line:
CORS(app)
What am I doing wrong?
I tried changing the app.yaml with the Allow_cors_origin of the url handler, installing flask-cors package, nothing worked
EDIT:
I found in the app engine the following message while debugging:
{
"textPayload": "The client is using an unsupported version of the Socket.IO or Engine.IO protocols (further occurrences of this error will be logged with level INFO)",
"insertId": "5fca5af900064b8faf6f9267",
"resource": {
"type": "gae_app",
"labels": {
"module_id": "default",
"project_id": "island-battles",
"version_id": "20201204t174848",
"zone": "europe-west6-3"
}
},
"timestamp": "2020-12-04T15:51:21.412559Z",
"labels": {
"clone_id": "00c61b117cf0689fb08fabba9037f4624c77b480da8e9472be2b02038e0fe7d2d8dcac81021c"
},
"logName": "projects/island-battles/logs/stderr",
"receiveTimestamp": "2020-12-04T15:51:21.465294012Z"
}
How do I fix this? Thanks
SECOND EDIT:
Everything works fine in my local version, the problem lies with app engine
If you're using Flask-SocketIO make sure to install a compatible version, the latest is not compatible with python-socketio 3.1.2 and you will get an error.
I ran:
pip install python-socketio==3.1.2
as suggested by Oliver but had error because I had Flask-SocketIO version 5.0.1, so I ran the following:
pip install flask-socketio==4.3.2
and that solved my issues.
Ultimately you'd want flask-socketio-4.3.2 python-engineio-3.14.2 python-socketio-4.6.1
Similar conclusion reached here:
https://github.com/miguelgrinberg/Flask-SocketIO/issues/1432
https://github.com/juharris/switch-remoteplay/issues/37
This error is due to an unsupported Socket IO version. I imagine you are using the latest version, however, App Engine usually takes some time to support the latest versions. Try downgrading it to v3.x, maybe even v2.x.
You can install specific versions of packages with $ pip install <PACKAGE>==<VERSION>, in this case, for example: $ pip install python-socketio==3.1.2.
I'm having trouble with my server. This is a multitenant project, the one in the Windows server is working fine, but the one in Ubuntu is giving me a "No module named 'memcache'" error although it is installed. I know it is installed because I ran a "python3 manage.py runserver 0.0.0.0:8001' and when I accessed by my personal browser worked fine. Gunicorn is pointing properly to my virtual env and there are no log errors when I restart the service, I'm quite desperate now.
My configuration:
CACHE_HOST = os.getenv('cache_host', '127.0.0.1')
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': f'{CACHE_HOST}:11211',
},
'estadisticos': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': f'{CACHE_HOST}:11211',
}
}
So is your memcache host running on localhost? if not perhaps gunicorn is started as a service and doesn't have the right value of the env var cache_host
in any case I'd suggest you add prints at the end of your settings file
and one print to see whether you're using the same ptyhon for gunicorn and your command line:
import sys # if not already imported in settings
print("my python is ", sys.executable)
print("CACHES", CACHES, file=sys.stderr)
or if you can't see stdout:
with open("/tmp/mylog.log") as fout:
print("my python is ", sys.executable, file=fout)
print("CACHES", CACHES, file=fout)
Check that python3 manage.py runserver 0.0.0.0:8001 creates the same trace as running gunicorn.
delete the file `/tmp/mylog.log` between the two runs.
If outputs are identical, but memcached is working for one and not the other, then you had to check that the django settings are not overridden somewhere else
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.
I've just recently begun trying to wrap my head around Docker and have managed to get a development machine up and running. What i'm now trying to do is to be able to use the debugger in Visual Studio Code in my python application (specifically Django).
I've tried following the limited documentation of the python extension for VS Code which explains the parameters for remote debugging.
Dockerfile
FROM python:3.5.2
RUN apt-get update \
--no-install-recommends && rm -rf /var/lib/apt/lists/* \
&& mkdir -p /code \
EXPOSE 8000
WORKDIR /code
COPY requirements.txt /code
RUN /bin/bash --login -c "pip install -r requirements.txt"
ADD . /code
CMD []
docker-compose.yml
version: '2'
services:
db:
image: postgres
web:
build: .
volumes:
- .:/code
ports:
- "8000:8000"
command: bash -c "./wait-for-it.sh db:5432 && python manage.py migrate && python manage.py runserver 0.0.0.0:8000 --noreload"
depends_on:
- db
launch.json
{
"name": "Attach (Remote Debug)",
"type": "python",
"request": "attach",
"localRoot": "${workspaceRoot}",
"remoteRoot": "/code",
"port": 8000,
"secret": "debug_secret",
"host": "localhost"
}
I've also added the line ptvsd.enable_attach("debug_secret", address = ('0.0.0.0', 8000)) to one of the project files
The Issue
When ever I start the debugger nothing happens and it looks like VS Code is waiting for a breakpoint to hit. But it never does.
Any ideas?
EDIT: Minor update
I have tried using different ports for the debugger aswell as exposing the new ports in docker-compose.yml without any success. It looks like the attach is successfull because the debugger doesn't crash but no breakpoint is triggered. I'm really stuck on this one.
Solution
See answer from theBarkman.
I'll add that I was unable to use a secret to get this working. I did the following:
manage.py
import ptvsd
ptvsd.enable_attach(secret=None, address=('0.0.0.0', '3000'))
launch.json
{
"name": "Attach Vagrant",
"type": "python",
"request": "attach",
"localRoot": "${workspaceRoot}",
"remoteRoot": "/code",
"port": 3000,
"secret": "",
"host":"localhost"
}
I've had the most success remote debugging dockerized Django projects by throwing the ptvsd code into my manage.py file and turning off Django's live code reload.
Since Django essentially spins up 2 servers when you runserver (one for that live code reloading, and the other for the actual app server`, ptvsd seems to get really confused which server it should watch. I could sort of get it to work by waiting for attachment, try/excepting the enable_attach method or breaking into the debugger - but breakpoints would never work, and I could only seem to debug a single file at a time.
If you use the django flag --noreload when spinning up the server, you can throw the ptvsd inside the manage.py file without all the waiting / breaking into the debugger nonsense, and enjoy a much more robust debugging experience.
manage.py:
import ptvsd
ptvsd.enable_attach(secret='mah_secret', address=('0.0.0.0', 3000))
run teh server:
python manage.py runserver 0.0.0.0:8000 --noreload
Hope this helps!
I was trying to do something very similar to you and came across this issue/comment:
https://github.com/DonJayamanne/pythonVSCode/issues/252#issuecomment-245566383
In there it describes that in order to use breakpoints you need to use the ptvsd.break_into_debugger() function.
As an example:
import ptvsd
ptvsd.enable_attach(secret='my_secret',address = ('0.0.0.0', 3000))
ptvsd.wait_for_attach()
ptvsd.break_into_debugger()
As soon as I added this in my python script, my breakpoints worked. Hopefully it's of some use.
Edit Jan 24, 2017
In my DockerFile I installed ptvsd:
FROM kaixhin/theano
RUN pip install ptvsd
WORKDIR /src
EXPOSE 3000
ENTRYPOINT ["python","src/app.py"]
COPY . /src
It looks like your installing dependencies via your requirements.txt file, is ptvsd in your requirements.txt?
a couple trouble shooting tips:
1) make sure your debug port is open. run this from your host.
nc -zv test.example.com 30302
2) make sure your webserve does not reload your app automatically. That will break the debugger connection. Put a print or log statement in your code which runs at startup time to make sure your app is not being loaded twice. This is for socketio running on flask. but django and other webservers have something similar.
socketio.run(app, host="0.0.0.0", port=5000, debug=True, use_reloader=False)
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