Introducting repoze.bfg.restrequest (technical) - mrtopf.demrtopf.de

Introducting repoze.bfg.restrequest (technical)

Should you be a Python developer, using repoze.bfg as web framework and need some way to distinguish between GET, POST, PUT and DELETE requests for a view you might want to have a look at repoze.bfg.restrequests.

What it gives you are 4 new Request types depending on which HTTP method is used for the request. A example for 2 views responding to the same URL but differently for GET and POST might look like follows:

from repoze.bfg.restrequest import IGETRequest, IPOSTRequest
from repoze.bfg.convention import bfg_view
from webob import Response

@bfg_view(request_type=IGETRequest, for_=models.IMyModel)
def my_view_get(context, request):
    return Response("GET\n")

@bfg_view(request_type=IPOSTRequest, for_=models.IMyModel)
def my_view_post(context, request):
    return Response("POST "+request.body+"\n")

(This also uses repoze.bfg.convention which is based on grokcore.component and automatically registers these views. The same can be accomplished with ZCML, check out the repoze.bfg.restrequest documentation.)

Assuming this is basically the standard project created you now can e.g. use curl to use different HTTP methods:

$ curl http://127.0.0.1:6543/
GET

$ curl http://127.0.0.1:6543/ -d "posttest"
POST posttest

You can find the package on pypi.

(If you need a more flexible way of attaching interfaces dynamically to a request you also might want to look at repoze.bfg.httprequest.)

Technorati Tags: , , ,

Kommentare sind geschlossen.