Django cookiecutter Project code won't run - django

I'm currently working on a django project built with django cookiecutter. I'm running both redis server and the redis client but anytime I run the django server it keeps giving the below error
raise ImproperlyConfigured(error_msg)
django.core.exceptions.ImproperlyConfigured: Set the CELERY_BROKER_URL environment variable
Below is the configurations of my .env file in my config folder
DEBUG=True
SECRET_KEY=12345
EMAIL_USE_TLS=True
EMAIL_HOST=smtp.gmail.com
EMAIL_PORT=587
EMAIL_HOST_USER=darkolawrence#gmail.com
EMAIL_HOST_PASSWORD=**********
DEFAULT_FROM_EMAIL=noreply#gmail.com
BRAINTREE_MERCHANT_ID=5pbrjk4gmztd5m8k6dg
BRAINTREE_PUBLIC_KEY=by84t6rfx9nz3vs6kegw
BRAINTREE_PRIVATE_KEY=202056899b37713b1faeb093207160ff2e
BROKER_URL=amqp://
CELERY_RESULT_BACKEND=db+sqlite:///results.sqlite

I think you need to setting.py Configure celery in the file_ BROKER_ URL, as follows:
CELERY_BROKER_URL = 'redis://hostname:6379/6'
The last bit 6 is the number represents the databases of Redis, 0-15 is available.

Related

Python Flask Web application not able to deploy on Heroku using Waitress server

I am trying to deploy my Flask application on Heroku PaaS Cloud Service. It, however, works on localhost with no errors. I am using git for version control and pushing to Heroku. Initially, as a web server, I used 'gunicorn' but later came to know it is useful for UNIX distributions. So I resorted my webserver to 'waitress'. I saw some of the posts and tried everything in the Procfile for hosting to Heroku. My Procfile reads like: web: waitress-serve --port=$PORT app:app. I also know that the first app in this line is the package and the second app is the name of the instance best to my knowledge. I even changed from app to myapp, website and I have all the packages including these mentioned are in my VS code editor. But my application is not getting deployed onto Heroku and it gives Application Error. Now when I check the logs using heroku logs --tail it gives me the following error as in the screenshot. Any help would be highly obliged. I am trying this for 23 hours. Heroku Logs
The Procfile looks correct but the problem could be that the file (app.py) and the variable (app) have the same name.
I suggest the following approach, in app.py
# define Flask app
def create_app():
try:
web_app = Flask(__name__)
logging.info('Starting up..')
return web_app
except Exception as e:
logging.exception(e)
# retrieve port
def get_port():
return int(os.environ.get("PORT", 5000))
# start Flask app
if __name__ == '__main__':
web_app = create_app()
web_app.run(debug=False, port=get_port(), host='0.0.0.0')
The application can be launched from the Procfile with
web: waitress-serve --port=$PORT --call 'app:create_app'

How to fix the issue "django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet"?

I have deployed my django webapp to my heroku server and it was working fine until I added a websocket connection that shows the contents of a model object in a separate url as soon as that object is created. For this, I used Django channels with a redis server hosted on redislabs. To run asgi app, I tried to use daphne server but when I try to run the daphne server with the following command:
$daphne smartResturant.asgi:channel_layer --port 8888
, it says
"django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet"
My asgi.py
import os
import django
from smartResturant.routing import get_default_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "smartResturant.settings")
django.setup()
application = get_default_application()
My settings.py
ASGI_APPLICATION = 'smartResturant.routing.application'
CHANNEL_LAYERS = {
'default': {
'BACKEND': 'channels_redis.core.RedisChannelLayer',
'CONFIG': {
"hosts": ['redis://:xxxxxxxx#redis-13131.c85.us-east-1-2.ec2.cloud.redislabs.com:13131']
},
},
}
It works fine when I run locally without using daphne server. But I found out that to run asgi based apps on a hosted server, you have to use daphne server and I am unable to run it. Any help will be appreciated!
This error may occur when you are adding an app in INSTALLED_APPS in the settings.py file but you do not have that app installed in your computer. You have two solution:
Install that app using package managers like pip in django
Or Comment out that installed app in the settings.py file
This error may also arise if you are not in your virtual environment which you may have created for your project.
When you run commands like python manage.py runserver, django automatically runs django.setup for you using DJANGO_SETTINGS_MODULE environment variable. So the code in views.py can access models, because django ensures that django.setup is called before views are imported. Since you are running your shell script as a simple python file, so you must manually call django.setup.

.env not working with Django with supervisor

I have a Django 2.2 project and all secrets are in .env file.
I'm using a library dotenv to load .env to the Django application in the manage.py file
import dotenv
def main():
# Read from .env file
env_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), '.env')
dotenv.read_dotenv(env_file)
....
The environment file is working and is loaded well when running locally.
On the server, I'm using the supervisor to run the application with the following configuration.
[supervisord]
[program:myapp]
command=/var/www/html/app/start_gunicorn.sh
directory=/var/www/html/app/
autostart=true
autorestart=true
stopasgroup=true
stopsignal=QUIT
logfile=/home/ubuntu/log/supervisor/supervisor.log
logfile_maxbytes=5MB
logfile_backups=10
loglevel = info
stderr_logfile=/home/ubuntu/log/supervisor/qcg-backend.err.log
stdout_logfile_maxbytes=5MB
stdout_logfile_backups=10
stdout_logfile=/home/ubuntu/log/supervisor/qcg-backend.out.log
stderr_logfile_maxbytes=5MB
stderr_logfile_backups=10
But the environment variables are not loaded and not working in Django.
Running following command from SSH console is working.
python manage.py shell
import os
os.environ.get('DEBUG')
> True
But running the application, environment variables are not accessible and not applied in the application.
manage.py is not invoked when running Django in production. From the dotenv docs, it says that you should add the loader code to the top of wsgi.py as well.
I think putting it on settings.py is more convenient. No need to add it to both manage.py and wsgi.py

Django apps on Heroku: how to access a shared database

On Heroku, it is possible to share a database among apps using the following command:
$ heroku addons:attach <databaseName> -a <appName>
where <databaseName> is the shared database (belonging to another app) and it is attached to the app <appName> (a Django application).
I googled around for a long time but couldn't find anything describing how to access the attached database in the app. Do I need to add or modify something to Django's settings.py and what? How do I access the attached database in Django's views.py?
The following is the setting for Heroku databases and database accessing is just via ORM.
# Parse database configuration from $DATABASE_URL
import dj_database_url
DATABASES = {'default':dj_database_url.config()}
# Honor the 'X-Forwarded-Proto' header for request.is_secure()
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
Thanks.
Heroku always supplies configuration details as environment variables. When you do addons:attach it will print the name of the variable it has created for your attached add-on; alternatively you can specify it with the --as flag.
heroku addons:attach <databaseName> -a <appName> --as MY_ATTACHED_DB_URL
Now you can pass that variable name to the config call:
DATABASES = {
'default':dj_database_url.config(),
'course': dj_database_url.config('MY_ATTACHED_DB_URL')
}

Heroku+django: cannot find config vars locally

I am trying django on heroku, following the official tutorial and stuck at the creating celery and kombu tables locally step using python manage.py syncdb, getting following errors:
File "/my/virtual/path/django/db/backends/postgresql_psycopg2/base.py",
line 162, in _cursor
raise ImproperlyConfigured("You need to specify NAME in your Django settings file.")
django.core.exceptions.ImproperlyConfigured: You need to specify NAME in your Django settings file.
The problem is it cannot find the db I set for heroku by the config vars of heroku. When I run heroku config, it displays the DATABASE_URL of my app correctly, but when I try:
if 'DATABASE_URL' in os.environ
in python interpreter, it returns false. I also check, none of my config vars is in my os.environ. Shouldn't vars be added to it automatically? My previous steps are correct.
I searched and got a lot of solutions to detect the heroku db but they all are based on the assumption that I have the DATABASE_URL in my os.environ.
Could anyone point out where I went wrong? Any suggestion is appreciated. Thanks!
I believe the tutorial is missing some steps on how to run the app locally. If you want to sync the database locally, you should override the "default" DATABASE with the one you have on your machine. There is one similar answer in here with code sample.
visit this page
Heroku Database Settings Injection - How do I setup my dev django database?
ldiqual's answer is right.