Streaming mp3 files in Django through Nginx - python

I have a website based on Django framework. I am running website via Nginx webserver (uWSGI,Django,Nginx). I want to stream mp3 files on my website with Accept-Ranges header. I want to serve my mp3 files with Nginx. I need my API to look like this
http://192.168.1.105/stream/rihanna
This must return mp3 file with partial download (Accept-Ranges).
My mp3 files are stored in : /home/docker/code/app/media/data/
When I run the server with these configurations and browse to 192.168.1.105/stream/rihanna , Django returns 404.
My Nginx conf:
# mysite_nginx.conf
# the upstream component nginx needs to connect to
upstream django {
server unix:/home/docker/code/app.sock; # for a file socket
# server 127.0.0.1:8001; # for a web port socket (we'll use this first)
}
# configuration of the server
server {
# the port your site will be served on, default_server indicates that this server block
# is the block to use if no blocks match the server_name
listen 80 default;
include /etc/nginx/mime.types;
# the domain name it will serve for
server_name .example.com; # substitute your machine's IP address or FQDN
charset utf-8;
# max upload size
client_max_body_size 75M; # adjust to taste
# Django media
location /media {
autoindex on;
sendfile on;
sendfile_max_chunk 1024m;
internal;
#add_header X-Static hit;
alias /home/docker/code/app/media/; # your Django project's media files - amend as required
}
location /static {
alias /home/docker/code/app/static/; # your Django project's static files - amend as required
}
# Finally, send all non-media requests to the Django server.
location / {
uwsgi_pass django;
include /home/docker/code/uwsgi_params; # the uwsgi_params file you installed
}
}
My views.py :
def stream(request, offset):
try:
mp3_path = os.getcwd() + '/media/data/' + offset + '.mp3'
mp3_data = open(mp3_path, "r").read()
except:
raise Http404()
response = HttpResponse(mp3_data, content_type="audio/mpeg", status=206)
response['X-Accel-Redirect'] = mp3_path
response['X-Accel-Buffering'] = 'no'
response['Content-Length'] = os.path.getsize(mp3_path)
response['Content-Dispostion'] = "attachment; filename=" + mp3_path
response['Accept-Ranges'] = 'bytes'
I want Nginx serve this files. And I really need Accept-Ranges enabled.
My Settings.py :
# 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.10/howto/deployment/checklist/
DEBUG = True
ALLOWED_HOSTS = ['localhost', '127.0.0.1', '192.168.1.105', '0.0.0.0']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
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 = 'beats.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 = 'beats.wsgi.application'
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
MEDIA_URL = os.path.join(BASE_DIR, 'media/')
# Database
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
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',
},
]
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/'
My problem is: It doesn't work, and Django return 404 Error webpage.

First of all, I did not copy the Nginx configuration file to the available-sites path. And because of it, It didn't work.
And in my views.py:
response = HttpResponse(mp3_data, content_type="audio/mpeg", status=206)
response['X-Accel-Redirect'] = mp3_path
these 2 lines must be changed to:
response= HttpResponse('', content_type="audio/mpeg", status=206)
response['X-Accel-Redirect'] = '/media/data/' + file_name + '.mp3'

Related

My Django App works on my local development server but does not work on my Linode VPS

I have the exact same code deployed locally on development server and Linode Virtual Private Server. The Local site works fine, but when I try to access the same url on the VPS, I see this in the browser:
This site can’t be reached XXX.XXX.XXX.X refused to connect.
Try:
Checking the connection
Checking the proxy and the firewall
ERR_CONNECTION_REFUSED
Even when I go to the admin site it is broken.
I have narrowed the change down to my views.py and settings.py file changes, as I was making one code change at a time to try and find out where the VPS did not like my code. I am unable to understand why the Django App just seems to break.
My views.py function, the last line of code will be called:
def start_or_end_fast(request):
if request.method == 'POST' and 'start_fast' in request.POST:
start()
return HttpResponseRedirect(reverse('start_or_end_fast'))
elif request.method == 'POST' and 'end_fast' in request.POST:
print('mmmmm')
end()
return HttpResponseRedirect(reverse('start_or_end_fast'))
elif request.method == 'POST' and 'duration' in request.POST:
duration = time_difference()
return render(request,'startandstoptimes/index.html', {'duration': duration})
else:
return render(request,'startandstoptimes/index.html')
settings.py:
from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
SETTINGS_PATH = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'XXXXXXXXXXXXXXXXXXXXXXXXX'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
#Xs to mask IP on Stackoverflow
ALLOWED_HOSTS = ['XXX.XXX.XXX.XXX.X','127.0.0.1']
# Application definition
INSTALLED_APPS = [
'startandstoptimes.apps.StartandstoptimesConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
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 = 'DjangoApp.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(SETTINGS_PATH, '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 = 'DjangoApp.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.2/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.2/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/3.2/howto/static-files/
STATIC_URL = '/static/'
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
I am thinking there may be some configuration on my server on something that needs changed, I am stumped.

Unable to write in a file after django app deployment on aws ec2 using nginx and gunicorn

I have deployed my Django online judge project on AWS EC2 using Nginx and Gunicorn I am taking user code in a string variable and writing it to a file in my project directory and it's working fine in development server but after deployment the program unable to write code in the file. for eg:-
lets say a user have submitted code in c++ language so I took that code in a string variable and I open the my .cpp file via open() function in my views.py and writing the code in it.
filepath = os.path.join(settings.BASE_DIR, 'language', 'forcpp.cpp')
cpp_code=open(filepath,"w")
cpp_code.write(user_problem_code)
cpp_code.close()
I have tried to modify path in every possible way but got unlucky in every try
I have my files in language folder in which I want to write user submitted code and my views.py are in problempg application
my project directory structure:
online_judge_project/
account/
homesrc/
language/ /* directory containing files in which I want to write */
forcpp.cpp
media/
oj/
settings.py
problempg/ /* application containing views.py */
views.py
static/
staticfiles/
template/
manage.py
settings.py
"""
Django settings for oj project.
Generated by 'django-admin startproject' using Django 4.0.5.
For more information on this file, see
https://docs.djangoproject.com/en/4.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.0/ref/settings/
"""
from importlib.resources import path
from pathlib import Path
import os
from .info import *
EMAIL_USE_TLS = EMAIL_USE_TLS
EMAIL_HOST = EMAIL_HOST
EMAIL_HOST_USER = EMAIL_HOST_USER
EMAIL_HOST_PASSWORD = EMAIL_HOST_PASSWORD
EMAIL_PORT = EMAIL_PORT
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
TEMPLATE_DIR=os.path.join(BASE_DIR,'template')
FILES_DIR=os.path.abspath(os.path.join(BASE_DIR,'language'))
# 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 = os.environ['SECRET_KEY']
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ["localhost","<MY_IP_ADDRESS>"]
# Application definition
INSTALLED_APPS = [
'widget_tweaks',
'account.apps.AccountConfig',
'problempg.apps.ProblempgConfig',
'homescr.apps.HomescrConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'ckeditor',
]
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 = 'oj.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 = 'oj.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# 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_ROOT= os.path.join(BASE_DIR,'staticfiles')
STATIC_URL = 'static/'
MEDIA_ROOT= os.path.join(BASE_DIR,'media')
MEDIA_URL='/media/'
LOGOUT_REDIRECT_URL = "index"
STATICFILES_DIRS=[
os.path.join(BASE_DIR, 'static'),
]
# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
from django.contrib.messages import constants as messages
MESSAGE_TAGS = {
messages.DEBUG: 'alert-info',
messages.INFO: 'alert-info',
messages.SUCCESS: 'alert-success',
messages.WARNING: 'alert-warning',
messages.ERROR: 'alert-danger',
}
may be the path I am using in development is different in EC2 server. I have develop this project on a windows machine and I am deploying it on Ubantu EC2 server or it's due to Nginx?

I cannot access Django Oscar url

I deployed oscar /django application:
Whenever I try to access my site on port 8000, I get the below error page :
In my urls.py, I have the following:
from django.apps import apps
from django.urls import include, path
from django.contrib import admin
urlpatterns = [
path('i18n/', include('django.conf.urls.i18n')),
# The Django admin is not officially supported; expect breakage.
# Nonetheless, it's often useful for debugging.
path('admin/', admin.site.urls),
path('', include(apps.get_app_config('oscar').urls[0])),
]
I have no active firewalls configured and I cannot access the app URL example.com:8000.
In settings.py, I have the following configured:
Django settings for frobshop project.
Generated by 'django-admin startproject' using Django 3.2.13.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
from oscar.defaults import *
from pathlib import Path
# 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/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-z#up7l!&f*qh1%u21p*_ltv+m2^8+_9o-th+zpdih5!3ydlipd'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['localhost']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'django.contrib.flatpages',
'oscar.config.Shop',
'oscar.apps.analytics.apps.AnalyticsConfig',
'oscar.apps.checkout.apps.CheckoutConfig',
'oscar.apps.address.apps.AddressConfig',
'oscar.apps.shipping.apps.ShippingConfig',
'oscar.apps.catalogue.apps.CatalogueConfig',
'oscar.apps.catalogue.reviews.apps.CatalogueReviewsConfig',
'oscar.apps.communication.apps.CommunicationConfig',
'oscar.apps.partner.apps.PartnerConfig',
'oscar.apps.basket.apps.BasketConfig',
'oscar.apps.payment.apps.PaymentConfig',
'oscar.apps.offer.apps.OfferConfig',
'oscar.apps.order.apps.OrderConfig',
'oscar.apps.customer.apps.CustomerConfig',
'oscar.apps.search.apps.SearchConfig',
'oscar.apps.voucher.apps.VoucherConfig',
'oscar.apps.wishlists.apps.WishlistsConfig',
'oscar.apps.dashboard.apps.DashboardConfig',
'oscar.apps.dashboard.reports.apps.ReportsDashboardConfig',
'oscar.apps.dashboard.users.apps.UsersDashboardConfig',
'oscar.apps.dashboard.orders.apps.OrdersDashboardConfig',
'oscar.apps.dashboard.catalogue.apps.CatalogueDashboardConfig',
'oscar.apps.dashboard.offers.apps.OffersDashboardConfig',
'oscar.apps.dashboard.partners.apps.PartnersDashboardConfig',
'oscar.apps.dashboard.pages.apps.PagesDashboardConfig',
'oscar.apps.dashboard.ranges.apps.RangesDashboardConfig',
'oscar.apps.dashboard.reviews.apps.ReviewsDashboardConfig',
'oscar.apps.dashboard.vouchers.apps.VouchersDashboardConfig',
'oscar.apps.dashboard.communications.apps.CommunicationsDashboardConfig',
'oscar.apps.dashboard.shipping.apps.ShippingDashboardConfig',
# 3rd-party apps that oscar depends on
'widget_tweaks',
'haystack',
'treebeard',
# 'sorl.thumbnail', # Default thumbnail backend, can be replaced
'django_tables2',
]
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',
'oscar.apps.basket.middleware.BasketMiddleware',
'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',
]
ROOT_URLCONF = 'frobshop.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',
'oscar.apps.search.context_processors.search_form',
'oscar.apps.checkout.context_processors.checkout',
'oscar.apps.communication.notifications.context_processors.notifications',
'oscar.core.context_processors.metadata',
],
},
},
]
WSGI_APPLICATION = 'frobshop.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
AUTHENTICATION_BACKENDS = (
'oscar.apps.customer.auth_backends.EmailBackend',
'django.contrib.auth.backends.ModelBackend',
)
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.simple_backend.SimpleEngine',
},
}
# Password validation
# https://docs.djangoproject.com/en/3.2/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.2/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/3.2/howto/static-files/
STATIC_URL = '/static/'
import os
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
I also tried the two below versions and did not work:
ALLOWED_HOSTS = ['']
ALLOWED_HOSTS = ['my_server_domain_or_IP', 'example.com', . . ., 'localhost']
The default file inside /etc/nginx/sites-available has the following configuration:
location = /favicon.ico { access_log off; log_not_found off; }
location /static/ {
root /root/frobshop/frobshop; ## This is where settings.py exists
}
But even if I delete the below lines from settings.py:
import os
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
and I delete the below lines from default file located in /etc/nginx/sites-available:
location = /favicon.ico { access_log off; log_not_found off; }
location /static/ {
root /root/frobshop/frobshop; ## This is where settings.py exists
}
I cannot access the app on port 8000. I actually added the above lines to make the URL accessible at example.com:8000 to no avail. How can I make the URL accessible?
Your application should be accessible only using 127.0.0.1:8000
If you want to use other addresses then run the following command
python manage.py runserver 0.0.0.0:8000
If it still doesn't work then check nginx.service file for listening port number and address.
Also I recommend using gunicorn.

Serving Media files in cPanel Shared Hosting for Django Web App

I am not able to display media files on Cpanel shared hosting Django web app. I receive a Error 404 URL Not Found whenever I try to access the media file.
I have specified + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) in my urls.py file.
This error only occurs whenever DEBUG = False. I am using whitenoise to serve the static files without any issue it is only the media directory that causes the 404 web error.
settings.py
"""
Django settings for app project.
Generated by 'django-admin startproject' using Django 3.2.9.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
import os
from pathlib import Path
# 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/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
# Replace with your secret key. Secret key is set as an env variable in Python
# Web Application Page
SECRET_KEY = os.environ['SECRET_KEY']
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['*', 'subdomain.myapp.com']
# Application definition
INSTALLED_APPS = [
'myapp',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'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.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'app.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 = 'app.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.2/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.2/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/3.2/howto/static-files/
# Static files are served via whitenoise
STATIC_URL = '/staticfiles/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles/')
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static/"),
)
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
passenger_wsgi.py
import os
import sys
#########Accessing the App's Default WSGI##############
import app.wsgi
application = app.wsgi.application
######## PASSENGER PATH INFO-FIX INITIALISATIONS#######
cwd = os.getcwd()
sys.path.append(cwd)
#sys.path.append(os.getcwd())
sys.path.append(cwd + '/app') #You must add your project here
# Set this to your root
SCRIPT_NAME = os.getcwd()
######## MIDDLEWARE CLASS TO FIX PASSENGER'S URI ISSUES #############
class PassengerPathInfoFix(object):
"""
Sets PATH_INFO from REQUEST_URI since Passenger doesn't provide it.
"""
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
#IF YOU ARE IN PYTHON 2.7 USE: from urllib import unquote
from urllib.parse import unquote
environ['SCRIPT_NAME'] = SCRIPT_NAME
request_uri = unquote(environ['REQUEST_URI'])
script_name = unquote(environ.get('SCRIPT_NAME', ''))
offset = request_uri.startswith(script_name) and len(environ['SCRIPT_NAME']) or 0
environ['PATH_INFO'] = request_uri[offset:].split('?', 1)[0]
return self.app(environ, start_response)
###########the redirecting Middleware
application = PassengerPathInfoFix(application)
I am using Python v3.8.6, Django=2.1 and CPanel Shared Hosting via NameCheap.
I know it's recommended to have a webserver to store and serve media files in Production Environment but I am unable to edit the Apache httpd.conf file as mentioned in the Django documentation.

Getting error while running app over https using Python and Django

I need to test my APP over https but here I am getting the below error while running my App using Python.
This site can’t provide a secure connection
127.0.0.1 sent an invalid response.
ERR_SSL_PROTOCOL_ERROR
I am making an app using Python and Django and wanted to run over the https. My settings.py is given below.
settings.py:
"""
Django settings for carClinic project.
"""
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__)))
""" SECURITY WARNING: keep the secret key used in production secret! """
SECRET_KEY = 'e8rq8bj5=w6cyiw&37s2kdys&$mg9m8agh#-%c6_+-jpu-21y='
""" SECURITY WARNING: don't run with debug turned on in production! """
DEBUG = False
ALLOWED_HOSTS = ['*']
""" Application definition """
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'bookingservice'
]
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 = 'carClinic.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 = 'carClinic.wsgi.application'
""" Database """
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
""" Password validation """
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 """
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
SECURE_SSL_REDIRECT = True
""" Static files (CSS, JavaScript, Images) """
STATIC_URL = '/static/'
To connect over HTTPS you need a valid SSL certificate on the server. From the error message it looks like you're connecting to a server on your local computer, and while you could get a certificate for that, it probably isn't worth the trouble. There is really no reason to test HTTPS on a local computer if you are planning on deploying to a server, as you'll have to set up SSL again on the server, and even if it works on your computer, it might not work on the server.
I recommend that you deploy the app to a server (you'll need a webserver like apache or nginx for that), and then set up a free Let's Encrypt certificate. Then you'll be able to connect over HTTPS.
If you really need to do this on you local computer, you must first get a fixed public IP-address, which you'll have to get from your ISP. If you use the IP-address you have now it will probably change in a few days or so, and then you'll have to get a new certificate.

Categories

Resources