Catch exceptions in CherryPy 3.2 during body.process - cherrypy

I got the following error in a live site where a utf character (test string 'Îñţérñâţîöñåļîžæ†îøñ') was submitted:
400 Bad Request
The request entity could not be decoded. The following charsets were attempted: ['utf-8']
Traceback (most recent call last):
File ".virtual/local/lib/python2.7/site-packages/cherrypy/_cprequest.py", line 648, in respond
self.body.process()
File ".virtual/local/lib/python2.7/site-packages/cherrypy/_cpreqbody.py", line 931, in process
super(RequestBody, self).process()
File ".virtual/local/lib/python2.7/site-packages/cherrypy/_cpreqbody.py", line 500, in process
proc(self)
File ".virtual/local/lib/python2.7/site-packages/cherrypy/_cpreqbody.py", line 153, in process_urlencoded
"charsets were attempted: %s" % repr(entity.attempt_charsets))
HTTPError: (400, "The request entity could not be decoded. The following charsets were attempted: ['utf-8']")
Powered by CherryPy 3.2.0
I can fix this using <form type="POST" accept-charset="utf-16">.
Normally, I catch errors in application code and log them or email them to myself, but this error never reached my application code which runs on TurboGears 1.5.
Any idea on how I can hook in to catch and log errors generated by CherryPy, and secondarily, give the user a better 404 page?
The method of error handling listed at _cperror.html#unanticipated-errors
doesn't work for this sort of error (but kicks in on e.g. static file missing)

Related

How to fix ValueError: I/O operation on closed file for ctx.voice_client.stop() in discord.py on linux

I am trying to run a music bot on a vps running ubuntu. Everything works fine when I run the bot on windows, but when I move it over to my linux vps and use my skip command, it gives me an error: ValueError: I/O operation on closed file. I am not sure how to fix this as it seems to be entirely to do with discord.py's inner workings, as you can see the code simply calls the ctx.voice_client.stop() method.
I have tried looking online and cannot find anyone who mentions this issue, so I believe it to be a problem specific to me, but I cannot figure out why it works on windows and not linux. Here is the command:
#commands.command(name='skip', description="skips to the next song in queue")
async def skip_(self, ctx):
"""Skip the song."""
vc = ctx.voice_client
if not vc or not vc.is_connected():
embed = discord.Embed(title="", description="Not connected to a voice channel")
return await ctx.send(embed=embed)
if not vc.is_playing() and not vc.is_paused():
return await ctx.send("**Nothing is playing**")
vc.stop()
Here is the full error:
Task exception was never retrieved
future: <Task finished name='Task-26' coro=<MusicPlayer.player_loop() done, defined at /home/ubuntu/mystuff/DiscordBots/MusicPlayer/bot.py:144> exception=ValueError('I/O operation on closed file')>
Traceback (most recent call last):
File "/home/ubuntu/mystuff/DiscordBots/MusicPlayer/bot.py", line 177, in player_loop
source.cleanup()
File "/home/ubuntu/.local/lib/python3.10/site-packages/discord/player.py", line 628, in cleanup
self.original.cleanup()
File "/home/ubuntu/.local/lib/python3.10/site-packages/discord/player.py", line 225, in cleanup
self._kill_process()
File "/home/ubuntu/.local/lib/python3.10/site-packages/discord/player.py", line 203, in _kill_process
proc.communicate()
File "/usr/lib/python3.10/subprocess.py", line 1139, in communicate
stdout = self.stdout.read()
ValueError: I/O operation on closed file

Local stack says started but throwing different errors `Error forwarding request: TypeError: the JSON object must be str, bytes or bytearray

I am getting this when I start make infra using localstack
Starting local dev environment. CTRL-C to quit.
cannot import name 'dns_server' from 'localstack_ext.services' (unknown location)
Starting mock S3 (http port 4572)...
Starting mock SNS (http port 4575)...
2019-09-21T13:11:08:INFO:localstack.multiserver: Starting multi API server process on port
51492
Starting mock SQS (http port 4576)...
Starting mock DynamoDB (http port 4569)...
Starting mock Lambda service (http port 4574)...
Starting mock CloudWatch Logs (http port 4586)...
Ready.
But when I do http://localhost:4569 it throws error and doesnt show it started.
Below are the errors I am getting
2019-09-21T13:15:05:ERROR:localstack.services.generic_proxy: Error forwarding request: the
JSON object must be str, bytes or bytearray, not NoneType Traceback (most recent call last):
File "/Users//workspaces/others/localstack/localstack/services/generic_proxy.py", line 240,
in forward
path=path, data=data, headers=forward_headers)
File"/Users//workspaces/others/localstack/localstack/services/dynamodb/dynamodb_listener.py",
line 35, in forward_request
data = json.loads(to_str(data))
File"/usr/local/Cellar/python/3.7.4/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/init.py", line 341, in loads
raise TypeError(f'the JSON object must be str, bytes or bytearray, '
TypeError: the JSON object must be str, bytes or bytearray, not NoneType
Error 2:
2019-09-21T13:14:11:ERROR:localstack.services.generic_proxy: Error forwarding request:'QueueUrl' Traceback (most recent call last):
File "/Users//workspaces/others/localstack/localstack/services/generic_proxy.py", line 240, in forward
path=path, data=data, headers=forward_headers)
File "/Users//workspaces/others/localstack/localstack/services/sqs/sqs_listener.py", line 53, in forward_request
self._set_queue_attributes(req_data)
File "/Users/*****/workspaces/others/localstack/localstack/services/sqs/sqs_listener.py", line 245, in _set_queue_attributes
queue_url = req_data['QueueUrl'][0]
KeyError: 'QueueUrl'`
Please help on this its a been a blocker for me.
This is because I was hitting http://localhost:4569 which isn't a user interface. So its throwing error.But if I create tables using aws cli and do some operations it just works fine without any issue.

_tkinter.TclError: invalid command name ".!text"

I am making a program using tkinter that executes some code from different files.
This is the part of my code causing problems:
text=textbox.get('1.0','end-1c')
FYI: textbox is a tkinter.Text object defined by a different file that my code executed
when ever I execute my code, I get the error:
Exception in Tkinter callback
Traceback (most recent call last):
File "/anaconda3/lib/python3.7/tkinter/__init__.py", line 1705, in __call__
return self.func(*args)
File "/Users/iskee/python/programs/atfedit/atf.py", line 98, in save
text=textbox.get('1.0','end-1c')
File "/anaconda3/lib/python3.7/tkinter/__init__.py", line 3246, in get
return self.tk.call(self._w, 'get', index1, index2)
_tkinter.TclError: invalid command name ".!text"
what is going wrong?
That error means that you're trying to access a widget that has been destroyed.

Seeing 'AttributeError: __enter__ 'when expecting to see Rasa Bot responses

I am trying to follow a post over creating and running a Rasa bot
Steps already did:
- I could get all working folders
- Got the basic data files
- Trained Nlu and Core
- launched action server and command line
- So here the expectation is User enters Input like 'Hi or hello' and then bot responds and continues the chat
Actual results: Seeing below error.
make cmdline
python -m rasa_core.run -d models/current/dialogue -u models/current/nlu --endpoints endpoints.yml
C:\Python3.6\lib\site-packages\h5py\__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.
from ._conv import register_converters as _register_converters
2019-05-14 17:06:45 INFO root - Rasa process starting
2019-05-14 17:06:49 INFO rasa_nlu.components - Added 'nlp_spacy' to component cache. Key 'nlp_spacy-en'.
2019-05-14 17:07:18.101829: I tensorflow/core/platform/cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2
2019-05-14 17:07:19 INFO root - Rasa Core server is up and running on http://localhost:5005
Bot loaded. Type a message and press enter (use '/stop' to exit):
Your input -> hey
127.0.0.1 - - [2019-05-14 17:08:23] "POST /webhooks/rest/webhook?stream=true&token= HTTP/1.1" 200 190 0.254340
Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\Python3.6\lib\threading.py", line 916, in _bootstrap_inner
self.run()
File "C:\Python3.6\lib\threading.py", line 864, in run
self._target(*self._args, **self._kwargs)
File "C:\Python3.6\lib\site-packages\rasa_core\channels\console.py", line 114, in record_messages
for response in bot_responses:
File "C:\Python3.6\lib\site-packages\rasa_core\channels\console.py", line 71, in send_message_receive_stream
with requests.post(url, json=payload, stream=True) as r:
AttributeError: __enter__
On preliminary search over forums, seems it is a Python code issue, as I understand it try to get bot responses using 'WITH' keyword ?
Any pointers on how can I get it sorted please ?
Thanks in advance,
Venky

Hello world failing

I've just installed python 3.2.1 (32-bit) and cherrypy 3.2.1 (CherryPy-3.2.1.win32-py3.exe) on my Windows 7 box and have tried the hello world example (executed via PyScripter) but it hangs after the Engine bus STARTED message.
If I try to start it via the python.exe, I get the following log:
C:\Program Files (x86)\Python32>python hello.py
[24/Jul/2011:16:24:03] ENGINE Listening for SIGTERM.
[24/Jul/2011:16:24:03] ENGINE Bus STARTING
CherryPy Checker:
The Application mounted at '' has an empty config.
[24/Jul/2011:16:24:03] ENGINE Started monitor thread 'Autoreloader'.
[24/Jul/2011:16:24:03] ENGINE Started monitor thread '_TimeoutMonitor'.
[24/Jul/2011:16:24:03] ENGINE Serving on 127.0.0.1:8080
[24/Jul/2011:16:24:03] ENGINE Bus STARTED
Exception in thread CP Server Thread-4:
Traceback (most recent call last):
File "C:\Program Files (x86)\Python32\lib\site-packages\cherrypy\wsgiserver\ws
giserver3.py", line 693, in read_request_headers
read_headers(self.rfile, self.inheaders)
File "C:\Program Files (x86)\Python32\lib\site-packages\cherrypy\wsgiserver\ws
giserver3.py", line 202, in read_headers
raise ValueError("Illegal end of headers.")
ValueError: Illegal end of headers.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Program Files (x86)\Python32\lib\site-packages\cherrypy\wsgiserver\ws
giserver3.py", line 1024, in communicate
req.parse_request()
File "C:\Program Files (x86)\Python32\lib\site-packages\cherrypy\wsgiserver\ws
giserver3.py", line 578, in parse_request
success = self.read_request_headers()
File "C:\Program Files (x86)\Python32\lib\site-packages\cherrypy\wsgiserver\ws
giserver3.py", line 696, in read_request_headers
self.simple_response("400 Bad Request", ex.args[0])
File "C:\Program Files (x86)\Python32\lib\site-packages\cherrypy\wsgiserver\ws
giserver3.py", line 840, in simple_response
status = str(status)
TypeError: 'tuple' object is not callable
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Program Files (x86)\Python32\lib\threading.py", line 736, in _bootstr
ap_inner
self.run()
File "C:\Program Files (x86)\Python32\lib\site-packages\cherrypy\wsgiserver\ws
giserver3.py", line 1174, in run
conn.communicate()
File "C:\Program Files (x86)\Python32\lib\site-packages\cherrypy\wsgiserver\ws
giserver3.py", line 1080, in communicate
req.simple_response("500 Internal Server Error", format_exc())
File "C:\Program Files (x86)\Python32\lib\site-packages\cherrypy\wsgiserver\ws
giserver3.py", line 840, in simple_response
status = str(status)
TypeError: 'tuple' object is not callable
What am I missing?
Code:
import cherrypy
class HelloWorld:
def index(self):
return "Hello world"
index.exposed = True
cherrypy.quickstart(HelloWorld())
EDIT: Bonus-info: I've tried various things to remedy the situation with no result. Installing the 64-bit version of python didn't help as cherrypy doesn't support 64-bit (unless, I'm mistaken). I've tried re-installing both python and the cherrypy packages, and I've tried deactivating all other things that might block it (IIS). All to no avail :-(
EDIT2: Second bonus - everything works if I install it with python 2.7.2, so seems it is only a problem with 3.x (I've tried 3.0.1 as well - same problem)
I have encountered two errors:
1 - open your browser before starting the script, so you'll not have any problem.
2 - if you use a personal firewall or an antivirus that handles HTTP protection, be sure he is not protecting the 8080 port, for example ESET Antivirus will not let you use the 8080 and CherryPy will say that the port is not free.

Resources