Sunday, August 30, 2015

python web.py with REST



Below is a simple script to demo how to create a web server to demo REST feature with python.

create a xml file in the same directory where you run this script.

assume : web.py has been install

# pip install web.py


 user_data.xml :
===========
<users>
    <user id="1" name="Rocky" age="38"/>
    <user id="2" name="Steve" age="50"/>
    <user id="3" name="Melinda" age="38"/>
</users>

Run the script with port number :

# webapp.py 8888
http://0.0.0.0:8888/

open a web browser and http://localhost:8888/users

# webapp.py 8888
http://0.0.0.0:8888/
child user {'age': '38', 'id': '1', 'name': 'Rocky'}
child user {'age': '50', 'id': '2', 'name': 'Steve'}
child user {'age': '38', 'id': '3', 'name': 'Melinda'}
127.0.0.1:39952 - - [30/Aug/2015 18:33:05] "HTTP/1.1 GET /users" - 200 OK


============= webapp.py script ================

#!/usr/bin/env python
import web
import xml.etree.ElementTree as ET

tree = ET.parse('user_data.xml')
root = tree.getroot()

urls = (
    '/users', 'list_users',
    '/users/(.*)', 'get_user'
)

app = web.application(urls, globals())

class list_users:      
    def GET(self):
output = 'users:[';
for child in root:
                print 'child', child.tag, child.attrib
                output += str(child.attrib) + ','
output += ']';
        return output

class get_user:
    def GET(self, user):
for child in root:
if child.attrib['id'] == user:
   return str(child.attrib)

if __name__ == "__main__":
    app.run()


==================================================================

1 comment: