TwistedFate 2015-09-16
PythonLover(7)TwistedBasic-ErrorHandling,Post,rpyScripts
1.ErrorHandling
http://twistedmatrix.com/documents/current/web/howto/web-in-60/error-handling.html
fromtwisted.web.serverimportSite
fromtwisted.web.resourceimportResource
fromtwisted.internetimportreactor
fromtwisted.web.resourceimportNoResource
fromcalendarimportcalendar
classCalendar(Resource):
defgetChild(self,path,request):
try:
year=int(path)
exceptValueError:
returnNoResource()
else:
returnYearPage(year)
classYearPage(Resource):
def__init__(self,year):
Resource.__init__(self)
self.year=year
defrender_GET(self,request):
return"<html><body><pre>%s</pre></body></html>"%(calendar(self.year),)
root=Calendar()
factory=Site(root)
reactor.listenTCP(8880,factory)
reactor.run()
2.CustomResponseCodes
http://twistedmatrix.com/documents/current/web/howto/web-in-60/custom-codes.html
ThatisatotalcustomResource.
fromtwisted.web.serverimportSite
fromtwisted.web.resourceimportResource
fromtwisted.internetimportreactor
classPaymentRequired(Resource):
defrender_GET(self,request):
request.setResponseCode(402)
return"<html><body>Pleaseswipeyourcreditcard.</body></html>"
root=Resource()
root.putChild("buy",PaymentRequired())
factory=Site(root)
reactor.listenTCP(8880,factory)
reactor.run()
3.HandlingPOSTs
http://twistedmatrix.com/documents/current/web/howto/web-in-60/handling-posts.html
fromtwisted.web.serverimportSite
fromtwisted.web.resourceimportResource
fromtwisted.internetimportreactor
importcgi
classFormPage(Resource):
defrender_GET(self,request):
return"""
<html>
<body>
<formmethod="POST">
<inputname="the-field"type="text"/>
</form>
</body>
</html>"""
defrender_POST(self,request):
return"""
<html>
<body>Yousubmitted:%s</body>
</html>
"""%(cgi.escape(request.args["the-field"][0]),)
root=Resource()
root.putChild("form",FormPage())
factory=Site(root)
reactor.listenTCP(8888,factory)
reactor.run()
cgiisusingheretodealwiththerequest.args.
4.OtherRequestBodies
http://twistedmatrix.com/documents/current/web/howto/web-in-60/other-request-bodies.html
Nottheargsattribute,butthecontentattribute.
Wefetchtherequestbodydirectlyfromrequest.content.
classFormPage(Resource):
defrender_POST(self,request):
return"""
<html>
<body>Yousubmitted:%s</body>
</html>
"""%(cgi.escape(request.content.read()))
5.rpyscripts
http://twistedmatrix.com/documents/current/web/howto/web-in-60/rpy-scripts.html
rpyisasourcefilewhichdefinesaresourceandcanbeloadedintoatwistedwebserver.
Thepurposeofthisisthatwedon’thavetowritecodetocreatethesiteorsetupalisteningportwiththereactor.
PreparethefileRestAPI.rpy
importtime
fromtwisted.web.resourceimportResource
classClockPage(Resource):
isLeaf=True
defrender_GET(self,request):
return"""
<html>
<body>
%s
</body>
</html>
"""%(time.ctime(),)
resource=ClockPage()
Startthecommand
>twistd-nweb--path.
Visitthepage
http://localhost:8080/RestAPI.rpy
Tips:
CheckandInstallTwistedonubuntu
CheckmyPythonVersion
>python-V
Python2.7.3
DownloadtheSource
>wgethttp://twistedmatrix.com/Releases/Twisted/15.4/Twisted-15.4.0.tar.bz2
>tar-xvfTwisted-15.4.0.tar.bz2
Installtwisted
>pythonsetup.pyinstall
ErrorMessage:
File"setup.py",line13,in<module>
importsetuptools
ImportError:Nomodulenamedsetuptools
Solution:
>sudoapt-getinstallpython-setuptools
Itworks.butIsawanotherErrorMessage:
twisted/test/raiser.c:4:20:fatalerror:Python.h:Nosuchfileordirectory
compilationterminated.
error:command'gcc'failedwithexitstatus1
Solution:
>sudoapt-getinstallpython-dev
Forthepermissionissue,Iusesudotoinstallthat.
Successfullyinstalltwisted.
Itrytouseprinttwisted.versiontoverifytheinstallation.Butitdoesnotwork.ButIcanrunallthetwistedclassesinpython.
Oh,Ineedtoimporttwistedfirst.
>>>importtwisted
>>>printtwisted.version
[twisted,version15.4.0]
References:
http://twistedmatrix.com/documents/current/web/howto/web-in-60/error-handling.html