Package: cosmicray
Cosmicray is a simple and high level http client API development framework. It provides the basic building blocks for
defining enpoints, handling a request response and automatically converting the result into to Models.Motivation:Ease of useConfigureability and customization on every levelNamespace different backends (one client to rule them all)Separate route definitions / response handling from models or “business logic”Ability to validate requests before making themAuthenticate each request as neededAbility to associate routes to modelsWarningCosmicray is under developmentInstall$ pip install cosmicrayQuick startCreate App>>>fromcosmicrayimportCosmicray>>>api=Cosmicray('myapp',domain='http://mydomain.com')Define routes and response handlersUsing the app we created, we can now add routes for it and define a response handler for each one. The response handler is simply a regular function that accepts a single argument of typerequests.Responseand returns the processed result.>>>@api.route('/v1/dogs/{id}',['GET','POST','PUT','DELETE'])>>>defdogs(response):...returnresponse.json()The decoratorapi.routecreates an instance ofcosmicray.Routenameddogsand stores the given function internally as the response handler.Instances ofcosmicray.Routeare callable and accept parameters:model_cls: Optional: Class that implements_make(cls, response)classmethod.**kwargs: Keyword arguments.urlargs: Mapping for url formatting argumentsheaders: Mapping for headersparams: Mapping for query parametersdata,json,files: Request bodyauthenticator: Authenticator callback&rest: Requests keyword argumentsWhen and instance ofcosmicray.Routeis called, it returns aRequestobject and with this you can:Use functions defined for each http method (ex:get(),post(),put(),delete())Override any parameters passed in (ex:params,headers, etc.) with settersAutomatically validates given parameters against the defined parameters on theRouteAuthenticates the request, if the app was configured with an authenticatorAfter the response is handled by the response handler, the result is automatically mapped to the model class, if one was providedHow to make requests>>>dogs().get()>>>dogs(urlargs={id:12345}).get()>>>dogs(json={'name':'Manu'}).post()>>>dogs(urlargs={'id':12345},json={'age':4}).put()>>>dogs(urlargs={'id':12345}).delete()To specify request parameters>>>dogs(params={'breed':'husky'},...headers={'Content-Type':'application/json'}).get()Authenticating requestsOften you’ll need to authenticate requests to access private resource and Cosmicray has a built-in mechanism to perform this step.>>>defauthenticator(request):...ifnotrequest.is_request_for(login):...auth=login(json={'username':'me','password':'mysecret'}).post()...returnrequest.set_headers({'X-AUTH-TOKEN':auth['token']})...returnrequest...>>>@api.route('/oauth',['POST'])...deflogin(response):..."""Get an auth token for the given credentials"""...returnresponse.json()...>>>@api.route('/private/resource',['GET'])...defprivate_resource(response):..."""Must be authenticated to access this"""...returnresponse.json()...>>>api.configure(authenticator=authenticator)>>># Now the private resourse will be automatically updated to include auth headers>>>private_resource.get()ModelsBasicsCosmicray ships with a built-in Model classThis base class is bound to a specific route handler and defines all the fields that would get mapped to a response or be part as the payload forpostandputrequestsIt automatically uses its defined fields as url parameters and as request bodyProvides functions to make http calls (ex:get,create,update,delete)You can override default behavior, such as create/update paylods>>>fromcosmicray.modelimportModel>>>classDog(Model):...__route__=dogs...__slots__=[...'id',...'name',...'breed',...'age'...]>>>manu=Dog(name='Manu',age=4).create()>>>manu.breed='Husky'>>>manu.update()>>>manu.delete()>>>manu=Dog(id=12345).get()>>>alldogs=Dog().get()Relationships with other models/routes>>>fromcosmicray.modelimportrelationhip,Model,ModelParam>>>classCat(cosmicray.model.Model):...__route__=cats...__slots__=[...'id',...'name',...'age'...]...friends=relationhip('Friend',urlargs={'id':ModelParam('id')})If you don’t want to usecosmicray.Modelas your base, you can define your own OR
even use just usecollections.namedtupleas the model.>>>classMyModel(object):...@classmethod...def_make(cls,response):...obj=cls()......dostuffwiththeresponse...returnobj