Twisted is a very imaginative framework. I have been impressed by its code. I think Twisted may only be used when I use python to develop a network application. However, to truly achieve performance optimization, we still need to apply Twisted tools well in our programs. The most common situation is that we add a long processing process to a non-blocking application to achieve the blocking effect, this allows everyone to wait for a long job as a comrade.
Let's take a look at the following code:
1 from twisted. internet import protocol, reactor
2 from twisted. protocols import basic
3 class FingerProtocol (basic. LineReceiver ):
4 def lineReceived (self, user ):
5 self. transport. write (self. factory. getUser (user) + "\ r \ n ")
6 self. transport. loseConnection ()
7 class FingerFactory (protocol. ServerFactory ):
8 protocol = FingerProtocol
9 def _ init _ (self, ** kwargs): self. users = kwargs
10 def getUser (self, user ):
11 return self. users. get (user, "No such user ")
12 reactor. listenTCP (1079, FingerFactory (hd = 'Hello my python World '))
13 reactor. run ()
It may be the first Twisted server we wrote. Everyone may think that this operation is no longer a problem. However, it is clear that our getUser may obtain relevant information from the database or the LDAP server in more cases. The best solution is to return the get operation in a non-real-time manner to avoid processing blocking. Deferreds is needed:
1 from twisted. internet import protocol, reactor, defer
2 from twisted. protocols import basic
3 class FingerProtocol (basic. LineReceiver ):
4 def lineReceived (self, user ):
5 self. factory. getUser (user
6). addErrback (lambda _: "Internal error in server"
7). addCallback (lambda m:
8 (self. transport. write (m + "\ r \ n "),
9 self. transport. loseConnection ()))
10 class FingerFactory (protocol. ServerFactory ):
11 protocol = FingerProtocol
12 def _ init _ (self, ** kwargs): self. users = kwargs
13 def getUser (self, user ):
14 return defer. succeed (self. users. get (user, "No such user "))
15 reactor. listenTCP (1079, FingerFactory (hd = 'Hello my python World '))
16 reactor. run ()
Here, getUser returns a transaction processed by defer, And the addCallback method registers the returned event after processing in defer. In this way, the transaction can be processed when another event can be scheduled. This prevents all users from stopping the response when one user's processing is blocked.