[Twisted-Python] How to design REST API with Twisted?

Glyph Lefkowitz glyph at twistedmatrix.com
Thu Nov 5 15:02:53 MST 2015


> On Nov 5, 2015, at 1:28 AM, Wang Yan <snailcoder at 163.com> wrote:
> 
> Thank you to remind me of Klein. I'm very new to Twisted and Klein. What I've known is that Klein is a little like Flask, with which I can implement a UserAPI as follows:
>     
>     from flask import Flask
>     from flask.ext.restful import Api, Resource
> 
>     api = Flask(__name__)
>     api = Api(app)
> 
>     class UserAPI(Resource):
>         def get(self, user_id):
>             pass
> 
>         def post(self, user_id):
>             pass
> 
>     api.add_resource(UserAPI, '/users/<int:id>', endpoint='user')
> 
> Is there any similar usage in Klein? 

Yes; in fact this extension for Flask is similar to how twisted.web works internally.  I think you're looking for something like this:

from klein import run, route

from twisted.web.resource import Resource

class User(Resource, object):
    def __init__(self, user_id):
        super(User, self).__init__()
        self.user_id = user_id
    def render_GET(self, request):
        pass
    def render_POST(self, request):
        pass

@route("/users/<int:user_id>")
def user(request, user_id):
    return User(user_id)

run("localhost", 8080)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: </pipermail/twisted-python/attachments/20151105/884fc812/attachment-0002.html>


More information about the Twisted-Python mailing list