Digital Davide
Saturday, January 13, 2007
  REST Web Services at your fingertips with Python and twisted

Digg!


(Foto by Very Good With Computers)

Why using Soap? Soap is so complex and so heavy to implement, to test and to deploy. You have an alternative: you can use REST. It is not a brand new protocol. REST was already here, from the beginning of the Web. You don't trust me? Read this.



In very few words, every web application can be designed around a good data definition and on 4 fundamental operations: create new data, edit existing data, read data, delete data. You can trust me: you have these operations in HTTP: POST, PUT, GET and DELETE. Your data may represent orders, user profiles, bookings and they are usually defined in XML. Or not? In some cases other formats can be used more convenientely. For instance JSON if your client is a web browser. JSON is a format that uses Javascript literals to serialize data. Moreover, Javascript and Python have some syntax in common. Expression like these:

a={“x”:32 , “y”:25}

b=[23,33, “I'm a string”]

c=[[34,35,36],[44, “s”]]


... are valid both in Python and Javascript. This fact suggests that with a little effort we can write web applications using Python in the server side and Ajax in the client side.

Let's see an example. We can build a very simple web service to manage a list of people. The operations are: create a user, see a user profile, remove a user. To do that we need two URLs and the 4 HTTP methods.


http://myserver/listUsers

to be used only in GET

http://myserver/user?name=davide

where

POST creates a new user davide

GET reads the profile of davide

PUT modify the record for user davide

DELETE remove the user davide from the list



Here you have the code, that depends on Twisted.

To test GET and POST you can use a HTML form. To test PUT and DELETE you need to make some Ajax call or to use another client able to implement these methods.

from twisted.internet import reactor
from twisted.web import server, resource
from twisted.web.static import File

user1={"name":"john", "surname":"smith", "age":23, "email":"john@foo.bar"}
user2={"name":"davide", "surname":"carboni", "age":35, "email":"davide@foo.bar"}
user3={"name":"stefano", "surname":"sanna", "age":32, "email":"stefano@foo.bar"}

users=[user1,user2,user3]

class Root(resource.Resource):
isLeaf=False
def render_GET(self, request):
return "Arkanoid?"





class ListUsers(resource.Resource):
isLeaf=True
def render_GET(self, request):
userList=[us['name'] for us in users]
return str(userList)




class User(resource.Resource):
isLeaf=True
def render_GET(self, request):
name=request.args['name'][0]
record=filter(lambda(x): name==x['name'], users)[0]
return str(record)



def render_POST(self,request):
record=eval(request.content.read())
#WARNING. USING EVAL ON USER TRANSMITTED DATA
#IS A SEVERE SECURITY FLAW.
#USE A PARSER LIKE SIMPLEJSON INSTEAD

users.append(record)
return 'http://localhost/user?name=%s' % (record['name'])


def render_PUT(self,request):
name=request.args['name'][0]
newrecord=eval(request.content.read())
#WARNING. USING EVAL ON USER TRANSMITTED DATA
#IS A SEVERE SECURITY FLAW.
#USE A PARSER LIKE SIMPLEJSON INSTEAD

oldrecord=filter(lambda(x): name==x['name'], users)[0]

for key in oldrecord:
oldrecord[key]=newrecord[key]

return "OK"

def render_DELETE(self,request):
name=request.args['name'][0]
record=filter(lambda(x): name==x['name'], users)[0]
users.remove(record)
return "OK"



if __name__ == "__main__":
root=Root()
root.putChild("user",User())
root.putChild("listUsers",ListUsers())
root.putChild("d",File("."))
site = server.Site(root)
reactor.listenTCP(8000, site)
reactor.run()

Labels: , , , , , , , ,

 
Comments:
If you want to see the "Arkanoid?" when opening http://localhost:8000, set

isLeaf=False

in Root.
 
Who knows where to download XRumer 5.0 Palladium?
Help, please. All recommend this program to effectively advertise on the Internet, this is the best program!
 
Better yet:

omit the isLeaf stuff (defaults to False anyways; should have been True in my previous post)

Instead overwrite the getChild method of Root like this:

class Root(resource.Resource):
    def render_GET(self, request):
        return "Arkanoid?"

    def getChild(self, name, request):
        if name == "":
            return self
        return Resource.getChild(self, name, request)

This way a request like http://localhost:8000/ will yield "Arkanoid?". Nested URLS like http://localhost:8000/listUsers/ will work too.

See Twistedweb Howto.

I hope this is indented. Used lots of nbsp tags. Why does blogger.com disallow pre and code tags?
 
Post a Comment

Subscribe to Post Comments [Atom]



Links to this post:

Create a Link



<< Home
Non se ne può piu' ...\\ abbasso i blogger

My Photo
Name:

Questo e' un blog ed e' un assedio psichico neurologico. Per le controindicazioni consultate il vostro medico analista webologo. Puo' avere effetti indesiderati e decorso demenziale. Qui si parla spesso di tecnologia e molto raramente di politica e società. Le opinioni espresse in questo blog sono opinioni personali dell'autore e non riflettono in nessun modo opinioni e posizioni di persone, organizzazioni e società in qualsiasi modo in relazione con l'autore

Archives
04/25/06 / 05/12/06 / 05/13/06 / 05/14/06 / 05/19/06 / 05/23/06 / 05/25/06 / 05/27/06 / 05/31/06 / 06/01/06 / 06/07/06 / 06/09/06 / 06/10/06 / 06/11/06 / 06/13/06 / 06/14/06 / 06/16/06 / 06/17/06 / 06/26/06 / 06/28/06 / 06/29/06 / 06/30/06 / 07/03/06 / 07/05/06 / 07/06/06 / 07/07/06 / 07/09/06 / 07/10/06 / 07/12/06 / 07/13/06 / 07/16/06 / 07/17/06 / 07/19/06 / 07/21/06 / 07/25/06 / 07/27/06 / 08/31/06 / 09/05/06 / 09/08/06 / 09/13/06 / 09/19/06 / 09/20/06 / 09/28/06 / 10/01/06 / 10/03/06 / 10/04/06 / 10/07/06 / 10/10/06 / 10/16/06 / 10/18/06 / 10/20/06 / 10/22/06 / 10/24/06 / 10/25/06 / 10/26/06 / 10/30/06 / 11/02/06 / 11/06/06 / 11/11/06 / 11/14/06 / 11/17/06 / 11/21/06 / 11/22/06 / 11/25/06 / 12/15/06 / 12/18/06 / 12/19/06 / 12/21/06 / 01/04/07 / 01/10/07 / 01/13/07 / 01/15/07 / 01/20/07 / 01/21/07 / 02/05/07 / 02/12/07 / 04/20/07 / 05/14/07 / 06/08/07 / 06/29/07 / 01/20/08 / 02/04/08 / 02/13/08 / 03/03/08 / 03/14/08 / 07/13/08 / 07/17/08 / 07/18/08 / 07/19/08 / 09/30/08 / 12/16/08 / 01/18/09 / 01/19/09 / 01/21/09 / 02/03/09 / 02/04/09 / 05/20/09 / 06/16/09 / 06/17/09 / 06/20/09 / 06/22/09 / 06/25/09 / 06/26/09 / 06/29/09 / 06/30/09 / 07/01/09 / 07/02/09 / 07/03/09 / 07/06/09 / 07/10/09 / 07/13/09 / 07/14/09 / 07/15/09 / 07/30/09 / 07/31/09 / 08/07/09 / 09/07/09 / 09/24/09 / 04/10/10 / 04/28/10 / 05/29/10 / 08/29/10 / 12/24/10 / 07/08/13 /


Powered by Blogger

Subscribe to
Posts [Atom]