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/
Related
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!
I wrote a python program as to [Ph Num 1 <-> Twilio Server <-> Ph Num2 ]
[- Send a Message from my ph number (Num 1) containing another phone number(Num 2) to twilio server
- twilio takes the number (Num2) and calls me back (Num1) (saying as you are about to conference) and
- twilio calls the Num 2 and conferences me (Num1)
Here is my program:
from flask import Flask, request
from twilio import twiml
from twilio.rest import Client
app = Flask(__name__)
account = "AC7d2a***************"
token = "f83b27**************"
client = Client(account, token)
#app.route("/sms", methods=['GET', 'POST'])
def sms():
number=request.form["From"]
call= client.calls.create(from_="+1857*******",to=number,url="https://handler.twilio.com/twiml/EHb330731ab2c9a35fcdc620bef1b88536")
return str(resp)
if __name__=="__main__":
app.run()
The url="https://handler.twilio.com/twiml/EHb330731ab2c9a35fcdc620bef1b88536 contains
<?xml version="1.0" encoding="UTF-8"?>
<Response>
<Say>You are about to enter a conference</Say>
<Dial><Conference>number</Conference></Dial>
</Response>
i did Ngrok too and added my Ngrok link in Voice and Message URL in twilio number
I tried many changes and getting all kind of error instead of twilio number calling me after sending a message(with Ph Number (Num2) to conference)
Recent error while executing the above code is
Error:
[2017-11-13 09:46:41,570] ERROR in app: Exception on /sms [POST]
Traceback (most recent call last):
File "/home/arif/my_app/local/lib/python2.7/site-packages/flask/app.py", line 1982, in wsgi_app
response = self.full_dispatch_request()
File "/home/arif/my_app/local/lib/python2.7/site-packages/flask/app.py", line 1614, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/arif/my_app/local/lib/python2.7/site-packages/flask/app.py", line 1517, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/home/arif/my_app/local/lib/python2.7/site-packages/flask/app.py", line 1612, in full_dispatch_request
rv = self.dispatch_request()
File "/home/arif/my_app/local/lib/python2.7/site-packages/flask/app.py", line 1598, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "conf.py", line 17, in sms
return str(resp)
NameError: global name 'resp' is not defined
127.0.0.1 - - [13/Nov/2017 09:46:41] "POST /sms HTTP/1.1" 500 -
Does my program get the result what i expected ? Can anyone help me where is the issue is ?
Twilio developer evangelist here.
There are a couple of issues here. First up, you are getting an error in your webhook response. You can see the error at the bottom of your stack trace:
File "conf.py", line 17, in sms
return str(resp)
NameError: global name 'resp' is not defined
127.0.0.1 - - [13/Nov/2017 09:46:41] "POST /sms HTTP/1.1" 500 -
It says that resp is not defined.
You can see that within your method, you never define a resp but you try to return the str version of it:
def sms():
number=request.form["From"]
call= client.calls.create(from_="+1857*******",to=number,url="https://handler.twilio.com/twiml/EHb330731ab2c9a35fcdc620bef1b88536")
return str(resp)
You can just return an empty string to Twilio in this case.
def sms():
number=request.form["From"]
call= client.calls.create(from_="+1857*******",to=number,url="https://handler.twilio.com/twiml/EHb330731ab2c9a35fcdc620bef1b88536")
return ('', 204)
Once that is fixed you'll find you are only making one call, the outgoing call back to yourself. To conference with the number that you want to call, you will need to generate two calls. You say that the body of the message that you are sending will be the other number you want to dial into the conference, so this should work:
def sms():
my_number=request.form["From"]
other_number=request.form["Body"]
twilio_number="+1857*******"
conference_url="https://handler.twilio.com/twiml/EHb330731ab2c9a35fcdc620bef1b88536"
client.calls.create(from_=twilio_number,to=my_number,url=conference_url)
client.calls.create(from_=twilio_number,to=other_number,url=conference_url)
return ('', 204)
Let me know if that helps.
INFO 2015-10-09 11:07:31,718 connectionpool.py:695] Starting new HTTPS connection (1): api.sandbox.braintreegateway.com
DEBUG 2015-10-09 11:07:31,724 api_server.py:277] Handled remote_socket.Resolve in 0.0028
DEBUG 2015-10-09 11:07:31,728 api_server.py:277] Handled remote_socket.CreateSocket in 0.0009
DEBUG 2015-10-09 11:07:32,049 api_server.py:277] Handled remote_socket.Connect in 0.3168
DEBUG 2015-10-09 11:07:32,055 api_server.py:272] Exception while handling service_name: "remote_socket"
method: "GetSocketOptions"
request: "\n$d15a35d7-d299-43c1-ba76-8bf4107f8850\022\006\010\001\020\003\032\000"
request_id: "aiUMNcTaLS"
Traceback (most recent call last):
File "/home/abc/Downloads/google-appengine/google_appengine/google/appengine/tools/devappserver2/api_server.py", line 247, in _handle_POST
api_response = _execute_request(request).Encode()
File "/home/abc/Downloads/google-appengine/google_appengine/google/appengine/tools/devappserver2/api_server.py", line 186, in _execute_request
make_request()
File "/home/abc/Downloads/google-appengine/google_appengine/google/appengine/tools/devappserver2/api_server.py", line 181, in make_request
request_id)
File "/home/abc/Downloads/google-appengine/google_appengine/google/appengine/api/apiproxy_stub.py", line 131, in MakeSyncCall
method(request, response)
File "/home/abc/Downloads/google-appengine/google_appengine/google/appengine/api/remote_socket/_remote_socket_stub.py", line 56, in WrappedMethod
return method(self, *args, **kwargs)
File "/home/abc/Downloads/google-appengine/google_appengine/google/appengine/api/remote_socket/_remote_socket_stub.py", line 265, in _Dynamic_GetSocketOptions
'Attempt to get blocked socket option.')
ApplicationError: ApplicationError: 5 Attempt to get blocked socket option.
DEBUG 2015-10-09 11:07:32,056 api_server.py:277] Handled remote_socket.GetSocketOptions in 0.0014
INFO 2015-10-09 11:07:32,058 views.py:570] handle_exception
INFO 2015-10-09 21:28:17,317 views.py:559] Traceback (most recent call last):
File "/home/abc/Downloads/google-appengine/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 570, in dispatch
return method(*args, **kwargs)
File "/home/abc/projects/src/views.py", line 806, in get
self._callHandlingMethod(url, self.getRegexps)
File "/home/abc/projects/src/views.py", line 883, in _callHandlingMethod
function(*matched.groups())
File "/home/abc/projects/src/views.py", line 2992, in buy_get
"client_token": braintree.ClientToken.generate(),
File "/home/abc/projects/src/lib/braintree/client_token.py", line 25, in generate
return gateway.generate(params)
File "/home/abc/projects/src/lib/braintree/client_token_gateway.py", line 17, in generate
response = self.config.http().post("/client_token", params)
File "/home/abc/projects/src/lib/braintree/util/http.py", line 49, in post
return self.__http_do("POST", path, params)
File "/home/abc/projects/src/lib/braintree/util/http.py", line 66, in __http_do
status, response_body = http_strategy.http_do(http_verb, full_path, self.__headers(), request_body)
File "/home/abc/projects/src/lib/braintree/util/http.py", line 87, in http_do
timeout=self.config.timeout
File "/home/abc/projects/src/lib/requests/api.py", line 92, in post
return request('post', url, data=data, **kwargs)
File "/home/abc/projects/src/lib/requests/api.py", line 48, in request
return session.request(method=method, url=url, **kwargs)
File "/home/abc/projects/src/lib/requests/sessions.py", line 451, in request
resp = self.send(prep, **send_kwargs)
File "/home/abc/projects/src/lib/requests/sessions.py", line 557, in send
r = adapter.send(request, **kwargs)
File "/home/abc/projects/src/lib/requests/adapters.py", line 407, in send
raise ConnectionError(err, request=request)
ConnectionError: ('Connection aborted.', error(13, 'Permission denied'))
This seemed to be a https issue. I have tried different approaches
a) https://github.com/agfor/braintree-python-appengine . Gave me same error
b) I thought this could be the error from this issue - https://urllib3.readthedocs.org/en/latest/security.html#openssl-pyopenssl
But on updating required libraries , I get stuck at OpenSSL.crypto failed import.
Help anyone!
It looks like braintree is trying to use a socket option unsupported by GAE, you can see a list of supported options here https://cloud.google.com/appengine/docs/python/sockets/ which also states that attempting to get an unsupported option will raise an error
Braintree Version - 3.20.0
Requests version - 2.7.0
With the help of my friend , I used the following hack -
in braintree/util/http.py in the method - __http_do
from google.appengine.api import urlfetch
.....
.....
try:
if http_verb in ["POST", "PUT"]:
result = urlfetch.fetch(url=full_path,
payload=request_body,
method=urlfetch.POST,
headers=self.__headers())
logging.debug('result: %r' % result)
status = result.status_code
response_body = result.content
logging.debug(result.content)
else:
status, response_body = http_strategy.http_do(http_verb, full_path, self.__headers(), request_body)
except Exception as e:
.....
.....
Using this hack, I was able to get things working. Hope this helps anybody coming across the same issue.
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