Django: sending email causes OSError - django

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

Related

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 authlib MismatchingStateError on authorize_access_token

I have some issue on django authlib client https://docs.authlib.org/en/latest/client/django.html. On redirect url, authorize_access_token raise raise MismatchingStateError().
This is my code:
def login(request):
# google = oauth.create_client('google')
authservice = oauth.create_client('authservice')
redirect_uri = 'http://localhost:8050/authorize'
authservice.save_authorize_data(request)
return authservice.authorize_redirect(request, redirect_uri)
def authorize(request):
token = oauth.authservice.authorize_access_token(request)
userinfo = oauth.authservice.parse_id_token(request, token)
resp = oauth.authservice.userinfo(token=token)
return JsonResponse(token, safe=False)
And the stacktrace :
Internal Server Error: /authorize/
app_1 | Traceback (most recent call last):
app_1 | File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
app_1 | response = get_response(request)
app_1 | File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response
app_1 | response = self.process_exception_by_middleware(e, request)
app_1 | File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
app_1 | response = wrapped_callback(request, *callback_args, **callback_kwargs)
app_1 | File "/opt/project/access/views.py", line 141, in authorize
app_1 | token = oauth.authservice.authorize_access_token(request)
app_1 | File "/usr/local/lib/python3.7/site-packages/authlib/integrations/django_client/integration.py", line 66, in authorize_access_token
app_1 | params = self.retrieve_access_token_params(request)
app_1 | File "/usr/local/lib/python3.7/site-packages/authlib/integrations/base_client/base_app.py", line 144, in retrieve_access_token_params
app_1 | params = self._retrieve_oauth2_access_token_params(request, params)
app_1 | File "/usr/local/lib/python3.7/site-packages/authlib/integrations/base_client/base_app.py", line 126, in _retrieve_oauth2_access_token_params
app_1 | raise MismatchingStateError()
app_1 | authlib.integrations.base_client.errors.MismatchingStateError: mismatching_state: CSRF Warning! State not equal in request and response.
If someone has an idea on how to fix it, it will be great.
Thank you guys :)
I believe the error may be happening since the url configured in your app is not the same as 'http://localhost:8050/authorize'
Check and verify if they are the same or not. Also, see this.

Django-Channels fails while giving name or service unknown error

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

Serializer object has no attribute '_writable_fields'

I have started writing an app in django with mongodb (my first time). But I'm getting this error related to my DRF-mongoengine serializer. The error reads:
AttributeError: 'UserSerializer' object has no attribute '_writable_fields'
Full Traceback is as follows:
Traceback (most recent call last):
web_1 | File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 132, in get_response
web_1 | response = wrapped_callback(request, *callback_args, **callback_kwargs)
web_1 | File "/usr/local/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
web_1 | return view_func(*args, **kwargs)
web_1 | File "/usr/local/lib/python2.7/site-packages/rest_framework/viewsets.py", line 85, in view
web_1 | return self.dispatch(request, *args, **kwargs)
web_1 | File "/usr/local/lib/python2.7/site-packages/rest_framework/views.py", line 407, in dispatch
web_1 | response = self.handle_exception(exc)
web_1 | File "/usr/local/lib/python2.7/site-packages/rest_framework/views.py", line 404, in dispatch
web_1 | response = handler(request, *args, **kwargs)
web_1 | File "/usr/local/lib/python2.7/site-packages/rest_framework/mixins.py", line 20, in create
web_1 | serializer.is_valid(raise_exception=True)
web_1 | File "/usr/local/lib/python2.7/site-packages/rest_framework/serializers.py", line 186, in is_valid
web_1 | self._validated_data = self.run_validation(self.initial_data)
web_1 | File "/usr/local/lib/python2.7/site-packages/rest_framework/serializers.py", line 364, in run_validation
web_1 | value = self.to_internal_value(data)
web_1 | File "/usr/local/lib/python2.7/site-packages/rest_framework_mongoengine/serializers.py", line 197, in to_internal_value
web_1 | for field in self._writable_fields:
web_1 | AttributeError: 'UserSerializer' object has no attribute '_writable_fields'
This seems to be some problem with the DRF-mongoengine version because when I was using 3.3.0, I had an error about no no attribute named "get_field_names". To resolve that, I moved to 3.3.1 which is the lastest version and I started getting this one. My requirements.txt file is:
blinker == 1.1
Django==1.8.0
django-rest-framework-mongoengine==3.3.1
gunicorn==19.6.0
django-admin-generator==2.0.0
pymongo==2.8
mongoengine==0.9.0
djangorestframework==3.0.4
And my serializers.py file is:
from rest_framework_mongoengine import serializers
from api.models import User
class UserSerializer(serializers.DocumentSerializer):
class Meta:
model = User
fields = '__all__'
My models are:
from mongoengine import *
class User(Document):
name = StringField(max_length=50, required=True)
email = EmailField(max_length=254, required=True)
password = StringField(max_length=100, required=True)
role = StringField(max_length=16, default='basic', required=True)
def __unicode__(self):
return self.name, self.email
Any idea as to what happens to be the problem?