Home > AI > Backend > PythonTornado >

REST controller built on tornado


from tornado.web import Application, RequestHandler
from tornado.ioloop import IOLoop
import json

items = []

def get_json_arg(req_body, fields):
    """
    Gets argument from JSON
    """
    results = {}
    for i in fields:
        results[i] = json.loads(req_body).get(i)
    return results

class TodoItems(RequestHandler):

    def get(self):
        '''This function is to realize the retrieve function in REST API'''
        self.write({'items': items})


class TodoItem(RequestHandler):

    def post(self, _):
        '''This function is to realize the create function in REST API'''
        items.append(json.loads(self.request.body))
        self.write({'message': json.loads(self.request.body)})

    def delete(self, id):
        '''This function is to realize the delete function in REST API'''
        global items
        new_items = [item for item in items if item['id'] is not int(id)]
        items = new_items
        self.write({'message': 'Item with id %s was deleted' % id})

    def put(self, id):
        '''This function is to realize the update function in REST API'''
        global items
        result = [item for item in items if item['id'] == int(id)]
        if result:
            items.remove(result[0])
            item = get_json_arg(self.request.body, ['name'])
            item['id'] = int(id)
            items.append(item)
            self.json_response(item)
        self.write({'message': 'Item with id %s was updated' % id})

def make_app():
    urls = [
        (r"/", TodoItems),
        (r"/api/item/([^/]+)?", TodoItem),
    ]
    return Application(urls, debug=True)


if __name__ == '__main__':
  app = make_app()
  app.listen(9090)
  IOLoop.instance().start()

Related posts:
    No posts found.

Leave a Reply