I am currently working on a web-application using VueJS for the front-end and Django (Django Rest Framework) for the back-end.
One of the feature of the application is to send a pdf invoice by mail. So I was able to generate the pdf using "jspdf" library. And on Django side, I made an API end-point in order to send an email (with the pdf attached).
So the logic is (tell me if it's wrong to do that):
Converting the output pdf to Base64 on the front-end in order to post it to my "sendmail" endpoint with Axios.
Decoding the Base64 string on the back-end, write a temp pdf file, and attached it to send the mail.
It works perfectly, I tested it, the post request have a status 200. I receive the mail with the pdf attached... But on django side, I got "[Errno 54] Connection reset by peer".
Here's the full error:
[24/Nov/2020 21:50:53] "POST /api/sendmail/ HTTP/1.1" 200 0
--------------------------------------------
Exception happened during processing of request from ('127.0.0.1', 59267)
Traceback (most recent call last):
File "/Users/jjj/anaconda3/lib/python3.6/socketserver.py", line 639, in process_request_thread
self.finish_request(request, client_address)
File "/Users/jjj/anaconda3/lib/python3.6/socketserver.py", line 361, in finish_request
self.RequestHandlerClass(request, client_address, self)
File "/Users/jjj/anaconda3/lib/python3.6/socketserver.py", line 696, in __init__
self.handle()
File "/Users/jjj/Documents/DEV/Environments/project1_env/lib/python3.6/site-packages/django/core/servers/basehttp.py", line 174, in handle
self.handle_one_request()
File "/Users/jjj/Documents/DEV/Environments/project1_env/lib/python3.6/site-packages/django/core/servers/basehttp.py", line 182, in handle_one_request
self.raw_requestline = self.rfile.readline(65537)
File "/Users/jjj/anaconda3/lib/python3.6/socket.py", line 586, in readinto
return self._sock.recv_into(b)
ConnectionResetError: [Errno 54] Connection reset by peer
The thing is that I tried to do a post request with Postman and it worked without any error... which drives me crazy.
So I suspect the error to be on the front side.
Here's my vue side code:
sendInvoice() {
var mailInfo = {
email: this.currentOrder.email,
pdf: printPDF(this.currentOrder, true)
}
this.postSendMail(mailInfo)
}
and here's my axios code:
postSendMail(context, mailInfo) {
return new Promise((resolve, reject) => {
getAPI.post('/sendmail/', mailInfo)
.then(() => {
resolve()
})
})
},
Do you have any ideas...? Thanks in advance.
Okay, I feel very dumb right now. I just spent 3 hours trying to understand the error.
The reason was that in my axios instance I set the timeout to 1000... and since my Base64 pdf string is quite heavy, it takes more than 1 second. I just set it to 5000 and it works perfectly now!
Related
I have following Class to generate a pdf file where I use django-renderpdf to generate a pdf from a html template. But the view is executed twice and an error is thrown.
My class:
class WeeklyMetre(PDFView):
template_name = 'reports/invoice/weekly_metre.html'
allow_force_html = True
prompt_download = True
#property
def download_name(self) -> str:
invoice = Invoice.objects.get(pk=self.kwargs['pk'])
return f"WeeklyMetre_{invoice.invoice_number}.pdf"
def get_context_data(self, *args, **kwargs):
context = super().get_context_data(*args, **kwargs)
invoice = Invoice.objects.get(pk=self.kwargs.get('pk'))
market_labor_specifications = _getWeeklyMetreData(invoice=invoice)
# calculate reported items: reported market_labor_specifications
# invoiced specifications which are validated in invoice-period
# but labor_date before invoice-period
reported_mls = MarketLaborSpecification.objects.filter(invoice_id=self.kwargs.get('pk'), market_labor__labor_date__lt=invoice.period_from) \
.values('market_labor__labor_date', 'specification__position', 'specification__name') \
.order_by('market_labor__labor_date', 'specification__position', 'specification__name') \
.annotate(sum_pos=Sum('validated_quantity'))
context.update({
'invoice': invoice,
'market_labor_specifications': market_labor_specifications,
'reported_mlss': reported_mls
})
print('context data', datetime.datetime.now())
return context
Between the two excutions I have following error:
[01/Feb/2021 07:16:38] "GET /reports/invoice/select/17/ HTTP/1.1" 200 1414
context data 2021-02-01 07:16:44.835695
[01/Feb/2021 07:16:45] "GET /reports/weekly/metre/17/ HTTP/1.1" 200 58063
----------------------------------------
Exception happened during processing of request from ('127.0.0.1', 60114)
Traceback (most recent call last):
File "/usr/lib/python3.6/socketserver.py", line 654, in process_request_thread
self.finish_request(request, client_address)
File "/usr/lib/python3.6/socketserver.py", line 364, in finish_request
self.RequestHandlerClass(request, client_address, self)
File "/usr/lib/python3.6/socketserver.py", line 724, in __init__
self.handle()
File "/home/t3tr4ktys/python-virtual-environments/BillOfQuantities/lib/python3.6/site-packages/django/core/servers/basehttp.py", line 174, in handle
self.handle_one_request()
File "/home/t3tr4ktys/python-virtual-environments/BillOfQuantities/lib/python3.6/site-packages/django/core/servers/basehttp.py", line 182, in handle_one_request
self.raw_requestline = self.rfile.readline(65537)
File "/usr/lib/python3.6/socket.py", line 586, in readinto
return self._sock.recv_into(b)
ConnectionResetError: [Errno 104] Connection reset by peer
----------------------------------------
context data 2021-02-01 07:16:47.544189
[01/Feb/2021 07:16:48] "GET /reports/weekly/metre/17/ HTTP/1.1" 200 58063
First of all I don't know why it is executed twice and on the second execution the user is no more authenticated. At the end the pdf is generated well but I cannot apply the LoginRequiredMixin. More informations will be provided if needed and thank you for any help.
Looks like you closed tab in browser or browser stopped to accept response from server in some another way. But web server haven't stopped it's renderring and still generates response, but do not have whom to response. That's why you see:
ConnectionResetError: [Errno 104] Connection reset by peer
After that browser does retry with page reload and you see the second request in logs.
So, you need to understand why it happens. See what browser logs and Dev.Tools will show you (statuses, response and etc.).
P.S. About LoginRequiredMixin - don't know probably some internal things of browser caused with that "retry", but I believe it still should send cookies and session_id.
I believe I've experienced something like this.
The problem is that when you call your endpoint you call it in the URL without a '/' at the end causing DRF to return 301
that redirects you to the same path but with '/' at the end. The problem with that, that after the redirect you lose your headers and cookies and thus become unauthenticated.
That also explains why you can see 2 calls.
So basically if you have a call like this:
api/viewset/dosomethngs
to:
api/viewset/dosomethngs/
I am currently trying to connect to my instance of parse-server, created from Bitnami's AWS Parse server image, with the ParsePy python package.
However, the package's register() function requires a 'rest_key' parameter, which I believe to be the parse server instance's Rest API key.
I looked for the key in the following file, which came with the image:
/home/bitnami/apps/parse/htdocs/server.js
And only found parameters labelled masterKey and fileKey. I found a similar question here, but those answers don't direct me to where I would find the key in a Bitnami parse-server image.
Any guidance would be helpful. Thanks!
Edit: The relevant portions of server.js are shared below:
var express = require('express');
var ParseServer = require('parse-server').ParseServer;
var app = express();
var api = new ParseServer({
databaseURI: "mongodb://root:WcbKujWVdiX2#127.0.0.1:27017/bitnami_parse",
cloud: "./node_modules/parse-server/lib/cloud-code/Parse.Cloud.js",
appId: "APP_ID",
masterKey: "MASTER_KEY",
fileKey: "FILE_KEY",
serverURL: "http://34.242.164.250:80/parse"
});
I tried adding a parameter for a restAPIKey before serverURL as follows:
restAPIKey: "REST_API_KEY"
But that simply leads to this error message:
Traceback (most recent call last):
File "/anaconda3/lib/python3.7/site-packages/parse_rest/connection.py", line 140, in execute
response = urlopen(request, timeout=CONNECTION_TIMEOUT)
File "/anaconda3/lib/python3.7/urllib/request.py", line 222, in urlopen
return opener.open(url, data, timeout)
File "/anaconda3/lib/python3.7/urllib/request.py", line 531, in open
response = meth(req, response)
File "/anaconda3/lib/python3.7/urllib/request.py", line 641, in http_response
'http', request, response, code, msg, hdrs)
File "/anaconda3/lib/python3.7/urllib/request.py", line 569, in error
return self._call_chain(*args)
File "/anaconda3/lib/python3.7/urllib/request.py", line 503, in _call_chain
result = func(*args)
File "/anaconda3/lib/python3.7/urllib/request.py", line 649, in http_error_default
raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 410: Parse.com has shutdown - https://parseplatform.github.io/
I have made a webapp in python using web2py which has 3rd party authentication using Janrain as recommended.
On my local server it worked absolutely fine, but now when I deployed on pythonanywhere, the authentication is giving me the following error
"class 'urllib2.URLError' urlopen error Tunnel connection failed: 403 Forbidden"
Stack
===========
File "/usr/lib/python2.7/urllib2.py", line 127, in urlopen
return _opener.open(url, data, timeout)
File "/usr/lib/python2.7/urllib2.py", line 404, in open
response = self._open(req, data)
File "/usr/lib/python2.7/urllib2.py", line 422, in _open
'_open', req)
File "/usr/lib/python2.7/urllib2.py", line 382, in _call_chain
result = func(*args)
File "/usr/lib/python2.7/urllib2.py", line 1222, in https_open
return self.do_open(httplib.HTTPSConnection, req)
File "/usr/lib/python2.7/urllib2.py", line 1184, in do_open
raise URLError(err)
URLError: <urlopen error Tunnel connection failed: 403 Forbidden>
==========================
For third party authentication I had used yahoomail id.
This has now been fixed, but in case anyone else comes across this issue or a similar issue:
the problem was that free users on PythonAnywhere have restricted internet, that goes via a proxy and only allows a whitelist of sites.
The sites .janrain.com and .rpxnow.com weren't on the whitelist at the time, but we have now added them, and the janrain/yahoo mail login now works.
So, for anyone else that happens to be going via a proxy and trying to use this service, those are the sites you need to add. (may also be of interest to paranoid people that like to run noscript, if you find some federated auth system failing, you may need to unblock rpxnow).
Happy coding everyone!
I'm trying to finish the setup of django-allauth for my site (in development).
Using Django==1.6.5 and django-allauth==0.17.0.
After following the documentation, I have been able to get the FB dialog. When I click OK, it hangs on localhost:8000/accounts/facebook/login/token/ for about 2 minutes, before returning with an error. The console is showing:
Error accessing FB user profile
Traceback (most recent call last):
File "/home/amir/claudius/lib/python2.7/site-packages/allauth/socialaccount/providers/facebook/views.py", line 73, in login_by_token
login = fb_complete_login(request, app, token)
File "/home/amir/claudius/lib/python2.7/site-packages/allauth/socialaccount/providers/facebook/views.py", line 26, in fb_complete_login
params={'access_token': token.token})
File "/home/amir/claudius/lib/python2.7/site-packages/requests/api.py", line 55, in get
return request('get', url, **kwargs)
File "/home/amir/claudius/lib/python2.7/site-packages/requests/api.py", line 44, in request
return session.request(method=method, url=url, **kwargs)
File "/home/amir/claudius/lib/python2.7/site-packages/requests/sessions.py", line 456, in request
resp = self.send(prep, **send_kwargs)
File "/home/amir/claudius/lib/python2.7/site-packages/requests/sessions.py", line 559, in send
r = adapter.send(request, **kwargs)
File "/home/amir/claudius/lib/python2.7/site-packages/requests/adapters.py", line 375, in send
raise ConnectionError(e, request=request)
ConnectionError: HTTPSConnectionPool(host='graph.facebook.com', port=443): Max retries exceeded with url: /me?access_token=CAAUi8RJCRZAkBAPdHFKhckONnLwjOExZCeVXpW39GZAZBLdD5rTsukQqTPi9KP6neMDxtwdhZAQvmzCS92rxR0rIZCNlzenQ2jHiyANvToy6tOWrOh5ZAYFmJFYeYvbXGNc9fuPIa0hAUqGfPzFtZB0tepoxoO7bpt01izuTYBkmS9NJChXaX9iDZAQlDTDvtLTZBvLesjFtSfwp6RusbArRzH (Caused by <class 'socket.error'>: [Errno 101] Network is unreachable)
[26/Jul/2014 06:14:36] "POST /accounts/facebook/login/token/ HTTP/1.1" 200 1205
Anyone knows the cause for this?
Well, I found out that Facebook Graph API requires IPv6 in a PHP post by Etienne Rached, of all places. Tethering through my mobile phone solved it straight away after that for the development process, and this will be a non-issue when our website is deployed.
I hope this will help someone out there.
My site is an Intranet and has hundreds of hits by day. The issue is that django crash some times and I received this trace back error:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 105, in get_response
response = middleware_method(request, callback, callback_args, callback_kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/middleware/csrf.py", line 200, in process_view
request_csrf_token = request.POST.get('csrfmiddlewaretoken', '')
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/wsgi.py", line 210, in _get_post
self._load_post_and_files()
File "/usr/local/lib/python2.7/dist-packages/django/http/__init__.py", line 284, in _load_post_and_files
self._post, self._files = QueryDict(self.raw_post_data, encoding=self._encoding), MultiValueDict()
File "/usr/local/lib/python2.7/dist-packages/django/http/__init__.py", line 248, in _get_raw_post_data
self._raw_post_data = self.read(content_length)
File "/usr/local/lib/python2.7/dist-packages/django/http/__init__.py", line 296, in read
return self._stream.read(*args, **kwargs)
IOError: request data read error
And the relevant information is that I have found this on debug data all times that program crash:
'HTTP_USER_AGENT': 'Mozilla/5.0 (BlackBerry; U; BlackBerry 9300; es) AppleWebKit/534.8+ (KHTML, like Gecko) Version/6.0.0.668 Mobile Safari/534.8+',
'HTTP_X_RIM_HTTPS': '1.1',
'HTTP_X_WAP_PROFILE': '"http://www.blackberry.net/go/mobile/profiles/uaprof/9300_edge/6.0.0.rdf"',
App crash in login form. Some ideas?
as you might think, this is no django error.
see https://groups.google.com/group/django-users/browse_thread/thread/946936f69c012d96
have the error myself (but IE ajax requests only, no file upload, just post data).
will add an complete answer if i ever find out how to fix this.
REF: IOError: request data read error