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
-
"""
-
-
-
-
usage:
-
$ twistd -y webserver.py
-
"""
-
-
-
from pprint import pprint
-
from twisted.application.internet import TCPServer
-
from twisted.application.service import Application
-
from twisted.web.resource import Resource
-
from twisted.web.server import Site
-
-
-
class FormPage(Resource):
-
def render_GET(self, request):
-
return ''
-
-
def render_POST(self, request):
-
pprint(request.__dict__)
-
newdata = request.content.getvalue()
-
print newdata
-
return ''
-
-
-
root = Resource()
-
root.putChild("form", FormPage())
-
application = Application("My Web Service")
-
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.
-
import httplib2
-
from datetime import datetime
-
import simplejson
-
-
-
TESTDATA = {'woggle': {'version': 1234,
-
'updated': str(datetime.now()),
-
}}
-
URL = ''
-
-
jsondata = simplejson.dumps(TESTDATA)
-
h = httplib2.Http()
-
resp, content = h.request(URL,
-
'POST',
-
jsondata,
-
headers={'Content-Type': 'application/json'})
-
print resp
-
print content
Run the web server
$ twisted -y webserver.py
Run the test POST
twistd.log
Here are the results stored in twistd.log.
省略。。。。
from: http://www.saltycrane.com/blog/2010/08/twisted-web-post-example-json/
阅读(1879) | 评论(0) | 转发(0) |