Can I host ASGI Django App in Windows Server 2012 backed with Apache? I explored several blogs which mentions about "mod_wsgi" which confused me if it could handle ASGI application.
Can this server handle websocket requests?
Medium/Analytics-Vidya
Prof. Dr. Christian Leubner
settings.py
INSTALLED_APPS = [
'channels',
'rest_framework',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'broadcast',
]
ASGI_APPLICATION = 'AppMain.asgi.application'
CHANNEL_LAYERS = {
"default": {
"BACKEND": "channels_redis.core.RedisChannelLayer",
"CONFIG": {
"hosts": [("localhost", 6379)],
# "hosts":[os.environ.get('REDIS_URL', 'redis://localhost:6379')]
},
},
}
asgi.py
import os
import django
from django.core.asgi import get_asgi_application
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
from django.urls import path
from broadcast.consumers import AConsumer
import broadcast.routing
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'AppMain.settings')
django.setup()
# application = get_asgi_application()
application = ProtocolTypeRouter({
'http' : get_asgi_application(),
'websocket' : AuthMiddlewareStack(
URLRouter(
broadcast.routing.websocket_urlpatterns
)
)
})
Related
Hi, I have Blog post project some functionalities made with DRF and some functionalities made with Django.I need to add 404 page for missing urls. But If I use right-working link, I will get server error, However, I will get 404 page for missing url.
For example, urls such as '127.0.0.1:8000/en/me' or '127.0.0.1:8000/en/me/contact/' or '127.0.0.1:8000/en/book' will bring server error,
but url '127.0.0.1:8000/en/men' return not found page
in my django_project/urls.py:
from django.contrib import admin
from django.urls import path, include
from django.conf.urls.static import static
from django.conf import settings
from rest_framework import permissions
from drf_yasg.views import get_schema_view
from drf_yasg import openapi
from django.conf.urls.i18n import i18n_patterns
# from django.conf.urls import handler404
from my_works import views as my_works_views
schema_view = get_schema_view(
openapi.Info(
title="API Docs",
default_version='v1',
description="API urls description",
terms_of_service="https://www.myblogs.com/policies/terms/",
contact=openapi.Contact(email="aahmadov271101#gmail.com"),
license=openapi.License(name="Test License"),
),
public=True,
permission_classes=(permissions.AllowAny,),
)
urlpatterns = [
path('swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
path('redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),
path('i18n/', include('django.conf.urls.i18n')),
]
urlpatterns += i18n_patterns (
path('', include('my_works.urls')),
path('me/', include('accounts.urls')),
path('admin/', admin.site.urls),
)
urlpatterns+= (static(settings.STATIC_URL, document_root=settings.STATIC_ROOT))
urlpatterns+= (static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT))
handler404 = 'accounts.views.error_404_view'
admin.site.site_header = 'Alimardon Mustafoqulov Administration'
admin.site.site_title = 'Administration'
admin.site.index_title = 'Administration page'
in my django_app/urls.py:
from django.urls import path, include
from django.conf.urls.i18n import i18n_patterns
from .views import (
ArticlesViewList,
BooksViewList,
PresentationsViewList,
ProjectsViewList,
EventsViewList,
VideosViewList,
)
from rest_framework import routers
from django.conf.urls import handler404
router = routers.DefaultRouter()
router.register(r'articles', ArticlesViewList, basename='articles')
router.register(r'books', BooksViewList, basename='books')
router.register(r'presentations', PresentationsViewList, basename='presentations')
router.register(r'projects', ProjectsViewList, basename='projects')
router.register(r'events', EventsViewList, basename='events')
router.register(r'videos', VideosViewList, basename='videos')
urlpatterns = []
urlpatterns += router.urls
in my django_app2/urls.py:
from django.urls import path, include
from .views import ContactAPIView, ProfileView, AdminContactView, AddressLinkView
from rest_framework import routers
from django.contrib.auth import views as auth_views
from rest_framework.authtoken.views import obtain_auth_token
router = routers.DefaultRouter()
router.register(r'phones',AdminContactView, basename='phone')
router.register(r'addresses',AddressLinkView, basename='addresses')
router.register(r'contact',ContactAPIView, basename='contact')
router.register(r'',ProfileView, basename='profile')
urlpatterns = [
# path('auth-token/', obtain_auth_token, name='token-auth'),
path('api-auth/', include('rest_framework.urls')),
path('password-reset/',
auth_views.PasswordResetView.as_view(),
name='password_reset'),
path('password-reset/done/',
auth_views.PasswordResetDoneView.as_view(
template_name='password_reset_done.html'
),
name='password_reset_done'),
path('password-reset-confirm/<uidb64>/<token>/',
auth_views.PasswordResetConfirmView.as_view(),
name='password_reset_confirm'),
path('password-reset-complete/',
auth_views.PasswordResetCompleteView.as_view(),
name='password_reset_complete'),
]
urlpatterns += router.urls
in my django_project/settings.py:
import os
from pathlib import Path
from django.utils.translation import gettext_lazy as _ #for multi-language
# 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 = 'secret key hidden'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ["*",]
# Application definition
INSTALLED_APPS = [
'modeltranslation',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'accounts.apps.AccountsConfig',
'my_works.apps.MyWorksConfig',
'crispy_forms',
'rest_framework',
'django_filters',
'rest_framework.authtoken',
'corsheaders',
'phonenumber_field',
'drf_yasg',
'whitenoise',
]
I have developed oscar /django applications before but I am completely stumped by this issue:
I can see the dashboard url in the supported urls list but I am not able to access it.
404 Page
I have forked a few apps from oscar like voucher, shipping, checkout, reviews and customized them in various ways(None of these are dashboard related) . This is my INSTALLED_APPS:
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',
'iirns.checkout.apps.CheckoutConfig',
'oscar.apps.address.apps.AddressConfig',
'iirns.shipping.apps.ShippingConfig',
'oscar.apps.catalogue.apps.CatalogueConfig',
'iirns.catalogue.reviews.apps.CatalogueReviewsConfig',
'oscar.apps.communication.apps.CommunicationConfig',
'oscar.apps.partner.apps.PartnerConfig',
'oscar.apps.basket.apps.BasketConfig',
'iirns.payment.apps.PaymentConfig',
'oscar.apps.offer.apps.OfferConfig',
'oscar.apps.order.apps.OrderConfig',
'oscar.apps.customer.apps.CustomerConfig',
'oscar.apps.search.apps.SearchConfig',
'iirns.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',
'django_tables2',
'mailer',
'extra',
]
and this is my root url file:
from django.conf.urls import url
from django.contrib import admin
from django.apps import apps
from django.urls import include, path
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('extra.urls')),
path('', include(apps.get_app_config('oscar').urls[0])),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I do my first steps with the Django REST Framework.
But when I do:
python3 manage.py makemigrations && python3 manage.py migrate
I get this error:
ModuleNotFoundError: No module named 'rest_framework.renderers'
I have checked the settings.py:
INSTALLED_APPS = [
'api',
'rest_framework',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
I checked pip3 if the package is installed:
Django==3.0.5
django-rest-framework==0.1.0
djangorestframework==3.11.0
This is the code snippet where I use it and where I get the error:
from django.http import HttpResponse
from rest_framework.renderers import JSONRenderer
from rest_framework.decorators import api_view
from .models import Repo, Category
from .serializers import repoSerializer, categorySerializer
I do not know where the error is.
Can somebody give me a hint? Is maybe there a problem with the migration?
You have to include this in settings.py
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': [
'rest_framework.renderers.JSONRenderer',
]
}
For more info: https://www.django-rest-framework.org/api-guide/renderers/
I used a Custom password_reset_form.html
(My Path: /templates/registration/password_reset_form.html)
But Django takes the Django-Default-Password-Reset-View
Any solution what i could do?
urls.py
from django.contrib.auth import views as auth_views
from django.contrib.auth.forms import AuthenticationForm
from django.template import RequestContext
from django.urls import include, path, re_path
from myapp.CustomForms.appforms import LoginAuthenticationForm
from django.contrib.auth.views import LogoutView
from django.contrib import admin
from django.urls import path, include
from django.conf.urls import url
from myapp.views import (
...
)
from . import views
urlpatterns = [
...
url(r"^$", views.startseite, name="home"),
url(r"^signup/$", views.signup, name="signup"),
url(
r"^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z].
{1,13}-[0-9A-Za-z]{1,20})/",
views.activate, name="activate",),
url('^', include('django.contrib.auth.urls')),
]
settings.py
INSTALLED_APPS = [
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'django.contrib.auth',
'myapp',
]
...
The reason why django didn't pick up my custom template cause i have to change the order of my
INSTALLED_APPS = [
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp',
'django.contrib.admin',
'django.contrib.auth',
]
myapp has to set before django.contrib.admin and django.contrib.auth
I try to make a chat. There are some functions that work with "original" Django (def index(request) and so on) but also there are functions, where I need to use websockets. I installed channels to make a websocket interface. So, I have two systems: gunicorn interconnects with HTTP(S) and daphna interconnets with WS(S) interface.
On my local machine I set up all files (asgi.py, consumers.py, routing.py and settings.py) and I type: python manage.py runserver - everything works. But when I deploy it to heroku, I get a lot of errors.
I tried everything, but didn't find the solution. Ask for your help.
Here are my files:
chat/Procfile
web: daphne Chat.asgi:channel_layer --port $PORT
web2: gunicorn Chat.wsgi
chat/chat/asgi.py
import os
import channels.asgi
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Chat.settings')
channel_layer = channels.asgi.get_channel_layer()
chat/chat/routing.py
from channels.routing import route
channel_routing = {
'websocket.connect': 'user_chating.consumers.ws_connect',
'websocket.receive': 'user_chating.consumers.ws_message',
'websocket.disconnect': 'user_chating.consumers.ws_disconnect',
#'send_email': 'user_chating.consumers.send_email_consumer'
}
chat/chat/settings.py
...
# Application definition
INSTALLED_APPS = [
'user_chating',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'channels',
]
CHANNEL_LAYERS = {
'default': {
'BACKEND': 'asgiref.inmemory.ChannelLayer',
'ROUTING': 'Chat.routing.channel_routing',
},
}
ASGI_APPLICATION = "Chat.routing.application"
MIDDLEWARE = [
'whitenoise.middleware.WhiteNoiseMiddleware',
'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 = 'Chat.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [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 = 'Chat.wsgi.application'
...
chat/chat/wsgi.py
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Chat.settings')
application = get_wsgi_application()
chat/user_chatting/consumers.py
import json
import time
from django.core.mail import send_mail
from channels.channel import Group
def ws_connect(message):
Group('chat').add(message.reply_channel)
message.reply_channel.send({"accept": True})
def ws_message(message):
Group('chat').send({'text': json.dumps({'message': message.content['text'],
'sender': message.reply_channel.name})})
def ws_disconnect(message):
Group('chat').discard(message.reply_channel)
Can anybody help me please?