ERR_ABORTED 404 (Not Found) error in VueJS - django

I deployed a Django+VueJS application to a Digital Ocean droplet using Nginx, the Django app is working but i can't see the VueJS components loaded by Webpack (i'm using Django-Webpack-Loader).
In my console, i keep seing these errors:
GET http://MYURL/static/vue/js/stopwatch.js net::ERR_ABORTED 404 (Not Found)
GET http://MYURL/static/vue/js/index.js net::ERR_ABORTED 404 (Not Found)
Which means that the static folder was not found. I made sure to use npm run build and manage.py collectstatic and i can see that the static folder is there, even though the app doesn't see it. Here is the path:
django-vue-mpa
|-vue_frontend
|-django_vue_mpa
|-static
The full code of the application is here (i just cloned that repository and tried to deploy it).
Here is my vue.config.js (i think the problem might be here):
const BundleTracker = require("webpack-bundle-tracker");
const BundleAnalyzerPlugin = require("webpack-bundle-analyzer").BundleAnalyzerPlugin;
const pages = {
"stopwatch": {
entry: "./src/stopwatch.js",
chunks: ["chunk-moment", "chunk-vendors"],
},
"index": {
entry: "./src/index.js",
chunks: ["chunk-vendors"],
},
'vue_app_01': {
entry: './src/main.js',
chunks: ['chunk-vendors']
},
'vue_app_02': {
entry: './src/newhampshir.js',
chunks: ['chunk-vendors']
},
}
module.exports = {
pages: pages,
filenameHashing: false,
productionSourceMap: false,
publicPath: process.env.NODE_ENV === 'production'
? '/static/vue'
: 'http://localhost:8080/',
outputDir: '/django-vue-mpa/django_vue_mpa/static/vue/',
chainWebpack: config => {
config.optimization
.splitChunks({
cacheGroups: {
moment: {
test: /[\\/]node_modules[\\/]moment/,
name: "chunk-moment",
chunks: "all",
priority: 5
},
vendor: {
test: /[\\/]node_modules[\\/]/,
name: "chunk-vendors",
chunks: "all",
priority: 1
},
},
});
Object.keys(pages).forEach(page => {
config.plugins.delete(`html-${page}`);
config.plugins.delete(`preload-${page}`);
config.plugins.delete(`prefetch-${page}`);
})
config
.plugin('BundleTracker')
.use(BundleTracker, [{filename: '../vue_frontend/webpack-stats.json'}]);
// Uncomment below to analyze bundle sizes
// config.plugin("BundleAnalyzerPlugin").use(BundleAnalyzerPlugin);
config.resolve.alias
.set('__STATIC__', 'static')
config.devServer
.public('http://localhost:8080')
.host('localhost')
.port(8080)
.hotOnly(true)
.watchOptions({poll: 1000})
.https(false)
.headers({"Access-Control-Allow-Origin": ["*"]})
}
};
Here is my nginx config:
server {
listen 80;
server_name http://MYURL/;
location = /favicon.ico { access_log off; log_not_found off; }
location /static/ {
root /django-vue-mpa/django_vue_mpa/static;
}
location / {
include proxy_params;
proxy_pass http://unix:/django-vue-mpa/django-vue-mpa.sock;
}
}
And here is my settings.py:
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'MYKEY'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['MYURL']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'webpack_loader',
'django_vue_mpa'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'django_vue_mpa.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(BASE_DIR, 'templates')
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'django_vue_mpa.wsgi.application'
VUE_FRONTEND_DIR = os.path.join(BASE_DIR, 'vue_frontend')
WEBPACK_LOADER = {
'DEFAULT': {
'CACHE': not DEBUG,
'BUNDLE_DIR_NAME': 'vue/', # must end with slash
'STATS_FILE': os.path.join(VUE_FRONTEND_DIR, 'webpack-stats.json'),
'POLL_INTERVAL': 0.3,
'TIMEOUT': None,
'IGNORE': [r'.+\.hot-update.js', r'.+\.map']
}
}
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = "/django-vue-mpa/django_vue_mpa/static"

Check the difference between root and alias nginx directives. For your case you should use
location /static/ {
root /django-vue-mpa/django_vue_mpa;
}
instead of
location /static/ {
root /django-vue-mpa/django_vue_mpa/static;
}
You'd see nginx searches files on a wrong path if you looked at its error log.

Related

Why django session table growing automatically

I am developing a django project using nginx on the production. But when I start running my nginx server, the django_session table on the mysql starts growing. In each resfresh, I see more rows in the table. Why is that happening? Any way to stop this?
Here is my django settings.
import os
import platform
from pathlib import Path
from mydjangoapp import utilities as util
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'my secret key' #deidentified
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['localhost', '127.0.0.1', 'example.com']
CSRF_TRUSTED_ORIGINS = ['http://localhost', 'http://example.com', 'https://example.com']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.humanize',
'mydjangoapp',
'corsheaders',
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'mydjangoproj.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'mydjangoapp/templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'mydjangoproj.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
DATABASES = {
'default': {},
'db_magicnote': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'mydb_test',
'USER': '',
'PASSWORD': '',
'HOST': '',
'PORT': '3306',
'OPTIONS': {
'init_command': "SET sql_mode='STRICT_TRANS_TABLES'",
},
}
}
DATABASE_ROUTERS = ['mydjangoapp.dbRouter.MyDbRouter']
CURRENT_DATABASE = 'db_mydjangoapp'
# Password validation
# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/4.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/
STATIC_URL = '/static/'
#STATICFILES_DIRS = [
# BASE_DIR / "static",
#]
STATIC_ROOT = os.path.join(BASE_DIR,'static/')
# MEDIA
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
LOGIN_REDIRECT_URL = '/'
### SESSION SETTINGS ###
CSRF_COOKIE_SECURE = True
SESSION_COOKIE_SECURE = True
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
USE_X_FORWARDED_HOST = True
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
And here is my nginx conf settings:
# configuration of the server
server {
# the port your site will be served on
listen 80;
# the domain name it will serve for
server_name example.com;
charset utf-8;
# max upload size
client_max_body_size 75M; # adjust to taste
# Django media
location /media {
alias C:/Users/Administrator/Documents/mydjangoproj/media; # your Django project's media files - amend as required
}
location /static {
alias C:/Users/Administrator/Documents/mydjangoproj/static; # your Django project's static files - amend as required
}
# Finally, send all non-media requests to the Django server.
location / {
proxy_pass http://localhost:8080;
}
}
Okay, I've finally figured it out. This has nothing to do with the nginx web server. The health check of my AWS application load balancer was sending request every 5 seconds to my website.
I applied two steps:
1-) I increased the interval value to 300 seconds and timeout value to 120 seconds on the health check configuration (these are their maximum values). This way they don't make frequent request to the server that would increase the size of the django_sessions table significantly.
2-) I've started clearing expired sessions in the django_sessions table. There are a couple of ways to handle that:
a-) On MySQL, you can manually run the following sql:
DELETE FROM mydatabase.django_session where expire_date<now()
b-) Under the Django's main project directory, you can manually run the following command on your terminal:
python manage.py clearsessions
c-) One of these commands can be put in a shell script and scheduled to be run periodically (let's say once every day).
I prefer the python command (item 2) for now. As my userbase grows and the project gets larger, I can think of automating this manual process (the last item).

Recivieng error 500 when deploy Django rest-Vue project on Heroku

I'm been able to deploy my first project to heroku.
The API is this: https://segmentacion-app.herokuapp.com/cluster/, and the front is this: https://cluster-app-wedo.herokuapp.com/, the problem appears when I try to consume the api, I receive this: Failed to load resource: the server responded with a status of 500 (Internal Server Error) Error: Request failed with status code 500 at t.exports (createError.js:16) at t.exports (settle.js:17) at XMLHttpRequest.p.onreadystatechange (xhr.js:61) Home.vue:598, can I have some feedback about what i've missed?
Home.vue
let datos = await axios.post('https://segmentacion-app.herokuapp.com/cluster/',json)
.then(response => { ...
server.js
const express = require('express');
const port = process.env.PORT || 8080;
const app = express();
app.use(express.static(__dirname + '/dist/'));
app.get(/.*/, function(req, res) {
res.sendfile(__dirname + '/dist/index.html');
});
app.listen(port);
console.log("Server started...");
settings.py
import os
import django_heroku
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates')
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['https://cluster-app-wedo.herokuapp.com/',]
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'MiApp',
'import_export',
'django_extensions',
'rest_framework',
'api',
'corsheaders',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
]
CORS_ALLOWED_ORIGINS = [
'http://localhost:8080',
'https://cluster-app-wedo.herokuapp.com',
]
ROOT_URLCONF = 'ClusterApp.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATE_DIR,],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'ClusterApp.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
DATA_UPLOAD_MAX_NUMBER_FIELDS = None
# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = False
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)
# esto desactiva el error de sync to async
os.environ["DJANGO_ALLOW_ASYNC_UNSAFE"] = "true"
#esto es heroku
django_heroku.settings(locals())
The problem was on server.js file, now is:
const express = require('express');
const path = require('path');
const serveStatic = require('serve-static');
app = express();
app.use(serveStatic(path.join(__dirname, 'dist')));
app.get(/.*/, function(req, res) {
res.sendfile(__dirname + '/dist/index.html');
});
const port = process.env.PORT || 8080;
app.listen(port);
console.log("Server started..." + port);
Another thing important is to set server to production:
heroku config:set NODE_ENV=production --app <YOUR-PROJECT-NAME-HERE>
I followed this instructions:
https://medium.com/netscape/deploying-a-vue-js-2-x-app-to-heroku-in-5-steps-tutorial-a69845ace489

Getting 403 when trying to launch a django test site with nginx

I have a django site that resides in the following directory: /home/sgoodman/insta
and configured the /etc/nginx/sites-available/insta the following way.
server {
listen 80;
root /home/sgoodman/insta;
index index.html;
server_name 192.168.236.149;
}
Since I am in testing things out phase I set permissions to 777 in both /var/www and /home/sgoodman/insta
I am currently getting a 403 when I try to launch the page. Django automatically uses port 8000 when I do
python manage.py runserver
but when I try to running with
python manage.py runserver 80
it says port already in use. How do I launch a django app with nginx? I was trying to follow this tutorial.
https://linuxconfig.org/how-to-setup-the-nginx-web-server-on-ubuntu-18-04-bionic-beaver-linux
Below is my settings file:
DEBUG = True
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'posts.apps.PostsConfig',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'insta_project.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'insta_project.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/
STATIC_URL = '/static/'

DJango + nginx + gunicorn: how to stop caching

I am running Django 2.0 using gunicorn on nginx server. All my pages are not reflecting the changes immediately. How to stop caching
the below are my files:
nginx.conf
server {
listen 80;
server_name sample.com;
location = /favicon.ico { access_log off; log_not_found off; }
location /static/ {
root /home/testapp/testapp_project/test_artciles;
}
location /media/ {
root /home/testapp/testapp_project/test_artciles;
}
location / {
include proxy_params;
proxy_pass http://unix:/home/testapp/testapp_project/test_artciles.sock;
}
}
Django settings.py
import os
from django.contrib import messages
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = 'ssdjhasjdkhjaskdhkajsdhkjasdhkjh'
DEBUG = True
ALLOWED_HOSTS = ['xx.xxx.xx.xxx','127.0.0.1']
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.humanize',
'django_extensions',
# local apps
'articles',
'fcm_django',
'corsheaders',
'rest_framework',
)
MIDDLEWARE = (
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'webarticles.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(os.path.join(BASE_DIR, 'templates')),
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'webarticles.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'test.sqlite3'),
}
}
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Asia/Kolkata'
USE_I18N = True
USE_L10N = True
USE_TZ =True
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'frontend'),
)
CORS_ORIGIN_WHITELIST = ('xx.xxx.xx.xxx','127.0.0.1')
I am sure its something to do with the server because when i ran this code in localhost on my own laptop before transferring to server, things are reflecting immediately.
You should restart gunicorn to update working version after you changed code on server:
sudo systemctl restart gunicorn
or you can use --reload mode that will update gunicorn once code changed:
gunicorn --workers=2 test:app --reload
You can read about it on docs https://docs.gunicorn.org/en/stable/settings.html#reload
If you are talking about server caching, then here are the steps worked for me:
My implementation details are
gunicorn 19.9.0,
Django 1.11.16,
nginx version: nginx/1.10.3,
Os (Ubuntu)
Gunicorn is not caching already unless you have installed and enabled https://pypi.org/project/gunicorn_cache/
Disabling django caching,
from django.views.decorators.cache import never_cache
#never_cache
def generating the cached data/results():
Disabling ngnix caching
location todisablecaching {
proxy_no_cache 1;
proxy_cache_bypass 1;
...
}
https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_no_cache,
https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_cache_bypass
I hope it work for you as well.

Static files serving issue using Django channels

I am trying my hands on this example for websockets in Django, https://github.com/jacobian/channels-example as I have intention to use it my production application as well which is hosted in Heroku, and using Whitenoise there.
So, after cloning the above mentioned example, I did some tweaks using Whitenoise, but now on first visit to the application through any browser (chrome or FF) the static files doesn't load and when I refresh again it loads static files, and in third load it again goes off and so on.
Here is my settings file:
import os
import random
import string
import dj_database_url
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
SECRET_KEY = os.environ.get("SECRET_KEY", "".join(random.choice(string.printable) for i in range(40)))
DEBUG = os.environ.get("DEBUG", False)
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'channels',
'chat',
)
MIDDLEWARE_CLASSES = (
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'chat.urls'
TEMPLATES = (
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
'debug': DEBUG,
},
},
)
# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases
DATABASES = {
'default': dj_database_url.config(default="postgres:///channels-example", conn_max_age=500)
}
AUTH_PASSWORD_VALIDATORS = (
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
)
# Internationalization
# https://docs.djangoproject.com/en/1.9/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Honor the 'X-Forwarded-Proto' header for request.is_secure()
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
# Allow all host headers
ALLOWED_HOSTS = ['*']
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
# Extra places for collectstatic to find static files.
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
# Channel settings
CHANNEL_LAYERS = {
"default": {
"BACKEND": "asgi_redis.RedisChannelLayer",
"CONFIG": {
"hosts": [os.environ.get('REDIS_URL', 'redis://localhost:6379')],
},
"ROUTING": "chat.routing.channel_routing",
},
}
# Logging
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'class': 'logging.StreamHandler',
},
},
'loggers': {
'django': {
'handlers': ['console'],
'propagate': True,
'level': 'INFO'
},
'chat': {
'handlers': ['console'],
'propagate': False,
'level': 'DEBUG',
},
},
}
STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
Here is the other file which I made changes to routing.py:
from channels.staticfiles import StaticFilesConsumer
from . import consumers
channel_routing = {
# This makes Django serve static files from settings.STATIC_URL, similar
# to django.views.static.serve. This isn't ideal (not exactly production
# quality) but it works for a minimal example.
# 'http.request': StaticFilesConsumer(),
# Wire up websocket channels to our consumers:
'websocket.connect': consumers.ws_connect,
'websocket.receive': consumers.ws_receive,
'websocket.disconnect': consumers.ws_disconnect,
}
Procfile is:
web: daphne chat.asgi:channel_layer --port $PORT --bind 0.0.0.0 -v2
worker: python manage.py runworker -v2
I have not tried it on Heroku as if now, just on localhost I observed this behavior so didnt even integrate the solution with original application. I used heroku local to run the application locally.
What am I doing wrong? And is the process mentioned in Procfile production ready on Heroku?
Thanks
Try upgrading your Django channels to 1.0.3 and whitenoise 3.3.0 the example you mentioned Is using an outdated version and some bug fixes where added to allow Daphne to serve static content with whitenoise. Alternatively you can just leverage on s3 bucket to serve your static content which is the preferred approach to serve static content with Django.
https://github.com/django/channels/issues/87