佳音的博客

2010/05/12

the.Definitive.Guide.to.Pylons.Dec.2008.pdf

Filed under: python — 佳音 @ 12:35 上午

Apress.the.Definitive.Guide.to.Pylons.Dec.2008

2010/05/01

python epoll demo

Filed under: python — 佳音 @ 2:03 下午

from http://www.codexon.com/posts/debunking-the-erlang-and-haskell-hype-for-servers
epoll.py

  1.  
  2. import select
  3. import socket
  4.  
  5. EPOLLIN = select.EPOLLIN
  6. EPOLLOUT = select.EPOLLOUT
  7.  
  8. epoll = select.epoll(60000)
  9. connections = {}
  10.  
  11. class Server(object):
  12.     def __init__(self):
  13.         sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  14.         sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  15.         sock.setblocking(0)
  16.         sock.bind((, 8050))
  17.         sock.listen(60000)
  18.         self.socket = sock
  19.  
  20.         fileno = sock.fileno()
  21.         connections[fileno] = self
  22.         epoll.register(fileno, EPOLLIN)
  23.  
  24.     def onInput(self):
  25.         sock, address = self.socket.accept()
  26.         Client(sock)
  27.  
  28. class Client(object):
  29.     input  =
  30.     output = "HTTP/1.0 200 OK\r\nContent-Length: 5\r\n\r\nPong!\r\n"
  31.  
  32.     def __init__(self, sock):
  33.         sock.setblocking(0)
  34.         fileno = sock.fileno()
  35.         epoll.register(fileno, EPOLLIN|EPOLLOUT)
  36.         connections[fileno] = self
  37.         self.socket = sock
  38.  
  39.     def onInput(self):
  40.         newdata = self.socket.recv(1024)
  41.         if len(newdata) is 0:
  42.             self.close()
  43.         self.input += newdata
  44.  
  45.     def onOutput(self):
  46.         sent = self.socket.send(self.output)
  47.         self.output = self.output[sent:]
  48.         if len(self.output) is 0:
  49.             self.close()
  50.  
  51.     def close(self):
  52.         fileno = self.socket.fileno()
  53.         del connections[fileno]
  54.         epoll.unregister(fileno)
  55.         self.socket.close()
  56.  
  57. Server()
  58.  
  59. while 1:
  60.     for fd, event in epoll.poll():
  61.         if event & EPOLLIN:
  62.             connections[fd].onInput()
  63.  
  64.         if event & EPOLLOUT:
  65.             connections[fd].onOutput()
  66.  
  67.  

2010/04/30

了解 epoll 之 python

Filed under: python — 佳音 @ 11:46 下午

http://scotdoyle.com/python-epoll-howto.html

Powered by 00RZ