Package: django-rester
Package for creating API with built-in validation and authenticationThis product is designed to build API endpoints of varying complexity
and nesting.The core is a view class - BaseApiView (the inheritor of the standard
django view)1. requirementsPython 3+Django 1.11+2. settingsDEFAULT settings (may be overridden):DJANGO_RESTER={'AUTH_BACKEND':'django_rester.rester_jwt','RESPONSE_STRUCTURE':False,'CORS_ACCESS':False,'FIELDS_CHECK_EXCLUDED_METHODS':['OPTIONS','HEAD'],'SOFT_RESPONSE_VALIDATION':False,}DJANGO_RESTER_JWT:{'SECRET':'secret_key','EXPIRE':60*60*24*14,# seconds'AUTH_HEADER':'Authorization','AUTH_HEADER_PREFIX':'jwt','ALGORITHM':'HS256','PAYLOAD_LIST':['username'],'USE_REDIS':False,# here can be an int value (redis db number)'LOGIN_FIELD':'username',# as default django login field}DJANGO_RESTER- django-rester settings:AUTH_BACKEND- authentication backend*RESPONSE_STRUCTURE- Either False or a dict with ‘success’,
‘message’ and ‘data’ as a valuesCORS_ACCESS- CORS control: True, False, ‘*’, hosts_stringFIELDS_CHECK_EXCLUDED_METHODS- methods, which will not be
processed with body structure checksSOFT_RESPONSE_VALIDATION- if True, response will not be cut
off if it will contain additional to response_structure fieldsDJANGO_RESTER_JWT- JWT authentication settings (in case of
‘RESTER_AUTH_BACKEND’ = ‘django_rester.rester_jwt’)*:SECRET- JWT secret keyEXPIRE- token expiration time (datetime.now() +
RESTER_EXPIRATION_DELTA)AUTH_HEADER- HTTP headed, which will be used for auth token.AUTH_HEADER_PREFIX- prefix for auth token
(“Authorization:<prefix> <token>”)ALGORITHM- cypher algorithmPAYLOAD_LIST- payload list for token encode (will take
specifieduserattributes to create token)USE_REDIS- use redis-server to store tokens or notLOGIN_FIELD- user login field (default is ‘username’ as in
django) ***3. built-in statusesfrom django_rester.status import ...slightly modified status.py
fromDRF, it’s simple and
easy to understand.Any statuses used in this documentation are described in that file.
*** ##### 4. built-in exceptions:from django_rester.exceptions import ...Exceptions, which will help
you to recognise errors related to django-resterclass ResterException(Exception)base django-rester exception, standard Exception inheritorclass ResponseError(Exception)ResponseError inheritor, added response status -
HTTP_500_INTERNAL_SERVER_ERRORclass ResponseBadRequest(ResponseError)ResponseError inheritor, response status changed to
HTTP_400_BAD_REQUESTclass ResponseServerError(ResponseError)ResponseError inheritorclass ResponseAuthError(ResponseError)ResponseError inheritor, response status changed to
HTTP_401_UNAUTHORIZEDclass ResponseOkMessage(ResponseError)ResponseError inheritoracceptable arguments: *, message=’’, data=None,
status=HTTP_200_OKclass ResponseFailMessage(ResponseError)ResponseError inheritoracceptable arguments: *, message=’’, data=None,
status=HTTP_500_INTERNAL_SERVER_ERRORclass ResponseBadRequestMsgList(ResponseError)ResponseError inheritoracceptable arguments: *, messages=None,
status=HTTP_400_BAD_REQUESTmessages could be list, tuple or string.class JSONFieldError(ResterException)ResterException inheritor, base JSONField exceptionclass JSONFieldModelTypeError(JSONFieldError)JSONField exception, raises when type of model parameter is not
validclass JSONFieldModelError(JSONFieldError)JSONField exception, raises when value of model parameter is not
validclass JSONFieldTypeError(JSONFieldError)JSONField exception, simple TypeError inside JSONField classclass JSONFieldValueError(JSONFieldError)JSONField exception, simple ValueError inside JSONField classclass BaseAPIViewException(Exception)BaseAPIView exception classclass RequestStructureException(BaseAPIViewException)raise if request structure is invalidclass ResponseStructureException(RequestStructureException)raise if response structure is invalid *** ##### 5. permission
classesfrom django_rester.permission import ...Permission classes created
to interact wih@permissions()decorator (good example of usage), or
in any other way you wantAll permission classes accepts only one argument oninit- django
viewrequestobject.All permission classes has 2 attributes, defined oninit:check: Bool - returnsTrueorFalseif request.user may or
may not access endpoint methodmessage: could be a string or list of messagesclass
BasePermissioncontains all base permission methods, it is not recommended to use
it directly in projectsclass IsAuthenticated(BasePermission)check =Trueif user authenticated and active, elseFalseclass IsAdmin(BasePermission)check =Trueif user authenticated and active and is_superuser,
elseFalseclass AllowAny(BasePermission)check =Truefor any user (even anonymous)6. built-in decoratorsfrom django_rester.decorators import ...@permissions()accepts permission class or list, tuple of classes.if check is passed, then user will be allowed to use endpointexample:class Example(BaseApiView):

    @permissions(IsAdmin)
    def post(request, request_data, *args, **kwargs):
        pass7. built-in viewsfrom django_rester.views import ...class BaseApiView(View)inherits from standard django view.class attributes:auth- authentication backend instancerequest_fields- request validator (use JSONField to build this
validator)response_fields- response validator (use JSONField to build
this validator)class HTTP methods (get, post, put, etc…) accepts next arguments:
request, request_data, *args, **kwargsrequest- standard django view request objectrequest_data- all received request parameters as json
serialized objectUser authentication with selected authentication backendclass
Login(BaseApiView)Could be used to authenticate user with selected authentication backend.Allowed method is ‘POST’ only.Requires username and password in request parameters (username
fieldname parameter may be set in settings)Returns token and HTTP_200_OK status code if authentication
success, error message and HTTP_401_UNAUTHORIZED if failedclass
Logout(BaseApiView)Could be used to logout (with redis support) or just to let know
frontend about logout process. Any view could be used the same way, here
is asimple example:app/views.py:fromdjango_rester.viewsimportBaseAPIViewfromdjango_rester.decoratorsimportpermissionsfromdjango_rester.exceptionsimportResponseOkMessagefromdjango_rester.permissionimportIsAdminfromdjango_rester.statusimportHTTP_200_OKfromapp.modelsimportModel# import Model from your applicationfromdjango_rester.fieldsimportJSONFieldclassTestView(BaseAPIView):request_fields={"POST":{"id":JSONField(field_type=int,required=True,),"title":JSONField(field_type=str,required=True,default='some_title'),"fk":[{"id":JSONField(field_type=int,required=True)}],}}response_fields={"POST":{"id":JSONField(field_type=int,required=True,),"title":JSONField(field_type=str,required=True,default='some_title'),# ...}}defretrieve_items():returnModel.objects.all()defcreate_item(title):item,cre=Model.objects.get_or_create(title=title)returnitem,cre@permissions(AllowAny)defget(self,request,request_data,*args,**kwargs):items=self.retrieve_items()response_data={...hereweshouldbuildsomeresponsestructure...}***returnresponse_data,HTTP_200_OK@permissions(IsAdmin)defpost(self,request,request_data,*args,**kwargs):title=request_data.get('title',None)# no need to check 'if title', because it is allready validated by 'available_fields'# ... here we will do some view magic with the rest request_dataitem,cre=self.create_item(title)ifnotcre:raiseResponseOkMessage(message='Item allready exists',data={'title':title})response_data={...hereweshouldbuildsomeresponsestructure...}***returnresponse_dataapp/urls.py:fromdjango.conf.urlsimporturlfrom.viewsimportTestViewurlpatterns=[url(r'^test/',TestView.as_view()),]8. built-in fieldsfrom django_rester.fields import ...class JSONFieldclass attributes:field_type- data type (int, float, str, bool)required- field is requireddefault- default value if not specifiedblank- may or may not be blankmodel- model for foreign relationsfield- field for foreign relationsmethods (public), with normal usage, you won’t need them in your code:check_type- validate type of JSONField valuevalidate- validate field value with parameters ****- There is only one authentication backend available for now -
RESTER_JWT**- BaseApiView is on active development stage, other attributes and
methods could be added soon***- automatic response structure build - one of the nearest tasksInstallation notespycurl (Mac OS)brewremovecurlbrewinstallcurl-opensslexportPYCURL_SSL_LIBRARY=opensslpipinstall--no-cache-dir--global-option=build_ext--global-option="-L/usr/local/opt/openssl/lib"--global-option="-I/usr/local/opt/openssl/include"--compile--install-option="--with-openssl"pycurl