Error "concurrent.futures._base.CancelledError" on server after connection Client - websocket

I can not solve the problem with the error after connecting the client to the server. Here is the server code for Python 3.7.7:
#!/usr/bin/env python3
# WS server example
import asyncio
import websockets
#======================================================================
#Register
#======================================================================
async def Register(websocket):
remote_ip = websocket.remote_address[0] #Get client IP
print ("IP: " + remote_ip)
message="Hi. Your IP: " +remote_ip
await websocket.send(message) #Say client IP
print("==> " + str(message))
#======================================================================
#Handler
#======================================================================
async def Handler(websocket, path):
print("Client connect!")
await Register(websocket)
#try:
async for message in websocket:
print("<== " + str(message))
await websocket.send(message)
print("==> " + str(message))
#except Exception as E:
#print(str(E))
#finally:
#await asyncio.sleep(2)
#======================================================================
#MAIN
#======================================================================
print("Starting!")
start_server = websockets.serve(Handler, "0.0.0.0", 8012)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
After connecting, after 40 seconds from the moment of connection, an error is returned, and it does not matter if the client exchanged data with the server or not.
Error in connection handler
Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/websockets/protocol.py", line 827, in transfer_data
message = await self.read_message()
File "/usr/local/lib/python3.7/site-packages/websockets/protocol.py", line 895, in read_message
frame = await self.read_data_frame(max_size=self.max_size)
File "/usr/local/lib/python3.7/site-packages/websockets/protocol.py", line 971, in read_data_frame
frame = await self.read_frame(max_size)
File "/usr/local/lib/python3.7/site-packages/websockets/protocol.py", line 1051, in read_frame
extensions=self.extensions,
File "/usr/local/lib/python3.7/site-packages/websockets/framing.py", line 105, in read
data = await reader(2)
File "/usr/local/lib/python3.7/asyncio/streams.py", line 679, in readexactly
await self._wait_for_data('readexactly')
File "/usr/local/lib/python3.7/asyncio/streams.py", line 473, in _wait_for_data
await self._waiter
concurrent.futures._base.CancelledError
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/websockets/server.py", line 191, in handler
await self.ws_handler(self, path)
File "StartWB3.py", line 26, in Handler
async for message in websocket:
File "/usr/local/lib/python3.7/site-packages/websockets/protocol.py", line 439, in __aiter__
yield await self.recv()
File "/usr/local/lib/python3.7/site-packages/websockets/protocol.py", line 509, in recv
await self.ensure_open()
File "/usr/local/lib/python3.7/site-packages/websockets/protocol.py", line 812, in ensure_open
raise self.connection_closed_exc()
websockets.exceptions.ConnectionClosedError: code = 1006 (connection closed abnormally [internal]), no reason
What could be the problem?
Thanks in advance for the answers.

The reason is that the underlying socket has been closed and websockets is trying to cancel the task running Handler(). You can catch the error using a try/except block.

Empirically, it turned out that the problem is not in the WebSocket package for Python, but in C # WebSocket4Net: Why is WebSocket4Net closing the connection with 1011 error code
Started using the WebSocketSharp library and the problem disappeared.

Related

StatusCode.UNIMPLEMENTED when making Vertex AI API call

I have a simple Python app that invokes a Vertex AI API that fails when it runs and I can't understand why. The application is as follows:
from google.cloud import aiplatform_v1
def sample_list_datasets():
client = aiplatform_v1.DatasetServiceClient()
request = aiplatform_v1.ListDatasetsRequest(
parent="projects/MYPROJECT/locations/us-central1",
)
page_result = client.list_datasets(request=request)
for response in page_result:
print(response)
sample_list_datasets()
when run, it fails with:
E0126 03:52:04.146970105 22462 hpack_parser.cc:1218] Error parsing metadata: error=invalid value key=content-type value=text/html; charset=UTF-8
Traceback (most recent call last):
File "/home/kolban/projects/vertex-ai/datasets/env/lib/python3.7/site-packages/google/api_core/grpc_helpers.py", line 72, in error_remapped_callable
return callable_(*args, **kwargs)
File "/home/kolban/projects/vertex-ai/datasets/env/lib/python3.7/site-packages/grpc/_channel.py", line 946, in __call__
return _end_unary_response_blocking(state, call, False, None)
File "/home/kolban/projects/vertex-ai/datasets/env/lib/python3.7/site-packages/grpc/_channel.py", line 849, in _end_unary_response_blocking
raise _InactiveRpcError(state)
grpc._channel._InactiveRpcError: <_InactiveRpcError of RPC that terminated with:
status = StatusCode.UNIMPLEMENTED
details = "Received http2 header with status: 404"
debug_error_string = "UNKNOWN:Error received from peer ipv4:108.177.120.95:443 {created_time:"2023-01-26T03:52:04.147076255+00:00", grpc_status:12, grpc_message:"Received http2 header with status: 404"}"
>
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "run.py", line 25, in <module>
sample_list_datasets()
File "run.py", line 19, in sample_list_datasets
page_result = client.list_datasets(request=request)
File "/home/kolban/projects/vertex-ai/datasets/env/lib/python3.7/site-packages/google/cloud/aiplatform_v1/services/dataset_service/client.py", line 1007, in list_datasets
metadata=metadata,
File "/home/kolban/projects/vertex-ai/datasets/env/lib/python3.7/site-packages/google/api_core/gapic_v1/method.py", line 113, in __call__
return wrapped_func(*args, **kwargs)
File "/home/kolban/projects/vertex-ai/datasets/env/lib/python3.7/site-packages/google/api_core/grpc_helpers.py", line 74, in error_remapped_callable
raise exceptions.from_grpc_error(exc) from exc
google.api_core.exceptions.MethodNotImplemented: 501 Received http2 header with status: 404
What might I be doing wrong?
Changing the code to the following caused it to work:
from google.cloud import aiplatform_v1
from google.api_core.client_options import ClientOptions
def sample_list_datasets():
service_base_path='aiplatform.googleapis.com'
region='us-central1'
client_options = ClientOptions(api_endpoint=f"{region}-{service_base_path}")
client = aiplatform_v1.DatasetServiceClient(client_options=client_options)
request = aiplatform_v1.ListDatasetsRequest(
parent="projects/MYPROJECT/locations/us-central1",
)
# Make the request
page_result = client.list_datasets(request=request)
# Handle the response
for response in page_result:
print(response)
sample_list_datasets()
The resolution was hinted at in the documentation for the API request found here. At that article there is a code sample and in the code sample there are some comments and in the comments the following is written:
It may require specifying regional endpoints when creating the service
client as shown in:
https://googleapis.dev/python/google-api-core/latest/client_options.html
And this was the core clue. When we make Vertex AI calls we must specify where the request is to be sent. We do this by setting the api_endpoint option to a URL of the form [REGION]-aiplatform.googleapis.com.

How do I fix this error with kick command

I wanted to make an kick command but i ran into this error but i couldnt find out how to fix it.
I tried giving permissions to the bot. And giving permissions to me but it all didnt work.
This is my code:
#bot.command(name='kick', aliases=['Kick'])
#commands.has_permissions(kick_members=True)
async def kick(ctx, member: discord.Member):
await ctx.send('What is the reason?')
msg = await bot.wait_for('message')
reason = msg.content
description = f'''
**Member:** = {member}
**Responsible moderator:** {ctx.author.mention}
**Reason:** {reason}
'''
embed = discord.Embed(title='Kick', description=description)
await ctx.send(content=None, embed=embed)
await member.kick(reason=reason)
This is the error:
Traceback (most recent call last):
File "C:\Users\Guido\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 83, in wrapped
ret = await coro(*args, **kwargs)
File "c:/Users/Guido/Desktop/yeet/overig/coding/discord bots/self coded/oden/code/Oden.py", line 80, in kick
await member.kick(reason=reason)
File "C:\Users\Guido\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\member.py", line 489, in kick
await self.guild.kick(self, reason=reason)
File "C:\Users\Guido\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\guild.py", line 1627, in kick
await self._state.http.kick(user.id, self.id, reason=reason)
File "C:\Users\Guido\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\http.py", line 221, in request
raise Forbidden(r, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Guido\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\bot.py", line 892, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Guido\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 797, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\Guido\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 92, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions```
It looks like the error is that the bot does not have the permission to kick a user in that server. Make sure that the bot has the Kick Members permission. The bot having permission is the only thing that matters from the API's perspective

How to call async function inside a celery task

I have a web chat using websockets (AsyncWebsocketConsumer, django-channels). I'm using celery to parse a request but it halt with no debbugable (for me) errors every time I try to send the response back to the consumer.
This attempt give me the next error:
#shared_task
def execute(command, parameter, room_group_name):
if command == '/stock':
loop = asyncio.get_event_loop()
loop.run_until_complete(sendData(stock(parameter), "BOT", room_group_name))
return True
loop = asyncio.get_event_loop()
loop.run_until_complete(sendData("I do not understand that parameter", "BOT", room_group_name))
return True
from channels.layers import get_channel_layer
async def sendData(message, from_, room_group_name):
channel_layer = get_channel_layer()
import datetime
currentDT = datetime.datetime.now()
datetime = currentDT.strftime("%Y-%m-%d %H:%M:%S")
await channel_layer.group_send(
room_group_name,
{
'type': 'chat_message',
'username': from_,
'datetime': datetime,
'message': message
}
)
await asyncio.sleep(5)
Error:
[2019-05-12 18:01:15,491: ERROR/ForkPoolWorker-1] Task chat.tasks.execute[8a69afca-8173-46d0-84bc-4ee5ce7782ca] raised unexpected: OSError(9, 'Bad file descriptor')
Traceback (most recent call last):
File "/Users/juan/Documents/manu/dev/python_challenge/venv/lib/python3.6/site-packages/celery/app/trace.py", line 385, in trace_task
R = retval = fun(*args, **kwargs)
File "/Users/juan/Documents/manu/dev/python_challenge/venv/lib/python3.6/site-packages/celery/app/trace.py", line 648, in __protected_call__
return self.run(*args, **kwargs)
File "/Users/juan/Documents/manu/dev/python_challenge/chat/tasks.py", line 14, in execute
loop.run_until_complete(sendData(stock(parameter), "BOT", room_group_name))
File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/asyncio/base_events.py", line 455, in run_until_complete
self.run_forever()
File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/asyncio/base_events.py", line 422, in run_forever
self._run_once()
File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/asyncio/base_events.py", line 1396, in _run_once
event_list = self._selector.select(timeout)
File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/selectors.py", line 577, in select
kev_list = self._kqueue.control(None, max_ev, timeout)
OSError: [Errno 9] Bad file descriptor
OSError: [Errno 9] Bad file descriptor, but I cannot find where it is coming from.
celery==4.3.0

Django : error: [Errno 10053] An established connection was aborted by the software in your host machine

I got error when i perform ajax request. Without authentication lines user = authenticate(username = user_username, password = user_password) in the views.py, success function is called. And if i add, error function is called with Errno 10053.
I am using MySql in Wamp. Why it is happening ?
views.py
class LoginVerify(View):
print('login')
def post(self,request,*args,**kwargs):
if request.is_ajax():
print("post called")
user_email = request.POST.get('email',False)
user_password = request.POST.get('pswd',False)
print(user_email)
try:
user_username = User.objects.get(email=user_email).username
user = authenticate(username = user_username, password = user_password)
except:
print("error occured")
return HttpResponse("response form server")
def get(self, request,*args,**kwargs):
print("get method")
return render(request,'feeds/feeds_home.html')
ajax request:
$(document).ready(function(){
$("#submit").on("click",function(){
var $email = $("#signin-email").val();
var $pswd = $("#signin-password").val();
alert($pswd);
$.ajax({
url : '{% url "feeds:login_view" %}',
type: "POST",
data: {csrfmiddlewaretoken :"{{ csrf_token }}", pswd : $pswd, email: $email},
success: function(data){
location.reload();
},
error: function(){
alert("fails");
}
});
});
Tracebrack
post called
vivek.ananthan.m.s#gmail.com
[19/Apr/2015 11:10:22] "POST / HTTP/1.1" 200 12
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 127, in finish_response
self.write(data)
File "C:\Python27\lib\wsgiref\handlers.py", line 210, in write
self.send_headers()
File "C:\Python27\lib\wsgiref\handlers.py", line 268, in send_headers
self.send_preamble()
File "C:\Python27\lib\wsgiref\handlers.py", line 192, in send_preamble
'Date: %s\r\n' % format_date_time(time.time())
File "C:\Python27\lib\socket.py", line 324, in write
self.flush()
File "C:\Python27\lib\socket.py", line 303, 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
Traceback (most recent call last):
File "C:\Python27\lib\SocketServer.py", line 582, in process_request_thread
self.finish_request(request, client_address)
File "C:\Python27\lib\SocketServer.py", line 323, in finish_request
self.RequestHandlerClass(request, client_address, self)
File "C:\Python27\lib\site-packages\django-1.7-py2.7.egg\django\core\servers\basehttp.py", line 129, in __init__
super(WSGIRequestHandler, self).__init__(*args, **kwargs)
File "C:\Python27\lib\SocketServer.py", line 640, in __init__
self.finish()
File "C:\Python27\lib\SocketServer.py", line 693, in finish
self.wfile.flush()
File "C:\Python27\lib\socket.py", line 303, 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
----------------------------------------
Exception happened during processing of request from ('127.0.0.1', 52490)
Please explain where i made the mistake and why it is happening.
Thanks in advance !!
Reference: https://stackoverflow.com/a/17854758/3940406
From the Windows Sockets Error Codes list:
WSAECONNABORTED 10053 Software caused connection abort. An established
connection was aborted by the software in your host computer, possibly
due to a data transmission time-out or protocol error.
There was a timeout or other network-level error. This is your operating system closing the socket, nothing to do with Python, django or Flask, really.
It could be the remote browser stopped responding, the network connection died, or a firewall closed the connection because it was open too long, or any other number of reasons.
I came by the question when I was trying to research a problem with regards to running a mysql code using the pymysql as the python sql client. I happen to have this same issue. Renaming the config setting for mysql and then restarting your system or running mysql server. Works to fix this issue

werkzeug server failed to handle request

I'm trying to run this gevent server
from gevent import pywsgi
from Index import application
import paste.urlparser
import os
# http server: serves up static files
print "static files",os.path.dirname(__file__)
print "serving on localhost:8000"
http_server = pywsgi.WSGIServer(
('', 8000),
paste.urlparser.StaticURLParser(os.path.dirname(__file__)))
print 'Serving on https://127.0.0.1:4000'
server = pywsgi.WSGIServer(('0.0.0.0', 4000), application,spawn=None)
# Start the server greenlets
http_server.start()
# to start the server asynchronously, call server.start()
# we use blocking serve_forever() here because we have no other jobs
server.serve_forever()
I'm getting this exception where it gives me failed to handle request from werkzeug server.
I've used only werkzeug utility and have never used werkzeug server..
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/gevent/server.py", line 131, in _do_accept
self._handle(client_socket, address)
File "/usr/local/lib/python2.7/dist-packages/gevent/pywsgi.py", line 571, in handle
handler.handle()
File "/usr/local/lib/python2.7/dist-packages/gevent/pywsgi.py", line 180, in handle
result = self.handle_one_request()
File "/usr/local/lib/python2.7/dist-packages/gevent/pywsgi.py", line 287, in handle_one_request
raw_requestline = self.read_requestline()
File "/usr/local/lib/python2.7/dist-packages/gevent/pywsgi.py", line 280, in read_requestline
return self.rfile.readline(MAX_REQUEST_LINE)
File "/usr/lib/python2.7/socket.py", line 476, in readline
data = self._sock.recv(self._rbufsize)
File "/usr/local/lib/python2.7/dist-packages/gevent/socket.py", line 432, in recv
wait_read(sock.fileno(), timeout=self.timeout, event=self._read_event)
File "/usr/local/lib/python2.7/dist-packages/gevent/socket.py", line 169, in wait_read
switch_result = get_hub().switch()
File "/usr/local/lib/python2.7/dist-packages/gevent/hub.py", line 154, in switch
assert cur is not self, 'Cannot switch to MAINLOOP from MAINLOOP'
AssertionError: Cannot switch to MAINLOOP from MAINLOOP
<WSGIServer fileno=4 address=0.0.0.0:4000>: Failed to handle request from ('127.0.0.1', 36088)

Resources