MicroService framework :: Resource

https://travis-ci.org/palankai/pyrs-resource.svg?branch=master https://coveralls.io/repos/palankai/pyrs-resource/badge.svg?branch=master&service=github Documentation Status

What is this package for

In the python world there are many RESTFul framework. Some of them based on Django others are based on Flask. I’ve tried some but I had the feeling, I want to learn one, the use with Django or Flask or even Odoo. And I don’t mention sometimes I found them not flexible enough. So, I’ve decided write my own independent framework what anybody can use in at least the mentioned 3 different worlds.

Nutshell (notice that, it would be the achivement)

from pyrs import resource
from pyrs.resource import GET

class UserResouce:

    @GET(response=ArrayOfUserSchema)
    def get_users(self):
        return User.objects.all()

    @PUT(path='/<int:user_id>', response=UserSchema, request=UserSchema)
    def update_user(self, user_id, body):
        user = get_object_or_404(User, pk=user_id)
        user.name = body['name']
        user.email = body['email']
        user.save()
        return user

app = resource.Application()
app.add('/user', UserResouce)

In this example I’ve shown Django (like) example. The schema is based on pyrs.schema. Even if I tend to use that framework, you would be able to use any other.

Features

  • Using simple classes or even functions (no inheritance)
  • Wrapped error handling, errors can be serialised
  • Extensible API
  • Works with python 2.7, 3.3, 3.4 (tested against these versions)
  • Hooks for extending the dispatching process

Installation

$ pip install pyrs-resource

Dependencies

See requirements.txt for details, but mainly depends on Werkzeug. I’m using that project routing capabilities. Also depends on pyrs.schema as I mentioned in nutshell section.

Important caveats

This code right now really in beta state. I plan to release soon as possible a completely working code, but right now it’s just shaping.

The ecosystem

This work is part of pyrs framework. The complete framework follow the same intention to implement flexible solution.

Contribution

I really welcome any comments! I would be happy if you fork my code or create pull requests. I’ve already really strong opinions what I want to achieve and how, though any help would be welcomed.

Feel free drop a message to me!

Contents:

Application

class pyrs.resource.base.App(parent=None, **config)[source]

Bases: pyrs.resource.base.Dispatcher

wsgi(request)[source]
class pyrs.resource.base.Directory(parent=None, **config)[source]

Bases: object

_add_class(path, resource, prefix='')[source]
_add_function(path, resource, prefix='')[source]
_make_rule(path, methods, endpoint)[source]
add(path, resource, prefix='')[source]
host = 'localhost'
match(path_info, method)[source]
parent
resources = None

Tuple should be presented as (‘/path’, Resource, [namespace])

root
setup()[source]
class pyrs.resource.base.Dispatcher(parent=None, **config)[source]

Bases: pyrs.resource.base.Directory

class Response(response=None, status=None, headers=None, mimetype=None, content_type=None, direct_passthrough=False)

Bases: werkzeug.wrappers.Response, pyrs.resource.gateway.CompatibilityMixin, pyrs.resource.gateway.ProducerMixin, pyrs.resource.gateway.ExceptionMixin

default_mimetype = 'application/json'
Dispatcher.dispatch(request, path=None, scope=None)[source]
classmethod Dispatcher.forward(scope, path, resource)[source]
class pyrs.resource.base.Scope(request, application)[source]

Bases: object

class Response(response=None, status=None, headers=None, mimetype=None, content_type=None, direct_passthrough=False)

Bases: werkzeug.wrappers.Response, pyrs.resource.gateway.CompatibilityMixin, pyrs.resource.gateway.ProducerMixin, pyrs.resource.gateway.ExceptionMixin

default_mimetype = 'application/json'
Scope.forward(resource, path='/')[source]
Scope.response

Resource

pyrs.resource.resource.DELETE(_func=None, **kwargs)[source]

Decorator function Ensure the given function will be available for DELETE method

pyrs.resource.resource.FORWARD(_func=None, path='/', forward=None)[source]

Ensure forwarding the request to an other resource

pyrs.resource.resource.GET(_func=None, **kwargs)[source]

Decorator function Ensure the given function will be available for GET method

pyrs.resource.resource.PATCH(_func=None, **kwargs)[source]

Decorator function Ensure the given function will be available for PATCH method

pyrs.resource.resource.POST(_func=None, **kwargs)[source]

Decorator function Ensure the given function will be available for POST method

pyrs.resource.resource.PUT(_func=None, **kwargs)[source]

Decorator function Ensure the given function will be available for PUT method

pyrs.resource.resource.RPC(_func=None, **kwargs)[source]

Decorator function Ensure the given function will be available for POST method This action tend to use as Remote procedure call

pyrs.resource.resource.endpoint(_func=None, path='/', **kwargs)[source]

Deadly simple decorator, add options to the given function. Can be user with or without any keyword arguments. The default options would contain the path and the name of the function. Based on configuration: conf.decorate

Response handling

Response handling

Error handling

exception pyrs.resource.errors.BadRequestError(message=None, errors=None, **details)[source]

Bases: pyrs.resource.errors.ClientError

Request cannot be processed because of an error.

error = 'BadRequest'
schema

alias of BadRequestErrorSchema

class pyrs.resource.errors.BadRequestErrorSchema(extend=None, **attrs)[source]

Bases: pyrs.resource.errors.ErrorSchema

_attrs = OrderedDict([('additional', False)])
_definitions = None
_fields = OrderedDict([('error', <pyrs.schema.types.String object at 0x7f005a8c2898>), ('error_description', <pyrs.schema.types.String object at 0x7f005a8c28d0>), ('error_uri', <pyrs.schema.types.String object at 0x7f005a8c2908>), ('message', <pyrs.schema.types.String object at 0x7f005a8c2940>), ('details', <pyrs.resource.errors.DetailsSchema object at 0x7f005a8c2978>), ('errors', <pyrs.schema.types.Array object at 0x7f005a8c2ac8>)])
to_raw(value, context=None)[source]
exception pyrs.resource.errors.ClientError(*args, **details)[source]

Bases: pyrs.resource.errors.Error

Generic Client Error. Normally the client errors have 4xx status codes.

status = 400
class pyrs.resource.errors.DetailsSchema(extend=None, **attrs)[source]

Bases: pyrs.schema.types.Object

Details part of the error schema. Additional properties possible.

_attrs = OrderedDict([('additional', True)])
_definitions = None
_fields = OrderedDict([('traceback', <pyrs.schema.types.Array object at 0x7f005a8c26d8>), ('args', <pyrs.schema.types.Array object at 0x7f005a8c27f0>)])
exception pyrs.resource.errors.Error(*args, **details)[source]

Bases: Exception

This is the base exception of this framework. The response based on this exception will be a JSON data

description = None

Description of error. Should give details about the error In the message it will appearing as error_description

details = None

None used as empty dict. Gives extra information about this error which could be parsed by the consumer of API.

error = None

Error code should be a string. If it’s not specified the class fully qualified name will be used

get_details(debug=False)[source]

Gives back detailed information about the error and the context. As this is part of the message should conform with the DetailsSchema.

get_headers()[source]

This method gives back the header property by default or an empty dict, but you can override, then provide special headers based on the context

get_status()[source]

This method gives back the status property by default which will be threated as HTTP status code. You can override, then provide your own status code based on the context.

headers = None

HTTP Response headers, (default None processed as empty)

schema

You can specify your schema class for validating your message By default the application default error schema the ErrorSchema will be used

alias of ErrorSchema

status = 500

HTTP status code (default=500)

uri = None

Reference for this error. You can pointing out a documentation which gives more information about how could this error happen and how could be possible to avoid

classmethod wrap(original)[source]

Wraps the exception gives back an Error instance. The created Error instance error property will be updated by the fully qualified name of the original exception. You could use it for Error instances as well, though is not recommended.

class pyrs.resource.errors.ErrorSchema(extend=None, **attrs)[source]

Bases: pyrs.schema.types.Object

Describe how the error response should look like. Goal of this schema is a minimalistic but usable error response.

_attrs = OrderedDict([('additional', False)])
_definitions = None
_fields = OrderedDict([('error', <pyrs.schema.types.String object at 0x7f005a8c2898>), ('error_description', <pyrs.schema.types.String object at 0x7f005a8c28d0>), ('error_uri', <pyrs.schema.types.String object at 0x7f005a8c2908>), ('message', <pyrs.schema.types.String object at 0x7f005a8c2940>), ('details', <pyrs.resource.errors.DetailsSchema object at 0x7f005a8c2978>)])
get_details(ex)[source]

Gives back detailed information about the error and the context. By default its an empty dictionary. The debug depends on the debug parameter should give back traceback information and the positional arguments of the exception. As this is part of the message should conform with the ErrorSchema.

to_raw(value, context=None)[source]
exception pyrs.resource.errors.InternalServerError(*args, **details)[source]

Bases: pyrs.resource.errors.Error

error = 'InternalServerError'
status = 500
exception pyrs.resource.errors.NotFound(*args, **details)[source]

Bases: pyrs.resource.errors.ClientError

error = 'NotFound'
status = 404

Hooks

Hooks in general the way to override amend the exist functionality of app. Even you could extend the app, sometimes much easier if you attach a hook like authentication hook and the will process the request, make request.auth available. But also you can create your own hook handling special header values or give special error handling strategy.

The Hook class provide the skeleton of any further hooks.

class pyrs.resource.hooks.Hook[source]

Bases: object

Hooks help to extend the functionality of application. The 3 hooks executed in different time of execution. This class should be the base class of any further hook.

exception(request, exception)[source]

If the function raise any exception it can be handled with this hook. return will be used as response if it gives back any (should be Response instance or None)

request(request)[source]

Executed when the request is created. It can amend the request. If has any return value it will be used as return value of the call, the the function will be not called. Can raise any exception and that will be treated as the function exception, in that case the function will be not called.

response(response)[source]

Executed after successful call of the function. Response object created and passed to the hook. Can modify the response or give back a new response. Have to return the response object.

Configuration

This module contains the default configurations. The pyrs.resource.base.App config will be based on these values.

pyrs.resource.conf.debug = False

You can get more information in response like traceback and args of exception

pyrs.resource.conf.decorate = '_endpoint'

This option will be used for decorators. Usage getattr(func, conf.decorate)

pyrs.resource.conf.host = 'localhost'

Default host for the application

pyrs.resource.conf.inject_app = False

Enable/disable injecting the base.App as keyword argument

pyrs.resource.conf.inject_app_name = 'app'

Name used for app injection

pyrs.resource.conf.inject_auth = False

Enable/disable injecting the request.auth as keyword argument

pyrs.resource.conf.inject_auth_name = 'auth'

With this name the auth will be injected

pyrs.resource.conf.inject_body = True

Enable/disable injecting the request body

pyrs.resource.conf.inject_cookies = False

Enable/disable injecting the cookies

pyrs.resource.conf.inject_cookies_name = 'cookies'

With this name the cookies will be injected

pyrs.resource.conf.inject_path = True

Enable/disable injecting the path arguments If a name provided the path arguments will be injected as specified

pyrs.resource.conf.inject_query = True

Enable/disable injecting the query arguments If a name provided the query arguments will be injected as specified

License

The MIT License (MIT)

Copyright (c) 2015 Csaba Palankai

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

Indices and tables