ConnectionAbortedError in Django - python

Whenever this view is executed my server showed up with some error which I don't know why! the view which I was executing is
#api_view(['POST'])
def Signin(request):
if request.method == 'POST':
username = request.POST.get('username')
passw = request.POST.get('password')
email = request.POST.get('email')
fullname = request.POST.get('fullname')
college = request.POST.get('college_name')
city = request.POST.get('city')
country = request.POST.get('country')
User.objects.create_user(
username=username, password=passw, email=email)
Userinfo.objects.create(
user_name=username, full_name=fullname, user_email=email, college_name=college, city=city, country=country , varified_user=False)
return Response({'status': 'created'})
And what i know after checking my database is my code is executing till user_name=username, full_name=fullname, user_email=email, college_name=college, city=city, country=country , varified_user=False) because I can see the data which I was inserting, now i don't know what error can cause by return Response({'status': 'created'}). The message in my terminal is
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
September 29, 2020 - 21:19:18
Django version 3.1, using settings 'backend.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
[29/Sep/2020 21:19:31] "POST /api/usercheck/ HTTP/1.1" 200 18
[29/Sep/2020 21:19:34] "POST /api/usercheck/ HTTP/1.1" 200 18
[29/Sep/2020 21:19:35] "POST /api/usercheck/ HTTP/1.1" 200 21
[29/Sep/2020 21:19:58] "POST /signin/ HTTP/1.1" 200 3318
----------------------------------------
Exception happened during processing of request from ('127.0.0.1', 65332)
Traceback (most recent call last):
File "C:\Python38\lib\socketserver.py", line 650, in process_request_thread
self.finish_request(request, client_address)
File "C:\Python38\lib\socketserver.py", line 360, in finish_request
self.RequestHandlerClass(request, client_address, self)
File "C:\Python38\lib\socketserver.py", line 720, in __init__
self.handle()
File "E:\Project_Bookbhandar\env\lib\site-packages\django\core\servers\basehttp.py", line 174, in handle
self.handle_one_request()
File "E:\Project_Bookbhandar\env\lib\site-packages\django\core\servers\basehttp.py", line 182, in handle_one_request
self.raw_requestline = self.rfile.readline(65537)
File "C:\Python38\lib\socket.py", line 669, in readinto
return self._sock.recv_into(b)
ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine
----------------------------------------
Can anyone help with this??

You will want to be using HttpResponse or JsonResponse.

Related

Django: ConnectionResetError: [Errno 54]

This logs, quite repeatedly, every time my app loads on my computer.
Exception happened during processing of request from ('127.0.0.1', 53597)
Traceback (most recent call last):
File "/usr/local/Cellar/python#3.8/3.8.6/Frameworks/Python.framework/Versions/3.8/lib/python3.8/socketserver.py", line 650, in process_request_thread
self.finish_request(request, client_address)
File "/usr/local/Cellar/python#3.8/3.8.6/Frameworks/Python.framework/Versions/3.8/lib/python3.8/socketserver.py", line 360, in finish_request
self.RequestHandlerClass(request, client_address, self)
File "/usr/local/Cellar/python#3.8/3.8.6/Frameworks/Python.framework/Versions/3.8/lib/python3.8/socketserver.py", line 720, in __init__
self.handle()
File "/usr/local/lib/python3.8/site-packages/django/core/servers/basehttp.py", line 174, in handle
self.handle_one_request()
File "/usr/local/lib/python3.8/site-packages/django/core/servers/basehttp.py", line 182, in handle_one_request
self.raw_requestline = self.rfile.readline(65537)
File "/usr/local/Cellar/python#3.8/3.8.6/Frameworks/Python.framework/Versions/3.8/lib/python3.8/socket.py", line 669, in readinto
return self._sock.recv_into(b)
ConnectionResetError: [Errno 54] Connection reset by peer
I realize that this has been posted on extensively over the years, but it seems to me that the consensus on the answer is that it could be one of a few things:
(a) Using a .png instead of an .ico in a favicon
(b) Misusing {% static %}
(c) Misusing event.preventDefault()
Unfortunately for me, none of those things have happened in the last few weeks in my teams commits. So I ask, are there other solutions I may be missing? This is a result of me recently merging with a master development branch.
As I mentioned over here, I had this issue show up while debugging POST DRF api endpoints.
The solution was to add SITE_URL to settings with my localhost and dev server port set, i.e.
SITE_URL = "http://localhost:4000"
Commonly this error is associated with a missing favicon file. But I'm not sure if this change gets around that issue or is due to something else.
For added context, I hit this error while using Pycharm's http request scratch file to debug and validate DRF (django rest framework) endpoints.
The format I was using was:
### Send POST request with json body
POST http://localhost:4000/api/admin/add_node/
Content-Type: application/json
Authorization: Basic admin password
{
"name": "node01",
"username": "username",
"password": "password"
}

flask-socket.io: frequent time-outs

I have a flask-socket.io application that is pretty standard:
server: eventlet
I start the app using: socketio.run(app, host='0.0.0.0')
Frequently but not always I have some kind of timeout:
Traceback (most recent call last):
File "/projects/ici_chat_prototype01/env/lib/python3.5/site-packages/eventlet/wsgi.py", line 507, in handle_one_response
result = self.application(self.environ, start_response)
File "/projects/ici_chat_prototype01/env/lib/python3.5/site-packages/flask/app.py", line 1997, in __call__
return self.wsgi_app(environ, start_response)
File "/projects/ici_chat_prototype01/env/lib/python3.5/site-packages/flask_socketio/__init__.py", line 42, in __call__
start_response)
File "/projects/ici_chat_prototype01/env/lib/python3.5/site-packages/engineio/middleware.py", line 47, in __call__
return self.engineio_app.handle_request(environ, start_response)
File "/projects/ici_chat_prototype01/env/lib/python3.5/site-packages/socketio/server.py", line 360, in handle_request
return self.eio.handle_request(environ, start_response)
File "/projects/ici_chat_prototype01/env/lib/python3.5/site-packages/engineio/server.py", line 267, in handle_request
environ, start_response)
File "/projects/ici_chat_prototype01/env/lib/python3.5/site-packages/engineio/socket.py", line 89, in handle_get_request
start_response)
File "/projects/ici_chat_prototype01/env/lib/python3.5/site-packages/engineio/socket.py", line 130, in _upgrade_websocket
return ws(environ, start_response)
File "/projects/ici_chat_prototype01/env/lib/python3.5/site-packages/engineio/async_eventlet.py", line 19, in __call__
return super(WebSocketWSGI, self).__call__(environ, start_response)
File "/projects/ici_chat_prototype01/env/lib/python3.5/site-packages/eventlet/websocket.py", line 127, in __call__
self.handler(ws)
File "/projects/ici_chat_prototype01/env/lib/python3.5/site-packages/engineio/socket.py", line 155, in _websocket_handler
pkt = ws.wait()
File "/projects/ici_chat_prototype01/env/lib/python3.5/site-packages/eventlet/websocket.py", line 633, in wait
for i in self.iterator:
File "/projects/ici_chat_prototype01/env/lib/python3.5/site-packages/eventlet/websocket.py", line 503, in _iter_frames
message = self._recv_frame(message=fragmented_message)
File "/projects/ici_chat_prototype01/env/lib/python3.5/site-packages/eventlet/websocket.py", line 526, in _recv_frame
header = recv(2)
File "/projects/ici_chat_prototype01/env/lib/python3.5/site-packages/eventlet/websocket.py", line 442, in _get_bytes
d = self.socket.recv(numbytes - len(data))
File "/projects/ici_chat_prototype01/env/lib/python3.5/site-packages/eventlet/greenio/base.py", line 360, in recv
return self._recv_loop(self.fd.recv, b'', bufsize, flags)
File "/projects/ici_chat_prototype01/env/lib/python3.5/site-packages/eventlet/greenio/base.py", line 354, in _recv_loop
self._read_trampoline()
File "/projects/ici_chat_prototype01/env/lib/python3.5/site-packages/eventlet/greenio/base.py", line 325, in _read_trampoline
timeout_exc=socket_timeout('timed out'))
File "/projects/ici_chat_prototype01/env/lib/python3.5/site-packages/eventlet/greenio/base.py", line 207, in _trampoline
mark_as_closed=self._mark_as_closed)
File "/projects/ici_chat_prototype01/env/lib/python3.5/site-packages/eventlet/hubs/__init__.py", line 163, in trampoline
return hub.switch()
File "/projects/ici_chat_prototype01/env/lib/python3.5/site-packages/eventlet/hubs/hub.py", line 295, in switch
return self.greenlet.switch()
socket.timeout: timed out
I am not able to interpret this traceback. Can somebody with some experience in flask-socket.io help?
I am not posting any code because I would not know where to start. All files in the traceback are from the installed modules.
EDIT:
I got some more info on the socket.io requests. After the above Exception the following requests are logged:
127.0.0.1 - - [04/Jan/2018 10:10:51] "GET /socket.io/?EIO=3&transport=websocket&sid=f93955151a3a4576b2e96427cc27121e HTTP/1.1" 500 0 60.061493
127.0.0.1 - - [04/Jan/2018 10:10:51] "GET /socket.io/?EIO=3&transport=polling&t=1515056991349-3&sid=f93955151a3a4576b2e96427cc27121e HTTP/1.1" 400 218 60.001593
127.0.0.1 - - [04/Jan/2018 10:10:52] "GET /socket.io/?EIO=3&transport=polling&t=1515057052758-4 HTTP/1.1" 200 381 0.000875
(12472) accepted ('127.0.0.1', 39520)
127.0.0.1 - - [04/Jan/2018 10:10:52] "POST /socket.io/?EIO=3&transport=polling&t=1515057052767-5&sid=10663b1e21e6492b81b5455ebc805408 HTTP/1.1" 200 219 0.001145
You may use socketio.run(app, host='0.0.0.0', port=5000, debug=True) if you want to switch in debug mode.
Then you may take a look on the socket.io official documentation website, most especialy on client-api and server-api.
Beause in the httpsserver-options part of the server-api (for javascript), you can see that there is some options when running the server, like:
pingInterval: 10000,
pingTimeout: 5000,
I expect that those arguments could be re-used as kwargs when you run you server with socketio.run(app, host='0.0.0.0', port=5000, debug=True,pingInterval = 10000, pingTimeout= 5000)
And in the flask-socketio documentation, in the "Error Handling" part,there is nice tips to to deal with exceptions
You may add something like
#socketio.on_error_default # handles all namespaces without an explicit error handler
def default_error_handler(e):
pass
Another tips could be to adapt this previous error_handler for timeout issue and re-run the server when this event will be triggered.
You may also note that:
The message and data arguments of the current request can also be inspected with the request.event variable, which is useful for error logging and debugging outside the event handler
You may also use this following code to handle the final socket.timeout: timed out error :
try:
socketio.run(app,...
except socket.error as socketerror:
print("Error: ", socketerror)
To complement a-stefani's answer. Proper way to change pingInterval and pingTimeout in flask-socketio is with:
from flask_socketio import SocketIO
socketio = SocketIO(app,ping_timeout=5,ping_interval=10)
This doesn't work: socketio.run(app, host='0.0.0.0', port=5000, debug=True,pingInterval = 10000, pingTimeout= 5000)

Django server is hanging in request handler

I do a poll once a second, and after some idle time (10min - 1h) the server stops responding. If I press Ctrl-C handler is terminated and the server is back alive. Error after pressing Ctrl-C (while trying to connect with a new client):
...same messages repeat...
[22/Sep/2016 21:54:27] "GET /ajax/?id=STATUS_POLL&_=1474566714286 HTTP/1.1" 200 0
[2016-09-22 21:54:28,217: DEBUG/MainProcess] NONE
[22/Sep/2016 21:54:28] "GET /ajax/?id=STATUS_POLL&_=1474566714287 HTTP/1.1" 200 0
[2016-09-23 09:33:14,657: INFO/MainProcess] Starting view
[23/Sep/2016 09:36:34] "GET / HTTP/1.1" 200 18970
Traceback (most recent call last):
File "c:\python27\lib\wsgiref\handlers.py", line 86, in run
self.finish_response()
File "c:\python27\lib\wsgiref\handlers.py", line 128, in finish_response
self.write(data)
File "c:\python27\lib\wsgiref\handlers.py", line 212, in write
self.send_headers()
File "c:\python27\lib\wsgiref\handlers.py", line 270, in send_headers
self.send_preamble()
File "c:\python27\lib\wsgiref\handlers.py", line 194, in send_preamble
'Date: %s\r\n' % format_date_time(time.time())
File "c:\python27\lib\socket.py", line 328, in write
self.flush()
File "c:\python27\lib\socket.py", line 307, in flush
self._sock.sendall(view[write_offset:write_offset+buffer_size])
error: [Errno 10053] An established connection was aborted by the software in your host machine
[23/Sep/2016 09:36:34] "GET / HTTP/1.1" 500 59
Request handler:
class CTrackerView(TemplateView):
__process = ProcessWrapper()
#staticmethod
def ajax_handler(request):
if request.GET.get('id', "") == "STATUS_POLL":
if CTrackerView.__process.is_alive(no_log=False):
return HttpResponse("UPDATING")
else:
return HttpResponse("")
process_wrapper.py:
class ProcessWrapper:
def is_alive(self, no_log=False):
if (not hasattr(self, "_process")) or not self._process:
if not no_log:
log("NONE", DEBUG)
return False
As you can see from the last code fragment, it just checks the variable is not defined (process is deleted) and return False during all the idle time. (Message "NONE" in log). The problem is difficult to reproduce.

Flask: Server becomes unresponsive after some time

I use a flask server to serve static files from a server but once in a while the server becomes completely unresponsive, downloading a file keeps loading but never downloads. When I opened up the terminal, I found some weird requests, I hit CTRL + C and the server immediately becomes responsive again and downloads continue. This happens every so often and I have no idea what's causing this and how to prevent it from freezing my flask server, is this someone trying to hack?
user#server:~/worker# python server.py
* Running on http://0.0.0.0:80/
93.134.13.318 - - [03/Sep/2014 02:07:18] code 400, message Bad request syntax ('\x00')
93.134.13.318 - - [03/Sep/2014 02:07:18] "" 400 -
93.134.13.318 - - [03/Sep/2014 02:07:19] "GET http://httpheader.net HTTP/1.1" 404 -
93.134.13.318 - - [03/Sep/2014 02:07:40] code 400, message Bad request syntax ('\x04\x01\x00P\xc6\xce\x0eu0\x00')
93.174.93.218 - - [03/Sep/2014 02:07:40] "P��u0" 400 -
^C----------------------------------------
Exception happened during processing of request from ('93.174.93.218 ', 45082)
Traceback (most recent call last):
File "/usr/lib/python2.7/SocketServer.py", line 284, in _handle_request_noblock
self.process_request(request, client_address)
File "/usr/lib/python2.7/SocketServer.py", line 310, in process_request
self.finish_request(request, client_address)
File "/usr/lib/python2.7/SocketServer.py", line 323, in finish_request
self.RequestHandlerClass(request, client_address, self)
File "/usr/lib/python2.7/SocketServer.py", line 638, in __init__
self.handle()
File "/usr/local/lib/python2.7/dist-packages/werkzeug/serving.py", line 200, in handle
rv = BaseHTTPRequestHandler.handle(self)
File "/usr/lib/python2.7/BaseHTTPServer.py", line 340, in handle
self.handle_one_request()
File "/usr/local/lib/python2.7/dist-packages/werkzeug/serving.py", line 231, in handle_one_request
self.raw_requestline = self.rfile.readline()
File "/usr/lib/python2.7/socket.py", line 447, in readline
data = self._sock.recv(self._rbufsize)
KeyboardInterrupt
----------------------------------------
42.36.63.90 - - [03/Sep/2014 03:21:20] "GET / HTTP/1.1" 404 -
63.63.193.195 - - [03/Sep/2014 03:21:20] "GET / HTTP/1.1" 404 -
I had the same issue. It's common in django/flask apps to hang when running as python server.py, because this in not an optimal environment for them. Only use it for testing purpose. When you're done with it and want to release, you should put it behind a wsgi/uwsgi + apache/nginx and your problem will go away.
http://flask.pocoo.org/docs/0.10/deploying/uwsgi/
http://flask.pocoo.org/docs/1.0/deploying/uwsgi/

Broken pipe during stream

I have a project with Django I am working on where I want to stream some mp3 files.
I have this same issue:
Streaming mp3 files with django, read from a page with <audio>
Let me explain: I want stream an ogg with Django, and with an <audio> tag in my html page
I have a url like domain.tld/song/show/X/, where X is the id of my song.
I can stream with VLC (directly with the file path), I can stream during test, (I write what I receive and read it with VLC).
But when I open my browser and load my home page domain.tld where I have and <\audio\> balise with url domain.tld/song/show/1/, I get a big broken pipe, as if my client closed the connection.
I read on others post that some problems was resolved when they put server in production. So I push my app on server, use apache, with the django.wgsi like on djangoproject.com.
I am running python 2.7.3 on Debian 7 with Django version 1.5.
there my code:
Song/views.py
def playAudioFile(request, pk):
f = get_stream_song(pk)# return a pipe from pipes.Template
l = f.read() # the file is an ogg get by pydub.com
f.close()
size_read = 550000
sr = size_read
while sr == size_read:
print "rep"
r = l[:size_read]
l=l[size_read:]
sr = len(r)
yield r
time.sleep(0.1)
#url : ~/song/show/X/
##login_required
def show_song(request, pk):
return StreamingHttpResponse(playAudioFile(request, pk), mimetype='audio/ogg',)
In my HTML, I just have that:
<audio controls height="100" width="100" preload="auto">
<source src="/.../song/show/1/" type="audio/ogg">
<embed height="50" width="100" src="/.../song/show/1/">
</audio>
The error looks like:
Traceback (most recent call last):
File "/usr/lib/python2.7/wsgiref/handlers.py", line 86, in run
self.finish_response()
File "/usr/lib/python2.7/wsgiref/handlers.py", line 127, in finish_response
self.write(data)
File "/usr/lib/python2.7/wsgiref/handlers.py", line 215, in write
self._write(data)
File "/usr/lib/python2.7/socket.py", line 324, in write
self.flush()
File "/usr/lib/python2.7/socket.py", line 303, in flush
self._sock.sendall(view[write_offset:write_offset+buffer_size])
error: [Errno 104] Connection reset by peer
----------------------------------------
Exception happened during processing of request from ('127.0.0.1', 46392)
Traceback (most recent call last):
File "/usr/lib/python2.7/SocketServer.py", line 593, in process_request_thread
self.finish_request(request, client_address)
File "/usr/lib/python2.7/SocketServer.py", line 334, in finish_request
self.RequestHandlerClass(request, client_address, self)
File "/home/lumy/SPhoque/SonoPhoque/SoPhoque/local/lib/python2.7/site-packages/django/core/servers/basehttp.py", line 150, in __init__
super(WSGIRequestHandler, self).__init__(*args, **kwargs)
File "/usr/lib/python2.7/SocketServer.py", line 651, in __init__
self.finish()
File "/usr/lib/python2.7/SocketServer.py", line 704, in finish
self.wfile.flush()
File "/usr/lib/python2.7/socket.py", line 303, in flush
self._sock.sendall(view[write_offset:write_offset+buffer_size])
error: [Errno 32] Broken pipe
I got this twice each time I try to stream.
Edit 15h 29/05:
I did what rahan suggested:
Looking at Firebug and Firefox debugger:
The client does:
GET 1 200 OK localhost:8000 537.1KB 4.71s
Headers
Response Headersview source
Date Wed, 29 May 2013 13:08:54 GMT
Server WSGIServer/0.1 Python/2.7.3
Content-Type audio/ogg
Request Headersview source
Host localhost:8000
User-Agent Mozilla/5.0 (X11; Linux x86_64; rv:10.0.12) Gecko/20100101 Firefox/10.0.12 Iceweasel/10.0.12
Accept audio/webm,audio/ogg,audio/wav,audio/*;q=0.9,application/ogg;q=0.7,video/*;q=0.6,*/*;q=0.5
Accept-Language en-us,en;q=0.5
Connection keep-alive
Range bytes=0-
Referer http://localhost:8000/
and details say that the total size for all documents is 1 MB (526 KB from cache)
May be I am crossing your existing solution, i have a suggestion, for mp3 streaming use nginx/apache server, these days there is solution known as sendfile, for example in your case on django view
def send_file_header(server_type):
header = "X-Sendfile" if server_type == "apache" else "X-Accel-Redirect"
return header
#login_required
def show_song(request, pk):
res = HttpResponse()
path = "/path/to/secret/x.mp3"
response[send_file_header('nginx')] = path
response['Content-Type']= "application/octet-stream"
response['Content-Disposition'] = "attachment; filename=\"x.mp3\""
return response

Categories