WebSocketHandler doesn't call initialize - websocket

What I'm trying to do, is have an object (it's a gstreamer process that runs in a seperate thread) to be able to call the write_message() function of a WebSocketHandler
Here is a piece of code that I currently have
app = tornado.web.Application([
(r'/', RadioSocketHandler),
])
class RadioSocketHandler(tornado.websocket.WebSocketHandler):
def initialize(self):
self.player = MusicPlayer(self)
thread.start_new(self.player.start(), ())
class MusicPlayer(object):
websocket_handler = None
def __init__(self, sockethandler):
self.websocket_handler = sockethandler
self.websocket_handler.write_message("success")
However, it does not work. 'initialize' is never called. What am I doing wrong?
__init__()
doesn't work either.
Or is there another way to call a function from the RadioSocketHandler outside of it's own class?
I'm quite new to Python fyi

Alright I got it working with the following:
app = tornado.web.Application([
(r'/', RadioSocketHandler, {'player': player}),
])
class RadioSocketHandler(tornado.websocket.WebSocketHandler):
def __init__(self, *args, **kwargs):
self.musicplayer = kwargs.pop('player')
self.musicplayer.set_sockethandler(self)
super(RadioSocketHandler, self).__init__(*args, **kwargs)
class MusicPlayer(object):
websocket_handler = None
def set_sockethandler(self, handler):
self.websocket_handler = handler
I had to give the arguments to the init function on a different way. And I forgot super()

Related

Tornado Coroutine fails with 'dict' object not callabale

Python version: 3.6
I am not super expert in Python, I was trying to use Tornado to implement a simple REST server and use non blocking coroutine to call a blocking function. When I return Json from the blocking function it fails with TypeError: 'dict' object is not callable
Here's the code
#gen.coroutine
def post(self):
jsonResponse = yield self.process_request(imageBytes)
self.write(json.dumps(jsonResponse))
#gen.coroutine
def process_request(self, imageBytes):
response = yield (executor.submit(self.test_func(), None))
return response
def test_func(self):
print('test func')
time.sleep(1)
jsonDataSet = {"text": "hello 123"}
return jsonDataSet
I am not sure what I am doing wrong, followed the sample code from Tornado reference. Any pointers will be helpful?
Latest:
I moved to async & await now I am getting "Object of type 'coroutine' is not JSON serializable"
async def test_func():
print('test func')
time.sleep(1)
jsonDataSet = {"text": "hello 123"}
return jsonDataSet
#return "test"
response = await `tornado.ioloop.IOLoop.current().run_in_executor(None, test_func)`
TypeError: 'dict' object is not callable
executor.submit() requires a callable, but you're already calling the test_func function. When you call test_func(), you're essentially passing its return value (which is a dict) to the submit() function.
You need pass this function without calling:
executor.submit(self.test_func, None)
Latest: I moved to async & await now I am getting "Object of type 'coroutine' is not JSON serializable"
run_in_executor is for running a normal function in a separate thread. It's not meant for running coroutines.
What's happening here is run_in_executor is calling test_func() coroutine, which automatically returns an awaitable object (because it's a coroutine).
If you want to execute test_func using run_in_executor, just make it a normal function (don't use async def).

Must __aenter__ return an awaitable? [duplicate]

In Python Lan Ref. 3.4.4, it is said that __aenter__() and __aexit__() must return awaitables. However, in the example async context manager, these two methods return None:
class AsyncContextManager:
async def __aenter__(self):
await log('entering context')
async def __aexit__(self, exc_type, exc, tb):
await log('exiting context')
Is this code correct?
__aenter__ and __aexit__ must return awaitables, but look what happens when you call the ones in the example:
>>> class AsyncContextManager:
... async def __aenter__(self):
... await log('entering context')
... async def __aexit__(self, exc_type, exc, tb):
... await log('exiting context')
...
>>> AsyncContextManager().__aenter__()
<coroutine object AsyncContextManager.__aenter__ at 0x7f5b092d5ac0>
It didn't return None! We got a coroutine object, which is awaitable.
These methods are async functions, which automatically return (awaitable) asynchronous coroutines. return statements in the body of an async function determine what gets returned when you await the coroutine, not what gets returned when you call the function.
This is similar to how generator functions return generator iterators, even though they usually have no return statement, and how if you write __iter__ as a generator function, you should not try to return an iterator inside the generator function.
So what happens if you do put a return in __aenter__ or __aexit__ defined as async functions? Well, you can, and if you do, the return statement doesn't have to return an awaitable. Here's what Python will do.
If you return something from an __aenter__ defined as an async function, that determines what gets bound to an as target, if the async with uses as.
If you return something from an __aexit__ defined as an async function, that determines whether to suppress exceptions that got raised inside the block. A "truthy" value tells the async with to suppress exceptions, while a "falsy" value tells the async with to let exceptions propagate. The default None is falsy, so by default, exceptions are not suppressed.
Here's an example:
import asyncio
class Example:
async def __aenter__(self):
return 3
async def __aexit__(self, exc_type, exc, tb):
return True
async def example():
async with Example() as three:
print(three == 3)
raise Exception
print("Exception got suppressed")
asyncio.run(example())
Output:
True
Exception got suppressed
Your __aenter__ method must return a context.
class MyAsyncContextManager:
async def __aenter__(self):
await log('entering context')
# maybe some setup (e.g. await self.setup())
return self
async def __aexit__(self, exc_type, exc, tb):
# maybe closing context (e.g. await self.close())
await log('exiting context')
async def do_something(self):
await log('doing something')
usage:
async with MyAsyncContextManager() as context:
await context.do_something()

PyQt5 overriding QDockwidget event bug?

I have the following problem where I want to customize the QDockwidget event function and calling super() already gives me an error withouth Code in it.
Error:
TypeError: invalid result from DockWindow.event(), an integer is required (got type NoneType)
Here is my actual Code:
from PyQt5.QtWidgets import QApplication, QDockWidget
from PyQt5.QtWidgets import QMainWindow
from PyQt5 import QtCore
import sys
class DockWindow(QDockWidget):
def __init__(self, parent=None):
super(DockWindow, self).__init__(parent, QtCore.Qt.Widget)
def event(self, ev):
# I actually want to do stuff here. But following already produces an error.
super(DockWindow, self).event(ev)
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super().__init__(parent, QtCore.Qt.Window)
self.dock_window = DockWindow(parent=self)
self.addDockWidget(QtCore.Qt.RightDockWidgetArea, self.dock_window)
def main(argv):
app = QApplication(sys.argv)
win = MainWindow()
win.show()
app.exec_()
if __name__ == '__main__':
main(sys.argv)
EDIT:
return super(DockWindow, self).event(ev)
does the trick!

PyCharm: Debug Django Forms clean() override

I overrode clean() in a derived forms class:
def clean(self):
self.user = None
cleaned_data = super(LoginForm, self).clean()
username = cleaned_data["user_id"].lower()
But the debugger isn't stopping on breakpoints that I set within the overridden method (e.g., it doesn't stop on a break set on self.user = None).
I can see that the method is being invoked because a custom ValidationError gets raised and recorded.
Is there a limitation on the PyCharm debugger where it won't hit breakpoints in overridden methods?

In MATLAB, can a class method act as a uicontrol callback without being public?

In MATLAB 2008a, is there a way to allow a class method to act as a uicontrol callback function without having to make the method public? Conceptually, the method should not be public because it should never be called by a user of the class. It should only be called as a result of a UI event triggering a callback. However, if I set the method's access to private or protected, the callback doesn't work. My class is derived from hgsetget and is defined using the 2008a classdef syntax.
The uicontrol code looks something like:
methods (Access = public)
function this = MyClass(args)
this.someClassProperty = uicontrol(property1, value1, ... , 'Callback', ...
{#(src, event)myCallbackMethod(this, src, event)});
% the rest of the class constructor code
end
end
The callback code looks like:
methods (Access = private) % This doesn't work because it's private
% It works just fine if I make it public instead, but that's wrong conceptually.
function myCallbackMethod(this, src, event)
% do something
end
end
Storing the function handle of the callback as a private property seems to workaround the problem. Try this:
classdef MyClass
properties
handle;
end
properties (Access=private)
callback;
end
methods
function this = MyClass(args)
this.callback = #myCallbackMethod;
this.handle = uicontrol('Callback', ...
{#(src, event)myCallbackMethod(this, src, event)});
end
end
methods (Access = private)
function myCallbackMethod(this, src, event)
disp('Hello world!');
end
end
end

Resources