Sunday, Mar 8th, 2009 by Tim |
0 Comments
Filed under:
Python | Tags:
Python,
socket
从网上参考了一些代码,实现了一个Python实现的基于线程的socket server, 用来实现各种服务系统的原型。放在这里供以后参考。
#!/usr/bin/env python
import threading
import SocketServer
users = []
class MyTCPHandler(SocketServer.StreamRequestHandler):
def handle(self):
username = None
while True:
self.data = self.rfile.readline().strip()
cur_thread = threading.currentThread()
print "RECV from ", self.client_address[0]
cmd = self.data
if cmd == None or len(cmd) == 0:
break;
print cmd
# business logic here
try:
if cmd.startswith('echo'):
result = cmd[5:]
elif cmd.startswith('login'):
username = cmd[6:]
users.append({username:self.wfile})
result = username + ' logined.'
elif cmd == 'quit':
break
else:
result = 'error cmd'
self.wfile.write(result)
self.wfile.write('\n')
except:
print 'error'
break
try:
if username != None:
users.remove(username)
except:
pass
print username, ' closed.'
class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
pass
if __name__ == "__main__":
HOST, PORT = "localhost", 9999
server = ThreadedTCPServer((HOST, PORT), MyTCPHandler)
server_thread = threading.Thread(target=server.serve_forever)
server_thread.setDaemon(True)
server_thread.start()
server.serve_forever()
Thursday, Feb 26th, 2009 by Tim |
1 Comments
Filed under:
Python | Tags:
flup,
Python,
REST,
web.py
前文用Python实现CRUD功能REST服务中发现,一个普通的web.py页面每秒只能执行数十次requests,经网友Arbow提醒, web.py默认是单线程方式,所以性能提升困难,并推荐了一些高性能的web framework。同时也看到Python资深网友ZoomQuiet的总结 Pythonic Web 应用平台对比,因此觉得有必要换一种更强的web framework。同时也研究了国内著名的豆瓣所采用的Quixote框架。但由于牵涉到更换之后web.py中的REST接口代码实现要调整,所以就暂时搁置了。
后来看到搜狐qiuyingbo在lighttpd 2.0一文中提到sohu mail也是用web.py, 在向qiuyingbo请教之后,了解到web.py通过fastcgi多进程方式也可以实现高性能的访问,决定不再换框架了。
qiuyingbo推荐使用nginx+flup+webpy, 但是最近nginx的mod_wsgi页面中的 http://wiki.codemongers.com/NginxNgxWSGIModule 下载链接始终不能访问,所以就转向 lighttpd/fastcgi 方式,国外著名的reddit也是采用此架构,性能上应该不会有很大的差异。
在安装了lighttpd和配置之后,目前调用一个helloworld.py在本地一普通服务器上可以每秒达到1000次左右,在一个更专业的4核服务器上,执行速度更可4,000次。基本上可以满足运营的要求。
另外赖勇浩在blog我常用的几个第三方 Python 库中提到,使用psyco可以提升Python 40%或更高的性能。在32bit Linux下,测试上面的场景可提高约10%的性能。但由于Psyco不支持64bit架构,所以正式的生产环境就没有安装这个加速功能。
具体配置过程如下,假定lighttpd安装在/data0/lighttpd下:
- Install Lighttpd, Download lighttpd http://www.lighttpd.net/download/lighttpd-1.4.21.tar.gz
./configure –prefix=/data0/lighttpd –with-openssl; make; make install
cp docs/lighttpd.conf /data0/lighttpd/sbin
openssl req -new -x509 -keyout lighttpd.pem -out lighttpd.pem -days 365 -nodes
- Install Python 2.6, 具有内置Json支持 http://www.python.org/ftp/python/2.6.1/Python-2.6.1.tgz
./configure; make; make install
- Install web.py http://webpy.org/static/web.py-0.31.tar.gz
python setup.py install
- Install flup, http://www.saddi.com/software/flup/dist/flup-1.0.1.tar.gz
- Install lighttpd + fastcgi with web.py
fastcgi.server = ( “/main.py” =>
(
( “socket” => “/tmp/fastcgi.socket”,
“bin-path” => “/data0/lighttpd/www/python/main.py”,
“max-procs” => 50,
“bin-environment” => (
“REAL_SCRIPT_NAME” => “”
), “check-local” => “disable”
)
)
)
url.rewrite-once = (
“^/favicon.ico$” => “/static/favicon.ico”,
“^/static/(.*)$” => “/static/$1″,
“^/(.*)$” => “/main.py/$1″,
)
也可参看webpy官方的lighttpd fastcgi说明:http://webpy.org/cookbook/fastcgi-lighttpd
cd /data0/lighttpd/sbin; ./lighttpd -f lighttpd.conf
Thursday, Feb 12th, 2009 by Tim |
1 Comments
Filed under:
Python | Tags:
Python,
REST,
web.py
最近内部需要实现一个新的HTTP REST服务,数据用JSON。打算用Python来做一个原型,用于比较和Java实现方案的具体差异,以前也没有Python实战经验,所以摸索过程如下。
首先定义协议,假定我们要实现一个群组成员管理的服务
添加成员:
POST http://server/group-user/<group-id>
users=[1,2,3...]
删除成员:
DELETE http://server/group-user/<group-id>
users=[1,2,3...]
获取成员:
GET http://server/group-user/<group-id>
评估了几个python web框架之后,包括django, selector, CherryPy等。
Django安装和看了一些文档之后觉得它类似ruby on rails, 是一个快速的MVC/ORM的框架,相对于一个轻量级的REST服务来说不太适合。
selector文档太少,使用也感觉比较繁琐。
网上相关的讨论也比较少,可能目前REST方式还没大规模应用。正在比较迷茫的时候,看到了web.py的介绍,试用了一下之后,发现是碰到最适合目前需求的,使用也最简单。POST,GET,DELETE,PUT只需要在相应的function实现即可。另外还带了db,form,http等常用的web应用所需的类。
主要源代码:
class group_user:
def __init__(self):
pass
def GET(self, gid):
db = web.database(dbn='mysql', user='user', pw='pass', db='db', host="localhost")
users = db.query('SELECT * FROM groupuser WHERE groupid=$gid', \
vars={'gid':gid})
output = StringIO.StringIO()
output.write("[")
count = 0
for u in users:
if count > 0:
output.write(',')
output.write('["uid":%d,"nickname":%s]' % \
(u['uid'], json.dumps(u['nick'], True, False))
count += 1
output.write("]")
str = output.getvalue()
return str
def POST(self, gid):
data = web.data()
result = urlparse.parse_qs(data)
uid = result['uid'][0]
add_count = 0
list = json.loads(result['users'][0])
for u in list:
add_count += self.add_user(gid, u[0])
return add_count
def DELETE(self, gid):
data = web.data()
result = urlparse.parse_qs(data)
uid = result['uid'][0]
del_count = 0
list = json.loads(result['users'][0])
for u in list:
uid = u[0]
self.del_user(uid)
del_count += 1
return del_coun
几点感想:
- 原型所需要的功能很精简,开发效率比Java稍快,Java的代码长度可能会是这个1-2倍之间,但是针对这种纯业务逻辑的代码,Python的优势也不是非常明显,一个熟练的Java程序员可以很快完成这个功能。
- 性能。测试环境下每秒只能执行40-50次,如果用Java实现的话可以轻松上千次。如果性能问题不能调优,可能Python实现的这个功能也只能用来验证原型,没法用在生产环境。
- 数据库连接是每个function内部都执行一次连接,从Java的角度来看比较低效。
- Python 2.6之上自带JSON支持,无须另外寻找JSON库,比较方便。
- Python Web框架通过一个WSGI的规范来定义,类似Java的Servlet的规范。
- Python的代码强制嵌入的方式看起来比Java更优雅,除了class function定义中要带一个self参数比较怪异。
参考文档
http://jhcore.com/2008/09/20/getting-restful-with-webpy/