How to pop a tkMessageBox in a twisted powered server
I have a server based on twiste开发者_StackOverflowd reactor, and I need the following scenario: the server can receive two types of request
- ADD(x,y) and returns a sum
- HUMAN_PERMISSION which returns true only if the human user approved the ip of the client
I am using tkMessageBox to ask the human user, but the problem is that it blocks the whole reactor and the server becomes unresponsive to other requests
I understand that I have to use twisted's deferred here in some way, just dont know how this: doesnt seem to work, it still blocks the whole reactor
d = deferLater(reactor, 1,tkMessageBox.showinfo, "is he ok?", clientIp)
d.addCallback(confirmUser)
Deferreds can't do anything to make your code non-blocking. All they can do is manage a callback chain based on an existing non-blocking event. That's what lets you translate low-level events like "some bytes were received" or "a connection was lost" or "a user clicked on a button" into high level events like "the HTTP request was responded to" or "the user answered your question". deferLater
, for example, simply fires its Deferred
when some time has passed.
You don't need a reactor to use a Deferred
, even. For example:
>>> from twisted.internet.defer import Deferred
>>> d = Deferred()
>>> def transformResult(result):
... return result + 5
...
>>> d.addCallback(transformResult)
<Deferred at 0x100521200>
>>> def itsDone(result):
... print("It's done: " + str(result))
...
>>> d.addCallback(itsDone)
<Deferred at 0x100521200>
>>> d.callback(3)
It's done: 8
>>>
You can call callback()
from anywhere; it's just usually called from a reactor event. In your case, you probably want to call callback
from a Tk
event instead.
All that said, you need a way to get Tk
events into the main reactor thread, which you do by using a reactor that knows about Tk
's mainloop. A commenter already mentioned that there is an existing API for this: twisted.internet.tksupport
. Given that Tk
is not the most popular GUI these days, you may find some issues, so please report them if you find any.
精彩评论