前段时间一直在用twisted在做server,当时在技术的选择上有些盲目,导致做到现在走了不少的弯路。还是写点东西总结一下吧。
twisted+fastcgi
search_server.py
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 from twisted.web2 import http,responsecode,http_headers,resource
2 class SearchHandledRequest(resource.Resource):
3 def render(self,req):
4 http.Response(responsecode.OK,{'content-type': http_headers.MimeType('text', 'html')},"")
5 if __name__ == "__builtin__":
6 from twisted.application import service, strports
7 from twisted.web2 import server, channel
8 from twisted.python import util
9 port_search = 9000
10 search = SearchHandledRequest()
11 site_search = server.Site(search)
12 application = service.Application("search")
13 s_search = strports.service('tcp:%i'%port_search, channel.FastCGIFactory(site_search))
14 s_search.setServiceParent(application)
15
在以fastcgi的方式配置到nginx上去,具体的配置网上到处都是。启动nginx,命令行里运行 twistd.py -noy search_server.py就行了。这样简单的twisted+fastcgi+nginx的服务就跑起来了。这样的部署我也用Siege做过压力测试,性能还不错。另外web2的部署方式见http://twistedsphinx.funsize.net/projects/web2/howto/deployment.html
另外在web2里用类似于cookie,session都不是很方便。
下面就是我折腾怎么用cookie的代码
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
headers = request.headers
cookies = headers.getHeader('cookie',[])
#改变cookies
return http.Response(responsecode.OK,{'content-type': http_headers.MimeType('text', 'html'),'set-cookie':set_cookies},"")
另外就是需要在web2里http_header.py的Headers累里添加
1 def getCookie(self, name):
2 for cookie in self.getHeader('cookie', ()):
3 if cookie.name == name:
4 return cookie
还有,之前同事在用twisted文件的上传下载时,问题一堆,最后还是放弃了。
总结一下,不管twisted的web还是web2都是不太合适做web开发的,如果让我从头再来的话,我决定不会选择它的。