Django-Channels fails while giving name or service unknown error - django

I've a fairly simple django-channels/daphne/asgi/redis app. The app never has any problem when using chrome but fails miserably when we use firefox (latest version ~ 60). I currently have the following error:
api_1 | 2018-06-12 16:02:24,378 INFO In the connect method
api_1 | xxxxxx:41647 - - [12/Jun/2018:16:02:24] "WSCONNECT /updates/" - -
api_1 | 2018-06-12 16:02:25,049 ERROR Exception inside application: [Errno -2] Name or service not known
api_1 | File "/usr/local/lib/python3.6/site-packages/channels/consumer.py", line 54, in __call__
api_1 | await await_many_dispatch([receive, self.channel_receive], self.dispatch)
api_1 | File "/usr/local/lib/python3.6/site-packages/channels/utils.py", line 48, in await_many_dispatch
api_1 | await dispatch(result)
api_1 | File "/usr/local/lib/python3.6/site-packages/asgiref/sync.py", line 110, in __call__
api_1 | return await asyncio.wait_for(future, timeout=None)
api_1 | File "/usr/local/lib/python3.6/asyncio/tasks.py", line 339, in wait_for
api_1 | return (yield from fut)
api_1 | File "/usr/local/lib/python3.6/concurrent/futures/thread.py", line 56, in run
api_1 | result = self.fn(*self.args, **self.kwargs)
api_1 | File "/usr/local/lib/python3.6/site-packages/channels/db.py", line 13, in thread_handler
api_1 | return super().thread_handler(loop, *args, **kwargs)
api_1 | File "/usr/local/lib/python3.6/site-packages/asgiref/sync.py", line 125, in thread_handler
api_1 | return self.func(*args, **kwargs)
api_1 | File "/usr/local/lib/python3.6/site-packages/channels/consumer.py", line 99, in dispatch
api_1 | handler(message)
api_1 | File "/usr/local/lib/python3.6/site-packages/channels/generic/websocket.py", line 19, in websocket_connect
api_1 | self.connect()
api_1 | File "./flypoll/consumers.py", line 146, in connect
api_1 | async_to_sync(self.channel_layer.group_add)("flypoll_socket_clients", self.channel_name)
api_1 | File "/usr/local/lib/python3.6/site-packages/asgiref/sync.py", line 64, in __call__
api_1 | return call_result.result()
api_1 | File "/usr/local/lib/python3.6/concurrent/futures/_base.py", line 432, in result
api_1 | return self.__get_result()
api_1 | File "/usr/local/lib/python3.6/concurrent/futures/_base.py", line 384, in __get_result
api_1 | raise self._exception
api_1 | File "/usr/local/lib/python3.6/site-packages/asgiref/sync.py", line 78, in main_wrap
api_1 | result = await self.awaitable(*args, **kwargs)
api_1 | File "/usr/local/lib/python3.6/site-packages/channels_redis/core.py", line 283, in group_add
api_1 | async with self.connection(self.consistent_hash(group)) as connection:
api_1 | File "/usr/local/lib/python3.6/site-packages/channels_redis/core.py", line 403, in __aenter__
api_1 | self.conn = await aioredis.create_redis(**self.kwargs)
api_1 | File "/usr/local/lib/python3.6/site-packages/aioredis/commands/__init__.py", line 174, in create_redis
api_1 | loop=loop)
api_1 | File "/usr/local/lib/python3.6/site-packages/aioredis/connection.py", line 107, in create_connection
api_1 | timeout, loop=loop)
api_1 | File "/usr/local/lib/python3.6/asyncio/tasks.py", line 339, in wait_for
api_1 | return (yield from fut)
api_1 | File "/usr/local/lib/python3.6/site-packages/aioredis/stream.py", line 19, in open_connection
api_1 | lambda: protocol, host, port, **kwds)
api_1 | File "/usr/local/lib/python3.6/asyncio/base_events.py", line 734, in create_connection
api_1 | infos = f1.result()
api_1 | File "/usr/local/lib/python3.6/concurrent/futures/thread.py", line 56, in run
api_1 | result = self.fn(*self.args, **self.kwargs)
api_1 | File "/usr/local/lib/python3.6/socket.py", line 745, in getaddrinfo
api_1 | for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
api_1 | [Errno -2] Name or service not known
It says there is a problem with connect method but the connect method is as follows:
def connect(self):
"""
standard connect handler, accepts the connection, and sets up some basic parameters
:return:
"""
logging.info("In the connect method")
self.accept()
async_to_sync(self.channel_layer.group_add)("flypoll_socket_clients", self.channel_name)
The app is dockerized and is hosted on ec2. The redis, python, django are dockerized too. I've updated the modules (asgiref, txaio, twisted, channels, daphne etc) to latest versions but i'm not able to get rid of this.
What could be wrong?

It looks like your django container can't access redis.
In your django settings you must have something like this :
CHANNEL_LAYERS = {
"default": {
"BACKEND": "channels_redis.core.RedisChannelLayer",
"CONFIG": {
"hosts": [('[redis-host-here]', 6379)], # REPLACE redis host here
},
},
}
And that host must be accessible from your django container

Related

Apache Superset Dashboard import is failing with Invalid Command Error

I am able to successfully export the Superset dashboard however importing the same dashboard is resulting in the below error. It was working a few days back.
Not sure what is causing the issue as I am not getting any specific error apart from the below error in the log.
Version: 0.0.0dev
superset_superset.1.uk4h0kabj1ru#xyz-asca-prod-swarm-2 | 2022-07-14 14:36:06,767:INFO:superset.dashboards.commands.importers.dispatcher:Command failed validation
superset_superset.1.uk4h0kabj1ru#xyz-asca-prod-swarm-2 | CommandException
superset_superset.1.uk4h0kabj1ru#xyz-asca-prod-swarm-2 | Traceback (most recent call last):
superset_superset.1.uk4h0kabj1ru#xyz-asca-prod-swarm-2 | File "/usr/local/lib/python3.8/site-packages/flask/app.py", line 1516, in full_dispatch_request
superset_superset.1.uk4h0kabj1ru#xyz-asca-prod-swarm-2 | rv = self.dispatch_request()
superset_superset.1.uk4h0kabj1ru#xyz-asca-prod-swarm-2 | File "/usr/local/lib/python3.8/site-packages/flask/app.py", line 1502, in dispatch_request
superset_superset.1.uk4h0kabj1ru#xyz-asca-prod-swarm-2 | return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
superset_superset.1.uk4h0kabj1ru#xyz-asca-prod-swarm-2 | File "/usr/local/lib/python3.8/site-packages/flask_appbuilder/security/decorators.py", line 89, in wraps
superset_superset.1.uk4h0kabj1ru#xyz-asca-prod-swarm-2 | return f(self, *args, **kwargs)
superset_superset.1.uk4h0kabj1ru#xyz-asca-prod-swarm-2 | File "/app/superset/views/base_api.py", line 113, in wraps
superset_superset.1.uk4h0kabj1ru#xyz-asca-prod-swarm-2 | raise ex
superset_superset.1.uk4h0kabj1ru#xyz-asca-prod-swarm-2 | File "/app/superset/views/base_api.py", line 110, in wraps
superset_superset.1.uk4h0kabj1ru#xyz-asca-prod-swarm-2 | duration, response = time_function(f, self, *args, **kwargs)
superset_superset.1.uk4h0kabj1ru#xyz-asca-prod-swarm-2 | File "/app/superset/utils/core.py", line 1533, in time_function
superset_superset.1.uk4h0kabj1ru#xyz-asca-prod-swarm-2 | response = func(*args, **kwargs)
superset_superset.1.uk4h0kabj1ru#xyz-asca-prod-swarm-2 | File "/app/superset/utils/log.py", line 244, in wrapper
superset_superset.1.uk4h0kabj1ru#xyz-asca-prod-swarm-2 | value = f(*args, **kwargs)
superset_superset.1.uk4h0kabj1ru#xyz-asca-prod-swarm-2 | File "/app/superset/views/base_api.py", line 98, in wraps
superset_superset.1.uk4h0kabj1ru#xyz-asca-prod-swarm-2 | return f(self, *args, **kwargs)
superset_superset.1.uk4h0kabj1ru#xyz-asca-prod-swarm-2 | File "/app/superset/dashboards/api.py", line 1029, in import_
superset_superset.1.uk4h0kabj1ru#xyz-asca-prod-swarm-2 | command.run()
superset_superset.1.uk4h0kabj1ru#xyz-asca-prod-swarm-2 | File "/app/superset/dashboards/commands/importers/dispatcher.py", line 64, in run
superset_superset.1.uk4h0kabj1ru#xyz-asca-prod-swarm-2 | raise exc
superset_superset.1.uk4h0kabj1ru#xyz-asca-prod-swarm-2 | File "/app/superset/dashboards/commands/importers/dispatcher.py", line 57, in run
superset_superset.1.uk4h0kabj1ru#xyz-asca-prod-swarm-2 | command.run()
superset_superset.1.uk4h0kabj1ru#xyz-asca-prod-swarm-2 | File "/app/superset/commands/importers/v1/__init__.py", line 64, in run
superset_superset.1.uk4h0kabj1ru#xyz-asca-prod-swarm-2 | self.validate()
superset_superset.1.uk4h0kabj1ru#xyz-asca-prod-swarm-2 | File "/app/superset/commands/importers/v1/__init__.py", line 95, in validate
superset_superset.1.uk4h0kabj1ru#xyz-asca-prod-swarm-2 | raise exception
superset_superset.1.uk4h0kabj1ru#xyz-asca-prod-swarm-2 | superset.commands.exceptions.CommandInvalidError: Error importing dashboard
superset_superset.1.uk4h0kabj1ru#xyz-asca-prod-swarm-2 | 2022-07-14 14:36:06,768:WARNING:superset.views.base:CommandException
superset_superset.1.uk4h0kabj1ru#xyz-asca-prod-swarm-2 | Traceback (most recent call last):
superset_superset.1.uk4h0kabj1ru#xyz-asca-prod-swarm-2 | File "/usr/local/lib/python3.8/site-packages/flask/app.py", line 1516, in full_dispatch_request
superset_superset.1.uk4h0kabj1ru#xyz-asca-prod-swarm-2 | rv = self.dispatch_request()
superset_superset.1.uk4h0kabj1ru#xyz-asca-prod-swarm-2 | File "/usr/local/lib/python3.8/site-packages/flask/app.py", line 1502, in dispatch_request
superset_superset.1.uk4h0kabj1ru#xyz-asca-prod-swarm-2 | return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
superset_superset.1.uk4h0kabj1ru#xyz-asca-prod-swarm-2 | File "/usr/local/lib/python3.8/site-packages/flask_appbuilder/security/decorators.py", line 89, in wraps
superset_superset.1.uk4h0kabj1ru#xyz-asca-prod-swarm-2 | return f(self, *args, **kwargs)
superset_superset.1.uk4h0kabj1ru#xyz-asca-prod-swarm-2 | File "/app/superset/views/base_api.py", line 113, in wraps
superset_superset.1.uk4h0kabj1ru#xyz-asca-prod-swarm-2 | raise ex
superset_superset.1.uk4h0kabj1ru#xyz-asca-prod-swarm-2 | File "/app/superset/views/base_api.py", line 110, in wraps
superset_superset.1.uk4h0kabj1ru#xyz-asca-prod-swarm-2 | duration, response = time_function(f, self, *args, **kwargs)
superset_superset.1.uk4h0kabj1ru#xyz-asca-prod-swarm-2 | File "/app/superset/utils/core.py", line 1533, in time_function
superset_superset.1.uk4h0kabj1ru#xyz-asca-prod-swarm-2 | response = func(*args, **kwargs)
superset_superset.1.uk4h0kabj1ru#xyz-asca-prod-swarm-2 | File "/app/superset/utils/log.py", line 244, in wrapper
superset_superset.1.uk4h0kabj1ru#xyz-asca-prod-swarm-2 | value = f(*args, **kwargs)
superset_superset.1.uk4h0kabj1ru#xyz-asca-prod-swarm-2 | File "/app/superset/views/base_api.py", line 98, in wraps
superset_superset.1.uk4h0kabj1ru#xyz-asca-prod-swarm-2 | return f(self, *args, **kwargs)
superset_superset.1.uk4h0kabj1ru#xyz-asca-prod-swarm-2 | File "/app/superset/dashboards/api.py", line 1029, in import_
superset_superset.1.uk4h0kabj1ru#xyz-asca-prod-swarm-2 | command.run()
superset_superset.1.uk4h0kabj1ru#xyz-asca-prod-swarm-2 | File "/app/superset/dashboards/commands/importers/dispatcher.py", line 64, in run
superset_superset.1.uk4h0kabj1ru#xyz-asca-prod-swarm-2 | raise exc
superset_superset.1.uk4h0kabj1ru#xyz-asca-prod-swarm-2 | File "/app/superset/dashboards/commands/importers/dispatcher.py", line 57, in run
superset_superset.1.uk4h0kabj1ru#xyz-asca-prod-swarm-2 | command.run()
superset_superset.1.uk4h0kabj1ru#xyz-asca-prod-swarm-2 | File "/app/superset/commands/importers/v1/__init__.py", line 64, in run
superset_superset.1.uk4h0kabj1ru#xyz-asca-prod-swarm-2 | self.validate()
superset_superset.1.uk4h0kabj1ru#xyz-asca-prod-swarm-2 | File "/app/superset/commands/importers/v1/__init__.py", line 95, in validate
superset_superset.1.uk4h0kabj1ru#xyz-asca-prod-swarm-2 | raise exception
superset_superset.1.uk4h0kabj1ru#xyz-asca-prod-swarm-2 | superset.commands.exceptions.CommandInvalidError: Error importing dashboard

why is Django not accepting the file sending from React Native app?

I am using Django for the Backend Server and React Native for a mobile app I am trying to upload an image from there but it is giving a 500 server error.
Views.py form Django
#api_view(['POST'])
def setFakeProfile(request):
if request.method=='POST':
user = Token.objects.get(key = request.META.get('HTTP_AUTHORIZATION').split(' ')[1]).user
profile = Profile.objects.get(user=user)
fakeProfiles = profile.fakeProfiles.filter(isProfileReadyToUse=False)
print(request.data)
print(request.FILES)
if fakeProfiles.exists():
fakeProfile = fakeProfiles[0]
fakeProfile.displayName = request.data["displayName"]
fakeProfile.profilePicture = request.FILES.get('profilePicture')
fakeProfile.isProfileReadyToUse = True
fakeProfile.save()
return Response({'status':'success', 'id':fakeProfile.id})
else:
return Response({'status':'failed', "message":"First select the chating platform."})
return Response({
'status':'success',
})
return Response({'status':'failed'})
The error that I am getting is there. I knew about the error and I also tried a lot of ways to resolve it but not still don't know how to fix it.
{'_parts': [['displayName', 'name'], ['profilePicture', {'cancelled': False, 'type': 'image', 'uri': 'file:///data/user/0/host.exp.exponent/cache/ExperienceData/%2540sumit2232%252FUnknownChats/ImagePicker/584abe5b-7f5e-45cb-81bd-fcb5751e3ed4.png', 'width': 1692, 'height': 1692}]]}
app_1 | <MultiValueDict: {}>
app_1 | Internal Server Error: /setFakeProfile/
app_1 | Traceback (most recent call last):
app_1 | File "/py/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner
app_1 | response = get_response(request)
app_1 | File "/py/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response
app_1 | response = wrapped_callback(request, *callback_args, **callback_kwargs)
app_1 | File "/py/lib/python3.9/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
app_1 | return view_func(*args, **kwargs)
app_1 | File "/py/lib/python3.9/site-packages/django/views/generic/base.py", line 70, in view
app_1 | return self.dispatch(request, *args, **kwargs)
app_1 | File "/py/lib/python3.9/site-packages/rest_framework/views.py", line 509, in dispatch
app_1 | response = self.handle_exception(exc)
app_1 | File "/py/lib/python3.9/site-packages/rest_framework/views.py", line 469, in handle_exception
app_1 | self.raise_uncaught_exception(exc)
app_1 | File "/py/lib/python3.9/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
app_1 | raise exc
app_1 | File "/py/lib/python3.9/site-packages/rest_framework/views.py", line 506, in dispatch
app_1 | response = handler(request, *args, **kwargs)
app_1 | File "/py/lib/python3.9/site-packages/rest_framework/decorators.py", line 50, in handler
app_1 | return func(*args, **kwargs)
app_1 | File "/app/core/views.py", line 318, in setFakeProfile
app_1 | fakeProfile.displayName = request.data["displayName"]
app_1 | KeyError: 'displayName'
app_1 | [03/May/2022 12:32:32] "POST /setFakeProfile/ HTTP/1.1" 500 91167
app_1 | {'_parts': [['displayName', 'name'], ['profilePicture', 'file:///data/user/0/host.exp.exponent/cache/ExperienceData/%2540sumit2232%252FUnknownChats/ImagePicker/584abe5b-7f5e-45cb-81bd-fcb5751e3ed4.png']]}
app_1 | <MultiValueDict: {}>
app_1 | Internal Server Error: /setFakeProfile/
app_1 | Traceback (most recent call last):
app_1 | File "/py/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner
app_1 | response = get_response(request)
app_1 | File "/py/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response
app_1 | response = wrapped_callback(request, *callback_args, **callback_kwargs)
app_1 | File "/py/lib/python3.9/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
app_1 | return view_func(*args, **kwargs)
app_1 | File "/py/lib/python3.9/site-packages/django/views/generic/base.py", line 70, in view
app_1 | response = self.handle_exception(exc)
app_1 | File "/py/lib/python3.9/site-packages/rest_framework/views.py", line 469, in handle_exception
app_1 | self.raise_uncaught_exception(exc)
app_1 | File "/py/lib/python3.9/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
app_1 | raise exc
app_1 | File "/py/lib/python3.9/site-packages/rest_framework/views.py", line 506, in dispatch
app_1 | response = handler(request, *args, **kwargs)
app_1 | File "/py/lib/python3.9/site-packages/rest_framework/decorators.py", line 50, in handler
app_1 | return func(*args, **kwargs)
app_1 | File "/app/core/views.py", line 318, in setFakeProfile
app_1 | fakeProfile.displayName = request.data["displayName"]
app_1 | KeyError: 'displayName'
app_1 | [03/May/2022 12:32:52] "POST /setFakeProfile/ HTTP/1.1" 500 91167
Let's see the React Native code.
const [displayName, setDisplayName] = useState("");
const [displayImage, setDisplayImage] = useState(null);
const [error, setError] = useState('');
const pickImage = async () => {
// No permissions request is necessary for launching the image library
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.All,
allowsEditing: true,
aspect: [1, 1],
quality: 1,
});
console.log(result);
if (!result.cancelled) {
setDisplayImage({
...result,
uri: Platform.OS === 'ios' ? result.uri.replace('file://', '') : result.uri,
});
}
};
const onSubmit = async () =>{
console.log("submit");
const formData = new FormData();
formData.append('displayName', displayName);
formData.append('profilePicture', displayImage);
await axios.post(
`${baseUrl}setFakeProfile/`,
formData,
{
headers: {
// 'Content-Type': 'multipart/form-data',
// 'Accept': 'multipart/form-data',
'Content-Type': 'application/json',
'Accept': "application/json",
'Authorization': `Token ${await getData('token')}`
}
}
).then(res=>{
if (res.data.status==="success"){
dispatch(setFakeProfileIdToOpen(res.data.id));
navigation.navigate('FakeAccount');
}else{
setError(res.data.message);
console.log(res.data.message);
}
}).catch(err=>console.log(err));
}
I also tried with the commented code (means 'Content-Type': 'multipart/form-data' ) but it is still not working.

Cookiecutter - Django: Anymail[SES] boto3 region error

I am trying to deploy to AWS(EC2) a Cookiecutter Django project.
The AWS user with this credentials has ful S3, SES and SNS policies.
The EC2 server has also a role with full SES/S3 policies.
In production file in envs I have the keys set up like this.
DJANGO_AWS_ACCESS_KEY_ID=xxxxxxxxx
DJANGO_AWS_SECRET_ACCESS_KEY=xxxxxxxxxx
DJANGO_AWS_STORAGE_BUCKET_NAME=xxxxxxxxxx
In settings I have
AWS_S3_REGION_NAME = env("DJANGO_AWS_S3_REGION_NAME", default=None)
AWS_ACCESS_KEY_ID = env("DJANGO_AWS_ACCESS_KEY_ID")
AWS_SECRET_ACCESS_KEY = env("DJANGO_AWS_SECRET_ACCESS_KEY")
AWS_STORAGE_BUCKET_NAME = env("DJANGO_AWS_STORAGE_BUCKET_NAME")
EMAIL_BACKEND = "anymail.backends.amazon_ses.EmailBackend"
ANYMAIL = {}
All nice and fine until the project tries to send an email using SES and it crashes with the error bellow .
Until now I have tried:
adding DJANGO_AWS_S3_REGION_NAME to the production file in envs - no result
adding the region in aws config using aws cli - no result
overriding the settings in ANYMAIL ={} with credetials and region - no result
making a blank project, just adding the aws credentials and not changing anything else - no result
creating manually on another project a boto3.session.client with the same credentials and sending a mail - it works
This is the error. The second part with 'NoneType' object has no attribute 'send_raw_email' repeats a lot after this.
django_1 | [2021-08-13 13:58:14 +0000] [12] [ERROR] Error handling request /accounts/signup/
django_1 | Traceback (most recent call last):
django_1 | File "/usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner
django_1 | response = get_response(request)
django_1 | File "/usr/local/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response
django_1 | response = wrapped_callback(request, *callback_args, **callback_kwargs)
django_1 | File "/usr/local/lib/python3.9/contextlib.py", line 79, in inner
django_1 | return func(*args, **kwds)
django_1 | File "/usr/local/lib/python3.9/site-packages/django/views/generic/base.py", line 70, in view
django_1 | return self.dispatch(request, *args, **kwargs)
django_1 | File "/usr/local/lib/python3.9/site-packages/django/utils/decorators.py", line 43, in _wrapper
django_1 | return bound_method(*args, **kwargs)
django_1 | File "/usr/local/lib/python3.9/site-packages/django/views/decorators/debug.py", line 89, in sensitive_post_parameters_wrapper
django_1 | return view(request, *args, **kwargs)
django_1 | File "/usr/local/lib/python3.9/site-packages/allauth/account/views.py", line 230, in dispatch
django_1 | return super(SignupView, self).dispatch(request, *args, **kwargs)
django_1 | File "/usr/local/lib/python3.9/site-packages/allauth/account/views.py", line 74, in dispatch
django_1 | response = super(RedirectAuthenticatedUserMixin, self).dispatch(
django_1 | File "/usr/local/lib/python3.9/site-packages/allauth/account/views.py", line 204, in dispatch
django_1 | return super(CloseableSignupMixin, self).dispatch(request, *args, **kwargs)
django_1 | File "/usr/local/lib/python3.9/site-packages/django/views/generic/base.py", line 98, in dispatch
django_1 | return handler(request, *args, **kwargs)
django_1 | File "/usr/local/lib/python3.9/site-packages/allauth/account/views.py", line 102, in post
django_1 | response = self.form_valid(form)
django_1 | File "/usr/local/lib/python3.9/site-packages/allauth/account/views.py", line 248, in form_valid
django_1 | return complete_signup(
django_1 | File "/usr/local/lib/python3.9/site-packages/allauth/account/utils.py", line 209, in complete_signup
django_1 | return perform_login(
django_1 | File "/usr/local/lib/python3.9/site-packages/allauth/account/utils.py", line 175, in perform_login
django_1 | send_email_confirmation(request, user, signup=signup, email=email)
django_1 | File "/usr/local/lib/python3.9/site-packages/allauth/account/utils.py", line 346, in send_email_confirmation
django_1 | email_address.send_confirmation(request, signup=signup)
django_1 | File "/usr/local/lib/python3.9/site-packages/allauth/account/models.py", line 62, in send_confirmation
django_1 | confirmation.send(request, signup=signup)
django_1 | File "/usr/local/lib/python3.9/site-packages/allauth/account/models.py", line 169, in send
django_1 | get_adapter(request).send_confirmation_mail(request, self, signup)
django_1 | File "/usr/local/lib/python3.9/site-packages/allauth/account/adapter.py", line 464, in send_confirmation_mail
django_1 | self.send_mail(email_template, emailconfirmation.email_address.email, ctx)
django_1 | File "/usr/local/lib/python3.9/site-packages/allauth/account/adapter.py", line 136, in send_mail
django_1 | msg.send()
django_1 | File "/usr/local/lib/python3.9/site-packages/django/core/mail/message.py", line 284, in send
django_1 | return self.get_connection(fail_silently).send_messages([self])
django_1 | File "/usr/local/lib/python3.9/site-packages/anymail/backends/base.py", line 89, in send_messages
django_1 | created_session = self.open()
django_1 | File "/usr/local/lib/python3.9/site-packages/anymail/backends/amazon_ses.py", line 44, in open
django_1 | self.client = boto3.session.Session(**self.session_params).client("ses", **self.client_params)
django_1 | File "/usr/local/lib/python3.9/site-packages/boto3/session.py", line 258, in client
django_1 | return self._session.create_client(
django_1 | File "/usr/local/lib/python3.9/site-packages/botocore/session.py", line 847, in create_client
django_1 | client = client_creator.create_client(
django_1 | File "/usr/local/lib/python3.9/site-packages/botocore/client.py", line 86, in create_client
django_1 | client_args = self._get_client_args(
django_1 | File "/usr/local/lib/python3.9/site-packages/botocore/client.py", line 355, in _get_client_args
django_1 | return args_creator.get_client_args(
django_1 | File "/usr/local/lib/python3.9/site-packages/botocore/args.py", line 71, in get_client_args
django_1 | final_args = self.compute_client_args(
django_1 | File "/usr/local/lib/python3.9/site-packages/botocore/args.py", line 148, in compute_client_args
django_1 | endpoint_config = self._compute_endpoint_config(
django_1 | File "/usr/local/lib/python3.9/site-packages/botocore/args.py", line 220, in _compute_endpoint_config
django_1 | return self._resolve_endpoint(**resolve_endpoint_kwargs)
django_1 | File "/usr/local/lib/python3.9/site-packages/botocore/args.py", line 302, in _resolve_endpoint
django_1 | return endpoint_bridge.resolve(
django_1 | File "/usr/local/lib/python3.9/site-packages/botocore/client.py", line 430, in resolve
django_1 | resolved = self.endpoint_resolver.construct_endpoint(
django_1 | File "/usr/local/lib/python3.9/site-packages/botocore/regions.py", line 133, in construct_endpoint
django_1 | result = self._endpoint_for_partition(
django_1 | File "/usr/local/lib/python3.9/site-packages/botocore/regions.py", line 148, in _endpoint_for_partition
django_1 | raise NoRegionError()
django_1 | botocore.exceptions.NoRegionError: You must specify a region.
django_1 |
django_1 | During handling of the above exception, another exception occurred:
django_1 |
django_1 | Traceback (most recent call last):
django_1 | File "/usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner
django_1 | response = get_response(request)
django_1 | File "/usr/local/lib/python3.9/site-packages/django/utils/deprecation.py", line 114, in __call__
django_1 | response = response or self.get_response(request)
django_1 | File "/usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 49, in inner
django_1 | response = response_for_exception(request, exc)
django_1 | File "/usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 104, in response_for_exception
django_1 | log_response(
django_1 | File "/usr/local/lib/python3.9/site-packages/django/utils/log.py", line 224, in log_response
django_1 | getattr(logger, level)(
django_1 | File "/usr/local/lib/python3.9/logging/__init__.py", line 1475, in error
django_1 | self._log(ERROR, msg, args, **kwargs)
django_1 | File "/usr/local/lib/python3.9/logging/__init__.py", line 1589, in _log
django_1 | self.handle(record)
django_1 | File "/usr/local/lib/python3.9/logging/__init__.py", line 1599, in handle
django_1 | self.callHandlers(record)
django_1 | File "/usr/local/lib/python3.9/logging/__init__.py", line 1661, in callHandlers
django_1 | hdlr.handle(record)
django_1 | File "/usr/local/lib/python3.9/logging/__init__.py", line 952, in handle
django_1 | self.emit(record)
django_1 | File "/usr/local/lib/python3.9/site-packages/django/utils/log.py", line 122, in emit
django_1 | self.send_mail(subject, message, fail_silently=True, html_message=html_message)
django_1 | File "/usr/local/lib/python3.9/site-packages/django/utils/log.py", line 125, in send_mail
django_1 | mail.mail_admins(subject, message, *args, connection=self.connection(), **kwargs)
django_1 | File "/usr/local/lib/python3.9/site-packages/django/core/mail/__init__.py", line 104, in mail_admins
django_1 | mail.send(fail_silently=fail_silently)
django_1 | File "/usr/local/lib/python3.9/site-packages/django/core/mail/message.py", line 284, in send
django_1 | return self.get_connection(fail_silently).send_messages([self])
django_1 | File "/usr/local/lib/python3.9/site-packages/anymail/backends/base.py", line 94, in send_messages
django_1 | sent = self._send(message)
django_1 | File "/usr/local/lib/python3.9/site-packages/anymail/backends/base.py", line 124, in _send
django_1 | response = self.post_to_esp(payload, message)
django_1 | File "/usr/local/lib/python3.9/site-packages/anymail/backends/amazon_ses.py", line 67, in post_to_esp
django_1 | response = payload.call_send_api(self.client)
django_1 | File "/usr/local/lib/python3.9/site-packages/anymail/backends/amazon_ses.py", line 127, in call_send_api
django_1 | return ses_client.send_raw_email(**self.params)
django_1 | AttributeError: 'NoneType' object has no attribute 'send_raw_email'
I'll appreciate any input. I'm out of ideas.
Thanks!
As you've probably figured out, the problem is boto3 doesn't know what AWS region you're trying to operate in:
botocore.exceptions.NoRegionError: You must specify a region.
The region name comes from boto3 configuration. From Anymail's SES docs:
you must make sure boto3 is configured with AWS credentials having the necessary IAM permissions. There are several ways to do this; see Credentials in the Boto docs for options. Usually, an IAM role for EC2 instances, standard Boto environment variables, or a shared AWS credentials file will be appropriate. For more complex cases, use Anymail’s AMAZON_SES_CLIENT_PARAMS setting to customize the Boto session.
It seems like you might be try to mix some of the "several ways" to provide boto3 credentials, which could be causing confusion.
Note that your AWS_* Django settings don't come into play. boto3 doesn't know about Django settings. Anymail's SES settings docs describe which Django settings Anymail will pass along to boto3. (And AWS_S3_REGION_NAME wouldn't be relevant anyway, because S3 is not the same service as SES. I'm guessing those AWS_* Django settings may be for some other app, maybe django-storages.)
If you want to provide AWS credentials specifically for Anymail in settings.py, you can do that with Anymail's AMAZON_SES_CLIENT_PARAMS setting. E.g.:
# (Be sure to add DJANGO_AWS_REGION_NAME to your env to use this example)
ANYMAIL = {
"AMAZON_SES_CLIENT_PARAMS": {
"aws_access_key_id": env("DJANGO_AWS_ACCESS_KEY_ID"),
"aws_secret_access_key": env("DJANGO_AWS_SECRET_ACCESS_KEY"),
"region_name": env("DJANGO_AWS_REGION_NAME"),
},
}

Django + Mongo + Docker getting pymongo.errors.ServerSelectionTimeoutError

I've been struggling to get a simple app running using Django, Djongo, Mongo, and Docker Compose. My setup looks like this:
docker-compose.yml
services:
mongodb:
image: mongo:latest
restart: always
environment:
MONGO_INITDB_ROOT_USERNAME: root
MONGO_INITDB_ROOT_PASSWORD: mongoadmin
MONGO_INITDB_DATABASE: django_mongodb_docker
ports:
- 27017:27017
web:
build: ./src
restart: always
command: python src/manage.py runserver 0.0.0.0:8000
volumes:
- .:/code
ports:
- 8000:8000
links:
- mongodb
Dockerfile
FROM python:3
ENV PYTHONUNBUFFERED=1
RUN mkdir /code
COPY . /code/
WORKDIR /code
COPY requirements.txt /code/
RUN pip install -r requirements.txt
settings.py
DATABASES = {
'default': {
'ENGINE': 'djongo',
'HOST': 'mongodb',
'PORT': 27017,
'USER': 'root',
'PASSWORD': 'mongoadmin',
'AUTH_SOURCE': 'admin',
'AUTH_MECHANISM': 'SCRAM-SHA-1',
}
}
What is annoying is that I am able to use pymongo from my web container to connect to the container running mongo. That works as follows.
from pymongo import MongoClient
c = MongoClient(
'mongodb://mongodb:27017',
username='root',
password='mongoadmin',
authSource='admin',
authMechanism='SCRAM-SHA-1')
print(c.server_info())
The issue is that when I go to run migrations from within my web container I get the following error.
Traceback (most recent call last):
File "/code/src/manage.py", line 22, in <module>
main()
File "/code/src/manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 330, in run_from_argv
self.execute(*args, **cmd_options)
File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 371, in execute
output = self.handle(*args, **options)
File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 85, in wrapped
res = handle_func(*args, **kwargs)
File "/usr/local/lib/python3.9/site-packages/django/core/management/commands/migrate.py", line 92, in handle
executor = MigrationExecutor(connection, self.migration_progress_callback)
File "/usr/local/lib/python3.9/site-packages/django/db/migrations/executor.py", line 18, in __init__
self.loader = MigrationLoader(self.connection)
File "/usr/local/lib/python3.9/site-packages/django/db/migrations/loader.py", line 53, in __init__
self.build_graph()
File "/usr/local/lib/python3.9/site-packages/django/db/migrations/loader.py", line 216, in build_graph
self.applied_migrations = recorder.applied_migrations()
File "/usr/local/lib/python3.9/site-packages/django/db/migrations/recorder.py", line 77, in applied_migrations
if self.has_table():
File "/usr/local/lib/python3.9/site-packages/django/db/migrations/recorder.py", line 56, in has_table
tables = self.connection.introspection.table_names(cursor)
File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/introspection.py", line 48, in table_names
return get_names(cursor)
File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/introspection.py", line 43, in get_names
return sorted(ti.name for ti in self.get_table_list(cursor)
File "/usr/local/lib/python3.9/site-packages/djongo/introspection.py", line 47, in get_table_list
for c in cursor.db_conn.list_collection_names()
File "/usr/local/lib/python3.9/site-packages/pymongo/database.py", line 863, in list_collection_names
for result in self.list_collections(session=session, **kwargs)]
File "/usr/local/lib/python3.9/site-packages/pymongo/database.py", line 825, in list_collections
return self.__client._retryable_read(
File "/usr/local/lib/python3.9/site-packages/pymongo/mongo_client.py", line 1460, in _retryable_read
server = self._select_server(
File "/usr/local/lib/python3.9/site-packages/pymongo/mongo_client.py", line 1278, in _select_server
server = topology.select_server(server_selector)
File "/usr/local/lib/python3.9/site-packages/pymongo/topology.py", line 241, in select_server
return random.choice(self.select_servers(selector,
File "/usr/local/lib/python3.9/site-packages/pymongo/topology.py", line 199, in select_servers
server_descriptions = self._select_servers_loop(
File "/usr/local/lib/python3.9/site-packages/pymongo/topology.py", line 215, in _select_servers_loop
raise ServerSelectionTimeoutError(
pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [Errno 111] Connection refused, Timeout: 30s, Topology Description: <TopologyDescription id: 5f9ecaa5bbdc0433baa13966, topology_type: Single, servers: [<ServerDescription ('localhost', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('localhost:27017: [Errno 111] Connection refused')>]>
In addition, I've tried to create a Djongo model and save it to see if maybe the problem is specific to migrations (essentially just trying to make any connection to mongo using djongo).
models.py
from djongo import models
class Blog(models.Model):
name = models.CharField(max_length=100)
test.py
b = Blog(name='test')
b.save()
That returns the following error:
The above exception was the direct cause of the following exception:
web_1 |
web_1 | Traceback (most recent call last):
web_1 | File "/usr/local/lib/python3.9/site-packages/djongo/cursor.py", line 51, in execute
web_1 | self.result = Query(
web_1 | File "/usr/local/lib/python3.9/site-packages/djongo/sql2mongo/query.py", line 783, in __init__
web_1 | self._query = self.parse()
web_1 | File "/usr/local/lib/python3.9/site-packages/djongo/sql2mongo/query.py", line 884, in parse
web_1 | raise exe from e
web_1 | djongo.exceptions.SQLDecodeError:
web_1 |
web_1 | Keyword: None
web_1 | Sub SQL: None
web_1 | FAILED SQL: INSERT INTO "game_blog" ("name") VALUES (%(0)s)
web_1 | Params: ['test']
web_1 | Version: 1.3.3
web_1 |
web_1 | The above exception was the direct cause of the following exception:
web_1 |
web_1 | Traceback (most recent call last):
web_1 | File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute
web_1 | return self.cursor.execute(sql, params)
web_1 | File "/usr/local/lib/python3.9/site-packages/djongo/cursor.py", line 59, in execute
web_1 | raise db_exe from e
web_1 | djongo.database.DatabaseError
web_1 |
web_1 | The above exception was the direct cause of the following exception:
web_1 |
web_1 | Traceback (most recent call last):
web_1 | File "/usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner
web_1 | response = get_response(request)
web_1 | File "/usr/local/lib/python3.9/site-packages/django/core/handlers/base.py", line 179, in _get_response
web_1 | response = wrapped_callback(request, *callback_args, **callback_kwargs)
web_1 | File "/usr/local/lib/python3.9/site-packages/django/views/generic/base.py", line 70, in view
web_1 | return self.dispatch(request, *args, **kwargs)
web_1 | File "/usr/local/lib/python3.9/site-packages/django/views/generic/base.py", line 98, in dispatch
web_1 | return handler(request, *args, **kwargs)
web_1 | File "/code/src/game/views.py", line 9, in get
web_1 | b.save(using='mongo')
web_1 | File "/usr/local/lib/python3.9/site-packages/django/db/models/base.py", line 753, in save
web_1 | self.save_base(using=using, force_insert=force_insert,
web_1 | File "/usr/local/lib/python3.9/site-packages/django/db/models/base.py", line 790, in save_base
web_1 | updated = self._save_table(
web_1 | File "/usr/local/lib/python3.9/site-packages/django/db/models/base.py", line 895, in _save_table
web_1 | results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
web_1 | File "/usr/local/lib/python3.9/site-packages/django/db/models/base.py", line 933, in _do_insert
web_1 | return manager._insert(
web_1 | File "/usr/local/lib/python3.9/site-packages/django/db/models/manager.py", line 85, in manager_method
web_1 | return getattr(self.get_queryset(), name)(*args, **kwargs)
web_1 | File "/usr/local/lib/python3.9/site-packages/django/db/models/query.py", line 1254, in _insert
web_1 | return query.get_compiler(using=using).execute_sql(returning_fields)
web_1 | File "/usr/local/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 1397, in execute_sql
web_1 | cursor.execute(sql, params)
web_1 | File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 98, in execute
web_1 | return super().execute(sql, params)
web_1 | File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 66, in execute
web_1 | return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
web_1 | File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 75, in _execute_with_wrappers
web_1 | return executor(sql, params, many, context)
web_1 | File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute
web_1 | return self.cursor.execute(sql, params)
web_1 | File "/usr/local/lib/python3.9/site-packages/django/db/utils.py", line 90, in __exit__
web_1 | raise dj_exc_value.with_traceback(traceback) from exc_value
web_1 | File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute
web_1 | return self.cursor.execute(sql, params)
web_1 | File "/usr/local/lib/python3.9/site-packages/djongo/cursor.py", line 59, in execute
web_1 | raise db_exe from e
web_1 | django.db.utils.DatabaseError
Any help on this would be greatly appreciated.
I have tried editing my mongodb.conf like this already.
According to this document, the settings.py should have a CLIENT section which contains:
A set of key-value pairs that will be passed directly to MongoClient as kwargs while creating a new client connection.
So try setting your settings.py to:
DATABASE = {
'default': {
'ENGINE': 'djongo',
'NAME': 'your-database-name',
'CLIENT': {
'host': 'mongodb://mongodb:27017',
'username': 'root',
'password': 'mongoadmin',
'authSource': 'admin',
'authMechanism': 'SCRAM-SHA-1',
}
}
}

Django: sending email causes OSError

I'm setting up registration proces for my Django REST API. I use "email.send()" function in my SignUpView. When I create new user, it should send him activation link. Unfortunately i get "OSError: [Errno 99] Cannot assign requested address".
I was looking for some solutions, but all was conected to some problems with sockets. Despite this I tried to change my ports in settings.
My email settings in settings.py:
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'myemail#gmail.com'
EMAIL_HOST_PASSWORD= 'mypassword'
EMAIL_PORT = 587
View i used to signup:
class SignUp(APIView):
def post(self, request, format=None):
serializer = SignUpSerializer(data=request.data)
if serializer.is_valid():
user = serializer.save(is_active=False)
current_site = get_current_site(request)
mail_subject = 'Aktywuj swoje konto w serwisie Podwoozka.'
message = 'user: ', user.username,'domain', current_site.domain,'uid',urlsafe_base64_encode(force_bytes(user.pk)).decode(),'token', account_activation_token.make_token(user),
to_email = user.email
email = EmailMessage(
mail_subject, message, to=[to_email]
)
email.send()
return HttpResponse('Potwierdz email aby zakonczyc rejestracje.')
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
And finally entire Traceback when i use this function:
Traceback (most recent call last):
api_1 | File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
api_1 | response = get_response(request)
api_1 | File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 126, in _get_response
api_1 | response = self.process_exception_by_middleware(e, request)
api_1 | File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 124, in _get_response
api_1 | response = wrapped_callback(request, *callback_args, **callback_kwargs)
api_1 | File "/usr/local/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
api_1 | return view_func(*args, **kwargs)
api_1 | File "/usr/local/lib/python3.7/site-packages/django/views/generic/base.py", line 68, in view
api_1 | return self.dispatch(request, *args, **kwargs)
api_1 | File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py", line 495, in dispatch
api_1 | response = self.handle_exception(exc)
api_1 | File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py", line 455, in handle_exception
api_1 | self.raise_uncaught_exception(exc)
api_1 | File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py", line 492, in dispatch
api_1 | response = handler(request, *args, **kwargs)
api_1 | File "/Dback/races/views.py", line 264, in post
api_1 | email.send()
api_1 | File "/usr/local/lib/python3.7/site-packages/django/core/mail/message.py", line 291, in send
api_1 | return self.get_connection(fail_silently).send_messages([self])
api_1 | File "/usr/local/lib/python3.7/site-packages/django/core/mail/backends/smtp.py", line 103, in send_messages
api_1 | new_conn_created = self.open()
api_1 | File "/usr/local/lib/python3.7/site-packages/django/core/mail/backends/smtp.py", line 63, in open
api_1 | self.connection = self.connection_class(self.host, self.port, **connection_params)
api_1 | File "/usr/local/lib/python3.7/smtplib.py", line 251, in __init__
api_1 | (code, msg) = self.connect(host, port)
api_1 | File "/usr/local/lib/python3.7/smtplib.py", line 336, in connect
api_1 | self.sock = self._get_socket(host, port, self.timeout)
api_1 | File "/usr/local/lib/python3.7/smtplib.py", line 307, in _get_socket
api_1 | self.source_address)
api_1 | File "/usr/local/lib/python3.7/socket.py", line 727, in create_connection
api_1 | raise err
api_1 | File "/usr/local/lib/python3.7/socket.py", line 716, in create_connection
api_1 | sock.connect(sa)
api_1 | OSError: [Errno 99] Cannot assign requested address
I don't know if its important, but im using docker in this project. I heard sometimes there are some problems with outgoing connections from container.
EDIT: I tried to run it in pipenv instead of docker, still not working.
This time its "ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it"
First, make sure that you enabled POP access in Gmail:
https://support.google.com/mail/answer/7104828?hl=en&visit_id=637244831918669326-2427073497&rd=1
Then, if you receive Application-specific password required error, set up an app password for your account:
https://support.google.com/accounts/answer/185833?p=InvalidSecondFactor&visit_id=637244831918669326-2427073497&rd=1
In my case, this problem has been resolved with set SMTP_BLCOK = off.
in ssh or terminal
You must run the 3 commands in your ssh or terminal:
vi /etc/csf/csf.conf
SMTP_BLOCK = "0"
csf -r
in cpanel
You must follow this path:
WHM >‌ Plugins > ConfigServer Security & Firewall > Firewall Configuration > SMTP_BLCOK
and set SMTP_BLCOK = OFF