channels.asgi.InvalidChannelLayerError: no BACKEND specified for default - python

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

Related

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.

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()

django.core.exceptions.ImproperlyConfigured: Requested setting DATABASES, but settings are not configured

Python is version 3.7.6, Django is version 3.0.8, I am trying to deploy from aws,
but adding container_commands gives an error
container_commands and DATABASES code
- container_commands: 01_migrate:
command: "django-admin.py migrate"
leader_only: true 02_compilemessages:
command: "django-admin.py compilemessages"
option_settings: aws:elasticbeanstalk:container:python:
WSGIPath: config.wsgi:application aws:elasticbeanstalk:application:environment:
DJANGO_SETTINGS_MODULE: config.settings
- DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql",
"HOST": os.environ.get("RDS_HOST"),
"NAME": os.environ.get("RDS_NAME"),
"USER": os.environ.get("RDS_USER"),
"PASSWORD": os.environ.get("RDS_PASSWORD"),
"PORT": "5432",
}
}
The problem seems to be caused by django-admin.py migrate
Enter django-admin.py migrate command
django.core.exceptions.ImproperlyConfigured: Requested setting
DATABASES, but settings are not configured. You must either define
the environment variable DJANGO_SETTINGS_MODULE or call
settings.configure() before accessing settings.
I get this message, I don't know how to fix it,
my github : https://github.com/dopza86/air_bnb_clone
I need help,thankyou

Gunicorn isnt finding 'memcache' module but it is found when I run python3 manage.py runserver 0.0.0.0:8000

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

Error: when I run flask app in visual studio code

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.

Categories

Resources