Websauna threading runtime signal error with pdb.set_trace() - pyramid

I want to debug the runtime of a websauna app, so I set a
pdb.set_trace()
in
system/admin/views.py:87 like so,
#view_config(context=ModelAdmin.Resource, name="show", renderer="crud/show.html", route_name="admin", permission='view')
def show(self):
# We override this method just to define admin route_name traversing
import pdb; pdb.set_trace()
return super(Show, self).show()
but I get the pyramid runtime error:
ValueError: signal only works in main thread
How do I avoid getting this runtime error and just break on the set_trace() ?

Is it possible to provide the entire class containing this view? That error is not a result of the short snippet you have provided above.

Related

Python: chain an exception to a warning

I want to handle certain exceptions by catching the exception and issuing a warning. When the warning is displayed (e.g. on stderr or in a log file, I use the logging module for that) I want it to display the stack trace of the warning followed by "caused by" plus the stack trace of the original exception.
If I were to raise another exception I would use the from keyword (assume XException, YException are custom exception classes derived from Exception and YWarning is derived from the Warning class):
def do_x():
riase XException("Failed to do X")
def do_y():
try:
# do other things
do_x()
# maybe do some more things
except XException as x_exc:
raise YException("Failed to do Y") from x_exc
But in my case, if doing X fails, it's not such a big deal and I can continue to do Y. I want to issue a warning though.
from warnings import warn
def do_x():
raise XException("Failed to do X")
def do_y():
try:
# do other things
do_x() # if this fails, we can live with it
except XException as x_exc:
warn(YWarning("Things went not so smooth with doing Y", cause=x_exc))
Here I made up the cause= optional argument, so what I'd like to know is how do I instantiate any Exception subclass (which includes Warning and its subclasses) and specify the cause.
So while writing this question I came up with a possible answer.
ywarn = YWarning("Things went not so smooth with doing Y")
ywarn.__cause__ = x_exc
warn(ywarn)
It turns out, according to PEP 3134, that from does exactly that.
One could even actually implement the imaginary cause= optional argument. After all, the YWarning is a custom subclass.
class YWarning(Warning):
def __init__(self, msg, cause=None):
self.__cause__ = cause

CherryPy Tool: How to register custom tool correctly?

I want to create a simple tool but fail to register it correctly. As soon as I add it to any method I get the error:
AttributeError: 'Toolbox' object has no attribute 'authenticate'
I tried
cherrypy.tools.authenticate = cherrypy.Tool('before_handler', authenticate)
and
#cherrypy.tools.register('before_handler')
def authenticate():
The issue I likely have is placing the function in the wrong place. I have a main file launching the server and all apps:
#config stuff
if __name__ == '__main__':
cherrypy.engine.unsubscribe('graceful', cherrypy.log.reopen_files)
logging.config.dictConfig(LOG_CONF)
cherrypy.tree.mount(app1(), '/app1')
cherrypy.tree.mount(app2(), '/app2')
cherrypy.quickstart(app3)
This file is launched by a systemd unit.
If I put the authenticate function in the config area, it doesn't work. If i put it in one of the apps directly and only use it in that app, it doesn't work. Always the same error.
So where do I have to place it to make this work?
Another case of me falling into the python definition order matters trap.
Doesn't work:
class MyApp(object):
#....
#cherrypy.tools.register('on_start_resource')
def authenticate():
#....
Works:
#cherrypy.tools.register('on_start_resource')
def authenticate():
#....
class MyApp(object):

Python Check if Methods or interface is implemented before runtime

I'm creating an interface Mixins that contains methods that will throw error if it is not implemented, however it only happens during run time when the method is called, i would like to have python check if method is implemented before run time.
class TestInterface():
def get_testing_name(self):
raise NotImplementedError
def do_something(self):
return self.get_testing_name()
class Testing(TestInterface):
def __init__(self):
super().do_something()
In my Testing class, i didn't defined get_testing_name method, hence it will raise NotImplementedError. However this will only happen on run time
How do i make sure python check if method is not implemented before run time?
I don't know if I understood you.
Maybe that was what you wanted ?:
try:
t = Testing()
except NotImplementedError:
print("Fail")

How do I connect a PyQt5 slot to a signal function in a class?

I'm trying to set up a pyqt signal between a block of UI code and a separate python class that is just for handling event responses. I don't want to give the UI code access to the handler (classic MVC style). Unfortunately, I am having difficulty connecting the slot to the signal. Here is the code:
from PyQt5 import QtCore
from PyQt5.QtCore import QObject
class UiClass(QObject):
mySignal = QtCore.pyqtSignal( str )
def __init__(self):
QObject.__init__(self)
def send_signal(self):
self.mySignal.emit("Hello world!")
class HandlerClass():
currentMessage = "none"
def register(self, mySignal):
mySignal.connect(self.receive_signal)
#QtCore.pyqtSlot(str)
def receive_signal(self, message):
self.currentMessage = message
print(message)
ui = UiClass()
handler = HandlerClass()
handler.register(ui.mySignal)
ui.send_signal()
When I run this code it fails at the handler.register line. Here is the error:
Traceback (most recent call last):
File "C:\git\IonControl\testpyqtslot.py", line 25, in
handler.register(ui.mySignal)
File "C:\git\IonControl\testpyqtslot.py", line 17, in register
mySignal.connect(self.receive_signal)
TypeError: connect() failed between UiClass.mySignal[str] and receive_signal()
I'd like this code to successfully register the signal to the slot and have the handler print "hello world" at the end. What did I do wrong here?
My basic question is this: how do I connect a signal to a slot function that is part of a class?
The error happens becuase you are using pyqtSlot decorator in a class which doesn't inherit from QObject. You can fix the problem by either getting rid of the decorator, or making HandlerClass a subclass of QObject.
The main purpose of pyqtSlot is to allow several different overloads of a slot to be defined, each with a different signature. It may also be needed sometimes when making cross-thread connections. However, these use-cases are relatively rare, and in most PyQt applications it is not necessary to use pyqtSlot at all. Signals can be connected to any python callable object, whether it is decorated as a slot or not.

RobotFramework Monitoring Thread to Trigger Teardown

I am trying to have a monitoring thread in robotframework to continuously monitor a signal and force a teardown if a certain signal is read. I have the following code.
import signal
from datetime import datetime
from robot.api import logger
from robot.libraries.BuiltIn import BuiltIn
import logging
import thread
import os
import sys
import time
def do_error_log_monitoring_new():
def _monitor_log():
time.sleep(5)
# Monitor_Some_Signal
builtin_lib.fatal_error(msg='Force Teardown')
thread_logger = logging.getLogger('root')
thread_logger.info("Started Fault Listener")
builtin_lib = BuiltIn().get_library_instance('BuiltIn', all=True)
thread.start_new_thread(_monitor_log, ())
I have builtin_lib = BuiltIn().get_library_instance('BuiltIn', all=True) with the all=True argument to return dictionary mapping of all library names to instances. However I see the following error:
AttributeError: 'dict' object has no attribute 'fatal_error'
Furthermore, removing the all=True argument allows the function to go through and fatal_error to trigger, however I notice that it does not trigger a teardown in the main thread, which is what I intend to do. Any advice on how I can trigger teardown in the main thread from the fatal_error() function in the secondary thread?
You're setting builtin_lib to a dictionary (the result of BuiltIn().get_library_instances(..., all=True). As the error message states, this dictionary does not have a fatal_error method.
Change this:
builtin_lib.fatal_error(msg='Force Teardown')
... to this:
BuiltIn().fatal_error(msg='Force Teardown')
If you only need a reference to the BuiltIn library (versus a dictionary of all libraries), you don't need to call get_library_instance at all since BuiltIn() already returns an instance of the library.

Resources