Git Product home page Git Product logo

tornado-rest's Introduction

PyRestful

pyRestful is an API to develop restful services with Tornado Web Server. Changes were made from the last version to improve the API.

Last version works with Python 2, 3.5 and 3.7.

Installation

Python version 2.7, 3.5+ are required.

Note: We recommend using Python 3.5+.

Download the api from github (https://github.com/rancavil/tornado-rest/archive/master.zip).

Unzip the file tornado-rest-master.zip

 $ unzip tornado-rest-master.zip

Go to the directory and install.

 $ cd tornado-rest-master
 $ python setup.py install

Or you can install it using.

 $ pip install -U git+https://github.com/rancavil/tornado-rest.git

New release 0.5.1

It was added "syntax sugar" to define services.

 import tornado.ioloop
 import pyrestful.rest

 from pyrestful.rest import get,post

 class EchoService(pyrestful.rest.RestHandler):
      @get('/echo/{name}')
      def sayHello(self, name):
           return {'Hello':name}

 class BookService(pyrestful.rest.RestHandler):
      @post('/book')
      def create_book(self,book):
           # do something...
           return 'Book created...'

 class SomeService(pyrestful.rest.RestHandler):
      @post('/person',{'format' : 'json'}) # content-type (consumes and produces) will be application/json 
      def create_person_json(self,book):
           # do something with book in format json
           return {'status' : 'person created...'} 

If you want to see a complete example, you can go to demo folder and check person_service.py.

Example

The API allows developing a CRUD (Create, Read, Update and Delete) over the resources. In this example the resource is Customer.

First, start the service:

 $ python demos/customer_service.py

Note: you can see customer_service.py is in demos folder.

Creating a new Customer:

 POST: http://myserver.domain.com:8080/customer

 POST /customer HTTP/1.1
 Host: myserver.domain.com
 
 customer_name=Rodrigo&customer_address=Santiago

 POST it is equivalent to INSERT.

Read a Customer:

 GET: http://myserver.domain.com:8080/customer/{id}

 GET /customer/1 HTTP/1.1

 GET it is equivalent to SELECT (READ).

Update a Customer:

 PUT: http://myserver.domain.com:8080/customer/{id}

 PUT /customer/1 HTTP/1.1
 Host: myserver.domain.com
 
 customer_name=Rodrigo&customer_address=Santiago
 
 PUT it is equivalent to UPDATE.

Delete a Customer:

 DELETE: http://myserver.domain.com:8080/customer/{id}

 DELETE /customer/1 HTTP/1.1

 DELETE it is equivalent to DELETE.

PyRestful implements the verbs get, post, put and delete.

Echo Rest Service

This example implements an echo rest service (echo_service.py).

Write the next code and save echo_service.py file.

 import tornado.ioloop
 import pyrestful.rest

 from pyrestful import mediatypes
 from pyrestful.rest import get

 class EchoService(pyrestful.rest.RestHandler):
      @get(_path="/echo/{name}", _produces=mediatypes.APPLICATION_JSON)
      def sayHello(self, name):
           return {"Hello":name}

 if __name__ == '__main__':
      try:
           print("Start the echo service")
           app = pyrestful.rest.RestService([EchoService])
           app.listen(8080)
           tornado.ioloop.IOLoop.instance().start()
      except KeyboardInterrupt:
           print("\nStop the echo service")

You can execute the service.

 $ python echo_service.py

Then in a browser write the url.

 http://localhost:8080/echo/john

You should see the following output in your browser.

 {"Hello": "john"}

tornado-rest's People

Contributors

rancavil avatar sksavant avatar vodchella avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

tornado-rest's Issues

POST decorator can't consume nested dict object

Useful python library, but how to pass nested json object to POST decorator?

I tried to post some json params from REST client like POSTMAN:
{ "name": "John Doe", "details: { "address": "21st Street" } }

Here's my Server side code:

class User(object):
    name = str
    details = dict

class UserHandler(RestHandler):
   @post(_path="/user", _types=[User])
   def user(self, params):
         return params

gives me internal server error:

Internal Server Error : 'dict' object has no attribute 'dict'

Can you give me some example to consume nested dict object to POST decorator?

Can it support asyncio?

I want to use asynchronous methods in handler functions like this.

@get('/data')
async def get_data_list(self):
    await asyncio.sleep(1)
    return {
        'result': 'ok'
    }

I wonder if you could just modify it like this.

class RestHandler(tornado.web.RequestHandler):
    async def get(self):
        """ Executes get method """
        await self._exe('GET')
    # .....
    async def _exe(self, method):
        # .....
        response = operation(*p_values)
        if asyncio.isfuture(response) or asyncio.iscoroutine(response):
            response = await response

Thank You!

Can it support websocket server

I would like to add a hanlder file to the existing restful API to implement a websocket server

I want to share a port with other restful API

The code is as follows. How do I access the websocket server?

urls = [
passport.IndexHandler,
websocket.MsgServerHandler,
# (r"/websocket", websocket.MsgServerHandler),
]

class MsgServerHandler(tornado.websocket.WebSocketHandler, CommonHandler):
current_user_id = ''
waiters = {}
cache = []
cache_size = 200

URL with `.` not working well

@get('/data.asp')
def get_data(self):
    print('ok')
    return {
        'result': 'ok'
    }
>>> req = requests.get('http://127.0.0.1:6767/data.asp')
>>> req.status_code
200
>>> req.text
''

server

I need to use both customer_service and person_service,what should i do?

Capture exception

Hi, very useful library!
I need to capture the exception for report it (I'm using sentry) but the exception is captured and formatted as string so most information are lost. I only need to report the errors of my application (unhandled exceptions for example).

I saw that here is where the error is processed
rest.py

Override the method gen_http_error does not help because the exception is already transformed into a string. A method that receives the exception that I can override would be great, and by default this method format the exception as it does now.

I could send you a pull request (there are just a few lines) unless you have a way to do it.

Thank you!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.