Chinaunix首页 | 论坛 | 博客
  • 博客访问: 5024787
  • 博文数量: 921
  • 博客积分: 16037
  • 博客等级: 上将
  • 技术积分: 8469
  • 用 户 组: 普通用户
  • 注册时间: 2006-04-05 02:08
文章分类

全部博文(921)

文章存档

2020年(1)

2019年(3)

2018年(3)

2017年(6)

2016年(47)

2015年(72)

2014年(25)

2013年(72)

2012年(125)

2011年(182)

2010年(42)

2009年(14)

2008年(85)

2007年(89)

2006年(155)

分类: Python/Ruby

2013-06-04 16:57:47

This is an example of a simple asynchronous Python web server using . This is a copy of Jp Calderone's modified to accept a JSON payload in the POST request instead of form data. It also uses his to run the web server as a daemon with twistd.  


webserver.py


  1. """



  2. usage:
  3.         $ twistd -y webserver.py
  4. """


  5. from pprint import pprint
  6. from twisted.application.internet import TCPServer
  7. from twisted.application.service import Application
  8. from twisted.web.resource import Resource
  9. from twisted.web.server import Site


  10. class FormPage(Resource):
  11.     def render_GET(self, request):
  12.         return ''

  13.     def render_POST(self, request):
  14.         pprint(request.__dict__)
  15.         newdata = request.content.getvalue()
  16.         print newdata
  17.         return ''


  18. root = Resource()
  19. root.putChild("form", FormPage())
  20. application = Application("My Web Service")
  21. TCPServer(8880, Site(root)).setServiceParent(application)

test_post.py

Here is a simple test client using to send a POST request with some JSON data. I used Mark Pilgrim's as a reference.



  1. import httplib2
  2. from datetime import datetime
  3. import simplejson


  4. TESTDATA = {'woggle': {'version': 1234,
  5.                        'updated': str(datetime.now()),
  6.                        }}
  7. URL = ''

  8. jsondata = simplejson.dumps(TESTDATA)
  9. h = httplib2.Http()
  10. resp, content = h.request(URL,
  11.                           'POST',
  12.                           jsondata,
  13.                           headers={'Content-Type': 'application/json'})
  14. print resp
  15. print content


Run the web server

$ twisted -y webserver.py 

Run the test POST

$ python test_post.py 

twistd.log

Here are the results stored in twistd.log.

省略。。。。



from: http://www.saltycrane.com/blog/2010/08/twisted-web-post-example-json/


阅读(1816) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~