ModuleNotFoundError: No module named 'channels.http' - django

I found a couple of similar questions, but nothing really helped. I tried updating asgiref version and also updated channels and django-eventstream. I mainly followed the instruction from the django-eventstream-setup page.
relevant packages from my setup:
Package Version
------------------ ---------
asgiref 3.6.0
channels 4.0.0
Django 4.1.2
django-eventstream 4.5.1
django-grip 3.2.0
django-htmx 1.12.2
gripcontrol 4.1.0
huey 2.4.3
MarkupSafe 2.1.2
requests 2.28.1
Werkzeug 2.2.2
The error I get upon executing python manage.py runserver:
...
File "...\venv\lib\site-packages\django_eventstream\routing.py", line 2, in <module>
from . import consumers
File "...\venv\lib\site-packages\django_eventstream\consumers.py", line 7, in <module>
from channels.http import AsgiRequest
ModuleNotFoundError: No module named 'channels.http'
I created an asgi.py file next to settings.py:
import os
from django.core.asgi import get_asgi_application
from django.urls import path, re_path
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
import django_eventstream
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'channels_test.settings')
application = ProtocolTypeRouter({
'http': URLRouter([
path("events/", AuthMiddlewareStack(URLRouter(django_eventstream.routing.urlpatterns)), { 'channels': ['test'] }),
re_path(r"", get_asgi_application()),
]),
})
In setup.py I updated for using asgi:
WSGI_APPLICATION = "channels_test.wsgi.application"
ASGI_APPLICATION = "channels_test.asgi.application"
This is the folder structure:

Related

flask_bcrypt, werkzeug.security.safe_str_cmp fails after upgrade to latest flask 2.1

I've upgraded my project to latest flask (2.1.2 and now I'm getting following error:
Traceback (most recent call last):
File "/home/ff/conveyors/run.py", line 1, in <module>
from conveyors import create_app
File "/home/ff/conveyors/conveyors/__init__.py", line 4, in <module>
from flask_bcrypt import Bcrypt
File "/home/ff/.cache/pypoetry/virtualenvs/conveyors-SV5d9Vx2-py3.9/lib/python3.9/site-packages/flask_bcrypt.py", line 21, in <module>
from werkzeug.security import safe_str_cmp
ImportError: cannot import name 'safe_str_cmp' from 'werkzeug.security'
In my __init__.py I have
...
from flask_bcrypt import bcrypt
from flask_login import LoginManager
...
and then below in create_app:
def create_app(config_class=Config):
app = Flask(__name__)
app.config.from_object(Config)
db.init_app(app)
bcrypt.init_app(app)
login_manager.init_app(app)
...
I've read Werkzeug release note about safe_str_cmp being removed from Werkzeug 2.1 and needs to be replaced with equivalent hmac functions, but I'm not sure what I need to do in my code to fix this.
Any help greatly appreciated.
Thanks.
It turned out to be a poetry update problem. Whatever I tried it wouldn't upgrade flask_bcrypt to the latest version 1.0.1 and stayed with 0.7.1
I had to start kind of from scratch and do
poetry add flask
...
for every package needed for this app

Django - How can my asgi websocket path be on my swagger

I am creating an api where two endpoints are using the ws(s) protocol.
As my API is behind Google endpoint, Every endpoint needs to be defined onto an OpenApi2.0 file.
To create this definition I use drf-yasg.
I have a routing. py file like this:
""" systems/routing.py"""
from django.urls import path
from .consumers.list_sessions_consumer import MyFirstConsumer
from .consumers.session_consumer import MySecondConsumer
urlpatterns = [
path(r'v1/ws/yo/<str:uuid>/sessions-sumpup', MyFirstConsumer.as_asgi()),
path(r'v1/ws/yo/<str:uuid>/sessions', MySecondConsumer.as_asgi()),
]
and I register it onto my asgi.py file like this:
# pylint: skip-file
""" main/asgi.py """
import os
import django
from django.core.asgi import get_asgi_application
django_asgi_app = get_asgi_application()
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'main.settings')
django.setup()
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
from systems.websockets.routing import urlpatterns as system_websocket_url
application = ProtocolTypeRouter({
"http": django_asgi_app,
"websocket": AuthMiddlewareStack(
URLRouter(
system_websocket_url
)
),
})
Don't mind the import order this is due to this error: Django apps aren't loaded yet when using asgi
So my socket works as expected, now, I want my command line: python3 manage.py generate_swagger swagger.yaml to add these new endpoint to my swagger file.
I tried to directly add my url to the same object then all my other urls like so:
urlpatterns = [
path(r'v1/toto/<str:uuid>', MyView.as_view()),
...,
path(r'v1/ws/yo/<str:uuid>/sessions-sumpup', MyFirstConsumer.as_asgi()),
path(r'v1/ws/yo/<str:uuid>/sessions', MySecondConsumer.as_asgi()),
]
But nothing shows up in my swagger file.
Any ideas ?
Thanks

setting up Django app to work on google app engine GAE (app.yaml & main.py)

I have a working Django app that I was able to get functioning on Heroku. The structure is project named 'untitled' and an app named 'web' such that the structure is:
project_root
static
templates
untitled
--->init.py
--->settings.py
--->urls.py
--->wsgi.py
web
--->init.py
--->admin.py
--->apps.py
--->models.py
--->tests.py
--->urls.py
--->views.py
This is a fairly basic app that I can get working outside of GAE (local and on Heroku), however, I'm getting stuck on the app.yaml and main.py requirements for GAE.
My app.yaml is:
application: seismic-interpretation-institute-py27
version: 1
runtime: python27
api_version: 1
threadsafe: true
handlers:
- url: /.*
script: main.app
libraries:
- name: django
version: "latest"
and my main.py (generated from PyCharm) is
import os,sys
import django.core.handlers.wsgi
import django.core.signals
import django.db
import django.dispatch.dispatcher
# Google App Engine imports.
from google.appengine.ext.webapp import util
# Force Django to reload its settings.
from django.conf import settings
settings._target = None
os.environ['DJANGO_SETTINGS_MODULE'] = 'untitled.settings'
# Unregister the rollback event handler.
django.dispatch.dispatcher.disconnect(
django.db._rollback_on_exception,
django.core.signals.got_request_exception)
def main():
# Create a Django application for WSGI.
application = django.core.handlers.wsgi.WSGIHandler()
# Run the WSGI CGI handler with that application.
util.run_wsgi_app(application)
if __name__ == '__main__':
main()
Finally, the output that is reported when running locally is
It seems that the error,
ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined.
is causing my problems. I am not exactly sure how to fix it.
try replace
from django.conf import settings
settings._target = None
os.environ['DJANGO_SETTINGS_MODULE'] = 'untitled.settings'
to
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "untitled.settings")
from django.conf import settings
settings._target = None

Serve static files when using the Django WSGI app

I am using the python-reload package. The readme gives this code to use it with django:
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "hello.settings")
from django.core.management import execute_from_command_line
if 'livereload' in sys.argv:
from django.core.wsgi import get_wsgi_application
from livereload import Server
application = get_wsgi_application()
server = Server(application)
# Add your watch
# server.watch('path/to/file', 'your command')
server.serve()
else:
execute_from_command_line(sys.argv)
However Django doesn't serve staticfiles anymore. The runserver command still works, so I guess it's related to the wsgi app. How can I made django serve static files when using WSGI? Is it posible?

Import Error : cannot import register

Getting Import error while trying to run localhost from my urls.py:
from django.conf.urls.defaults import *
from django.conf import settings
from django.http import HttpResponseRedirect
from django.contrib import admin
from mainapp.feeds import LatestReports, CityIdFeed, CitySlugFeed, WardIdFeed, WardSlugFeed,LatestUpdatesByReport
from mainapp.models import City
from social_auth.views import auth as social_auth
from social_auth.views import disconnect as social_disconnect
#Error at this line
from registration.views import register
from mainapp.forms import FMSNewRegistrationForm,FMSAuthenticationForm
from mainapp.views.account import SUPPORTED_SOCIAL_PROVIDERS
from django.contrib.auth import views as auth_views
from mainapp.views.mobile import open311v2
import mainapp.views.cities as cities
Traceback:
ImportError at /
cannot import name register
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 1.3
Exception Type: ImportError
Exception Value:
cannot import name register
Exception Location: /home/sourabh/Django/fixmystreet/fixmystreet/../fixmystreet/urls.py in <module>, line 9
Python Executable: /home/sourabh/Django/fixmystreet/bin/python
Python Version: 2.7.3
Python Path:
['/home/sourabh/Django/fixmystreet/fixmystreet',
'/home/sourabh/Django/fixmystreet/local/lib/python2.7/site-packages/distribute-0.6.24-py2.7.egg',
'/home/sourabh/Django/fixmystreet/local/lib/python2.7/site-packages/pip-1.1-py2.7.egg',
'/home/sourabh/Django/fixmystreet/lib/python2.7/site-packages/distribute-0.6.24-py2.7.egg',
'/home/sourabh/Django/fixmystreet/lib/python2.7/site-packages/pip-1.1-py2.7.egg',
'/home/sourabh/Django/fixmystreet/lib/python2.7',
'/home/sourabh/Django/fixmystreet/lib/python2.7/plat-linux2',
'/home/sourabh/Django/fixmystreet/lib/python2.7/lib-tk',
'/home/sourabh/Django/fixmystreet/lib/python2.7/lib-old',
'/home/sourabh/Django/fixmystreet/lib/python2.7/lib-dynload',
'/usr/lib/python2.7',
'/usr/lib/python2.7/plat-linux2',
'/usr/lib/python2.7/lib-tk',
'/home/sourabh/Django/fixmystreet/local/lib/python2.7/site-packages',
'/home/sourabh/Django/fixmystreet/local/lib/python2.7/site-packages/PIL',
'/home/sourabh/Django/fixmystreet/lib/python2.7/site-packages',
'/home/sourabh/Django/fixmystreet/lib/python2.7/site-packages/PIL']
Server time: Thu, 22 Aug 2013 09:34:40 -0500
If you look at the docs you see that register is something that used to exist and was deprecated in the last version. From the documentation:
The 1.0 release of django-registration represents a complete rewrite
of the previous codebase, and introduces several new features which
[...]
You either downgrade to django-registration v0.8 (where registration.views.register still exists) or learn how to implement the changes to fit the newest version