[Cubicweb] Pyramid and REST

Christophe de Vienne christophe at unlish.com
Mon Jun 8 15:06:45 CEST 2015



Le 08/06/2015 14:03, Rabah Meradi a écrit :
> On Wed, 2015-06-03 at 09:38 +0200, Christophe de Vienne wrote:
>> I just had a quick look.
>>
>> We need to define a standard route for entities, that match
>> /etype/*traverse. The nature of the context has to be discussed, as we
>> have different options to explore.
>> This route would used by any view that work on the etypes or entities,
>> including your 'delete' view.
>>
>> I think this route should be defined in pyramid-cubicweb, so any cube
>> can add views on it.
> 
> Is it possible to use pyramid traversal for this? I don't know if it's
> possible otherwise, but to use all the power of the pyramid traversal we
> must adapt our resources. In our case add the __getitem__ method to the
> entity object. 

Yes it is possible to use pyramid traversal, and I think we should do it.

It does not mean we need to use the entity object as a resource. I think
some specific resources that may give access to the actual entity or
entitytype are better suited as they would avoid unnecessary access to
the database in some cases.

We would probably need a specific predicate for the route. What I have
in mind looks like this (it is merely an illustration, an actual
implementation will need to support other things):


class EntityResource(object):
    def __init__(self, request, etype, eid):
        self.request = request
        self.etype = etype
        self.eid = eid

    def rset(self):
        return request.cw_cnx.find(self.etype, eid=self.eid)


class ETypeResource(object):
    def __init__(self, request):
        self.etype = request.matchdict['etype']

    def __getitem__(self, eid):
        return EntityResource(self.etype, eid)


config.add_route_predicate('cw_is_etype', ...)
config.add_route(
    'cwentities', '/{etype}/*travers',
    factory=ETypeResource, cw_is_etype=True)


@view_config(
    route_name='cwentities',
    context=EntityResource,
    http_method='delete'):
def delete_entity(context, request):
    context.rset().one().cw_delete()


Based on this route, we would also handle the primary and edit views easily:

@view_config(
    route_name='cwentities',
    context=EntityResource,
    method='get')
def edit_view(context, request):
    pyramid_cubicweb.core.render_view(request, 'primary')


@view_config(
    name='edit',
    route_name='cwentities',
    context=EntityResource)
def edit_view(context, request):
    pyramid_cubicweb.core.render_view(request, 'edit')


> 
>> Meanwhile, the routes you define automatically will do the work, but
>> with a pretty high cost.
> 
> Can you explain why there will be a high cost?
> 

Basically: lots of routes where one should suffice. It bloats the routes
namespace. It would make it a pain to use a different prefix for example.



More information about the Cubicweb mailing list