Python Lover(9)Twisted Basic - session and RESTful

PythonLover(9)TwistedBasic-sessionandRESTful

1.WSGI

http://twistedmatrix.com/documents/current/web/howto/web-in-60/wsgi.html

2.HTTPAuthentication

http://twistedmatrix.com/documents/current/web/howto/web-in-60/http-auth.html

3.Session

http://twistedmatrix.com/documents/current/web/howto/web-in-60/session-basics.html

fromtwisted.web.resourceimportResource

classShowSession(Resource):

defrender_GET(self,request):

return'Yoursessionidis:'+request.getSession().uid

classExpireSession(Resource):

defrender_GET(self,request):

request.getSession().expire()

return'Yoursessionhasbeenexpired.'

resource=ShowSession()

resource.putChild("expire",ExpireSession())

StarttheService

>twistd-nweb--path.--logfile./RestAPI.access.log

Visitthepagetogetthesessioninfo

http://localhost:8080/RestAPI.rpy

Visittheexpirethesession

http://localhost:8080/RestAPI.rpy/expire

StoreObjectintheSession

http://twistedmatrix.com/documents/current/web/howto/web-in-60/session-store.html

SessionEndings

http://twistedmatrix.com/documents/current/web/howto/web-in-60/session-endings.html

4.Restful

>gitclonehttps://github.com/iancmcc/txrestapi.git

>pythonsetup.pyinstall

Thismayworksinprojectsillycat-prest

OneMainFileRestAPI.pytohandleallthetraffic

fromtwisted.web.resourceimportResource

fromtwisted.web.serverimportSite

fromtwisted.internetimportreactor

fromBookAPIimportBookResource

bookResource=BookResource()

rootResource=Resource()

rootResource.putChild("book",bookResource)

site=Site(rootResource,timeout=None)

reactor.listenTCP(8888,site)

reactor.run()

OneModuleClassBookAPItohandlethetrafficinthatmodule

fromtxrestapi.methodsimportGET,POST,PUT,ALL,DELETE

fromtxrestapi.resourceimportAPIResource

classBookResource(APIResource):

@GET('^/book/(?P<id>[^/]+)')

defgetBook(self,request,id):

return'Pickuponebookwithid%s'%id

@GET('^/book')

defbooks(self,request):

return"books"

@PUT('^/book/(?P<id>[^/]+)')

defupdateBook(self,request):

return"Updatebookwithid%s"%id

@POST('^/book/(?P<id>[^/]+)')

defsaveBook(self,request,id):

return"Savebookwithid%s"%id

@DELETE('^/book/(?P<id>[^/]+)')

defdeleteBook(self,request,id):

return"Deletebookwithid%s"%id

@ALL('^/')

defdefault_view(self,request):

return"IfailtomatchotherURLs."

ThevisitsontheURLwillwork

http://localhost:8888/book/19343

References:

http://twistedmatrix.com/documents/current/web/howto/web-in-60/

restful

http://jacek99.github.io/corepost/doc/build/html/index.html

https://github.com/iancmcc/txrestapi

https://pypi.python.org/pypi/txrestapi

APIdocument

http://twistedmatrix.com/documents/current/api/index.html

projectstructure

http://stackoverflow.com/questions/193161/what-is-the-best-project-structure-for-a-python-application

相关推荐