Saravanan666/pypi-org huggingface dataset:
Package: drf_lighten
DRF LightenPurposeEven if we call the same end point at multiple places, the information we want
from the response varies greatly. DRF Lighten makes it possible to specify and
get only the data you want.Installationpip install drf_lightenUsage# serializers.pyfromappimportmodelsfromdrf_lighten.serializersimportDynamicFieldsMixinfromrest_frameworkimportserializersclassUserSerializer(DynamicFieldsMixin,serializers.HyperlinkedModelSerializer)classMeta:model=models.Userfields="__all__"classProfileSerializer(DynamicFieldsMixin,serializers.HyperlinkedModelSerializer)user=UserSerializer(read_only=True)classMeta:model=models.Profilefields="__all__"# views.pyfromappimportmodelsfromdrf_lighten.viewsimportDynamicFieldsMixinfromrest_frameworkimportviewsets# …classProfileViewSet(DynamicFieldsMixin,viewsets.ModelViewSet):queryset=models.Profile.objects.all()serializer_class=serializers.ProfileSerializerExampleshttps://localhost:8000/profiles/[{"url":"https://localhost:8000/profiles/22/","picture":"https://localhost:8000/media/22.jpg","phone_number":"+251-911-11-11-11","user":{"url":"https://localhost:8000/users/22/","user_name":"jupi2142","email":"test@gmail.com","first_name":"Henock","last_name":"Tesfaye"},"posts":["https://localhost:8000/posts/77/","https://localhost:8000/posts/78/","https://localhost:8000/posts/79/","https://localhost:8000/posts/79/","https://localhost:8000/posts/99/"]}]https://localhost:8000/profiles/?fields=["url", "picture", {"user": ["url", "username"]}][{"url":"https://localhost:8000/profiles/22/","picture":"https://localhost:8000/media/22.jpg","user":{"url":"https://localhost:8000/users/22/","user_name":"jupi2142"}}]ConfigurationIf you want to use different query params than the ones provided, you can go to your django project's settings and do thatDRF_LIGHTEN_INCLUDE='fields'DRF_LIGHTEN_EXCLUDE='exclude'
Package: drf-link-header-pagination
djangorestframework-link-header-paginationOverviewProvide pagination using aLinkHTTP header as described inGitHub's REST API documentation.This pagination style accepts a single page number in the request query parameters. The response uses an HTTP header calledLinkto provide the URLs for the next, previous, first, and last pages. If you are using Python'sRequestslibrary to make the request, this header is automatically parsed for you as describedhere.Request:GET https://api.example.org/accounts/?page=4Response:HTTP 200 OK
Link: <https://api.example.org/accounts/>; rel="first", <https://api.example.org/accounts/?page=3>; rel="prev", <https://api.example.org/accounts/?page=5>; rel="next", <https://api.example.org/accounts/?page=11>; rel="last"

[
   {
       "id": 1,
       "name": "item one",
   },
   ...
]RequirementsPython (3.7+)Django (3.2+)Django REST Framework (3.11+)InstallationInstall usingpip:$pipinstalldjangorestframework-link-header-paginationSetupAdddrf_link_header_paginationto your project'sINSTALLED_APPSsetting.To enable theLinkHeaderPaginationstyle globally, use the following configuration, modifying thePAGE_SIZEas desired:REST_FRAMEWORK={'DEFAULT_PAGINATION_CLASS':'drf_link_header_pagination.LinkHeaderPagination','PAGE_SIZE':100}OnGenericAPIViewsubclasses you may also set thepagination_classattribute to selectLinkHeaderPaginationon a per-view basis.Other pagination classes that are available are:LinkHeaderCursorPagination: This is similar to the normalCursorPaginationclass but using theLinkheader to return only thenextand/orprevlinks. Thefirstandlastlinks are unavailable.LinkHeaderLinkResponseCursorPagination: This is similar toLinkHeaderCursorPagination, but in addition to thenextand/orprevURL's being in theLinkheader, the content of the response body is updated to include them as well. The body will be an object with the keysnext(the next page's URL or None),previous(the previous page's URL or None), andresults(the original content of the body).LinkHeaderLimitOffsetPagination:Uses theLimitOffsetPaginationpagination class from DRFto supportoffsetandlimitparameters instead ofpageto indicate offset into the queryset.ConfigurationThe configuration is the same as forPageNumberPagination.TestingUse the excellenttoxtesting tool to run the tests
against all supported versions of Python and Django. Install tox
globally, and then simply run:$tox
Package: drf-link-navigation-pagination
DRF Link Navigation PaginationYet anotherthirdy party package for DRF Pagination.This package adds support to some headers that allow you to configure the behaviour of the LimitOffsetPagination class.X-Drf-Change-DomainIf you want to change de host address located onnextandpreviousfields, then this is the right thing to you. Take this body as an example:{"links":{"next":"http://localhost/api/v1/entities/?limit=1&offset=2","previous":"http://localhost/api/v1/entities/limit=1"},"count":100,"results":[{"id":"bc6c6868-4e4d-4381-a785-f353ee7ecce5"}]}Using a reverse proxy (like AWS API Gateway) to intermediate between your API, addingX-Drf-Change-Domain=chumacoheader to the request will make the client receive the following:{"links":{"next":"http://chumaco/api/v1/entities/?limit=1&offset=2","previous":"http://chumaco/api/v1/entities/limit=1"},"count":100,"results":[{"id":"bc6c6868-4e4d-4381-a785-f353ee7ecce5"}]}X-Drf-Max-Pagination-SizeThis header allows you to define different limits to the pagination depending on the gateway you are exposing your API.
For example. Forclient Awe allow a max of50entries, forclient Bwe allow a max of100you can by injecting
this header on the client's requests.If for some reason the client exceeds the limit he will receive a Bad Request Error:{"detail":"Bad limit value sent.","error":{"code":"bad_limit_value"},"type":"API_EXCEPTION"}Otherwise the default paginated  response is generated:{"links":{"next":"https://chumaco/api/v1/entities/?limit=1&offset=2","previous":"https://chumaco/api/v1/entities/limit=1"},"count":100,"results":[{"id":"bc6c6868-4e4d-4381-a785-f353ee7ecce5"}]}Configuration processTo use this package after installing you need to use it's pagination class. in yoursettings.pydo the following:REST_FRAMEWORK={"DEFAULT_PAGINATION_CLASS":"drf_link_navigation_pagination.LinkNavigationPagination",...}TestsIn order to execute the tests:pipenv run tox
Package: drf-lookup-fields
Lookup FieldsThis package provides utils for changing lookup fields in requests to Django Rest Framework endpoints. It supports choosing lookup field for identifier of endpoint and identifiers used in related fields of serializers.Per field lookup usageData for field should be supplied inContent-Lookup-FieldsHTTP header as base64 encoded json object where keys are serializer fields names (if nested use dotted notation) and values are intended lookup fields:{"some_field":"uuid","other.nested.field":"pk",}Fieldfromlookup_fields.fieldsimportCustomizableLookupRelatedFieldfromrest_frameworkimportserializersclassSerializer(serializers.ModelSerializer):field=CustomizableLookupRelatedField(lookup_fields={'some_field':serializers.CharField(),'uuid':serializers.UUIDField(),'other_field':serializers.IntegerField(),'another_field_with_custom_filter_lookup_suffix':{'field':serializers.CharField(max_length=20),'filter_lookup_suffix':'__icontains',}},no_pk_lookup=True,default_lookup_field_name='uuid',)default_lookup_field_name is 'pk', integer pk field is always added to lookup_fields. If you don't want this behavior set no_pk_lookup to True. Even then you can still add pk to lookup_fields when instantiate field.You can specify optional parameters to lookup_fields by passing a dict instead of Field instance. Field has to be passed under 'field' key.SerializerSerializers usesCustomizableLookupRelatedFieldas default related field.fromlookup_fields.fieldsimportCustomizableLookupRelatedFieldfromrest_frameworkimportserializersclassSerializer(CustomizableLookupRelatedField):classMeta:model=SomeModelfields=('relation',)extra_kwargs={'relation':{'lookup_fields':{'some_field':serializers.CharField(),},},}View mixin usageName of lookup field should be supplied inLookup-FieldHTTP header.Viewfromlookup_fields.viewsimportCustomizableLookupFieldMixinfromrest_framework.genericsimportGenericAPIViewclassView(CustomizableLookupFieldMixin,GenericAPIView):ALLOWED_LOOKUP_FIELDS=['pk','uuid','some_field',WithPermissions('other_field',permissions=['some_app.can_use_other_field_as_lookup_field'],)]LOOKUP_FIELD_VALIDATORS={'some_field':[validator],}LicenseThe Django Rest Framework Lookup Fields package is licensed under theFreeBSD
License.
Package: drf-madprops
drf-madpropsDRF library of helpers to operate on lists of resource properties as dictsWritten and used by the folks at Yola to support ourfree website builder.OverviewIt's a typical case for relational DBs when some table (e.g. User) is
extended via subordinate key-value table (e.g. UserPreference). This allows
to dynamically add/delete fields to User (stored in UserPreference).
Usually those property models have very simple structures, e.g:classUserPreference(models.Model):id=models.AutoField()user=models.ForeignKey(User,related_name='preferences')name=models.CharField()value=models.CharField)But it's not very convenient to expose/operate on them via standard DRF
serializers.  We'll get something like:[{"id":"id1","user":"user1","name":"property1","value":"value1"},{"id":"id2","user":"user1","name":"property2","value":"value2"}...]This library contains two base classes for property's serializers (for cases
when properties are exposed as separate resource and as nested resource) which
allows to retrieve/operate on parent resource properties as dicts. For example,
instead of representation listed above, we'll get something like:{"property1":"value1","property2":"value2",...}UsageAdditional meta optionsread_only_props: list of property names, which values cannot be changed
via serializer.json_props: list of property names, which values are stored as JSON.
Serializer willjson.loads()those values when converting to representation
and willjson.dumps()them before saving.As a nested serializerfrommadprops.serializersimportNestedPropertySerializer,PropertiesOwnerSerializerclassPreferenceSerializer(NestedPropertySerializer):classMeta:model=Preferenceread_only_props=('user_token','tutorial_email_sent')json_props=('packages',)classUserSerializer(PropertiesOwnerSerializer):preferences=PreferenceSerializer(many=True,required=False)As a serializer used for properties endpointfrommadprops.serializersimportPropertySerializerclassPreferenceSerializer(PropertySerializer):classMeta:model=Preferenceread_only_props=('user_token','tutorial_email_sent')classPreferencePrivateViewSet(ModelViewSet):serializer_class=PreferenceSerializerpaginate_by=NoneTestingRun the tests with:toxOr install development requirements and run tests with:pip install -r requirements.txt
pytest tests
Package: drf-manipulation
DRF ManipulationIt's really common to have fields like "inserted_at", "updated_at",
"created_at", "last_modification", "last_update", etc in tables. To avoid
repeatedly copy-past these fields, I made this package.Installationpipinstalldrf-manipulationOr, if you want the latest version, you can directly install the package from
the source code:pipinstallhttps://github.com/xanigo/drf-manipulation/archive/refs/heads/master.zipOr using git:pipinstallgit+ssh://git@github.com/xanigo/drf-manipulation.git
Package: drf-material
🎨 drf-materialdrf-materialis a project that gives a sleek and elegant look to the browsable API of Django REST Framework using Material Design.We want to make the API moreappealingandintuitivefor developers and users alike.
That's why we created abeautifulandresponsivedesign that follows the Material Design principles and guidelines.Our goal with drf-material is to make your work easier and faster when working with Django REST Framework.
We think that by improving the user experience, we can help you create stunning and powerful web applications.So if you're looking for a better way to work with Django REST Framework, don't hesitate to try drf-material.
We're sure you'll be impressed by it as much as we are!🌟 FeaturesModern design: drf-material uses Material Design, a design system based on Google's Material Design and
Bootstrap's components, to create a sleek and elegant design for the API.Accessibility: drf-material follows the best practices for web accessibility,
ensuring that the API is easy to use for everyone, regardless of their abilities or preferences.Form input max length indicators: drf-material shows the maximum length of each form input field,
so you know how much data you can enter. The indicators also change color when you reach the limit, giving you visual feedback.Form inputs required indicators: drf-material marks the required form input fields with an asterisk (*),
so you know which fields are mandatory to submit the form. The indicators also show an error message if you try to submit the form without filling the required fields.Browser form validation: drf-material uses the built-in browser form validation features, such as HTML5 attributes
to validate the form input data before sending it to the server. The validation checks for data types, formats, patterns, ranges, and more.🛠️ Get startedTo use drf-material, follow these simple steps:Install the package:pip install drf-materialAdddrf_materialtoINSTALLED_APPSsetting, beforerest_framework# settings.pyINSTALLED_APPS=[...'drf_material','rest_framework',...]That's it! You're ready to go. 😎I hope you find this useful. Let me know if you have any feedback or questions. 😊
Package: drf-messages
Use Django’s Messages Framework with Django Rest Framework.Documentation is available athttps://drf-messages.readthedocs.io/en/latest/PyPI Package athttps://pypi.org/project/drf-messages/Django Packages athttps://djangopackages.org/packages/p/drf-messages/Requirements:Python (3.7, 3.8, 3.9)Django (2.2, 3.0, 3.1, 3.2)Django Rest Framework (3.7-3.12)Django’s message framework is awesome, and now its even better with Django Rest Framework!The django’s messages framework is a very easy and quick way to provide one-time messages for the user.
When using django rest framework you loose most of the functionality of it.
Using this app you can access your messages though a rest api endpoint.FeaturesPersistent message storage in databaseAutomatic cleanupDRF endpoint for accessing messagesQuick StartInstall using:$ pip install drf-messagesConfigure projectsettings.py:INSTALLED_APPS=[# ...'django.contrib.messages','rest_framework','drf_messages',# ...]MESSAGE_STORAGE="drf_messages.storage.DBStorage"Configure routes at your project’surls.pyurlpatterns=[path('messages/',include('drf_messages.urls')),# ...]Run migrations using:$ py manage.py migrate drf_messagesFor more details visit the docs for installation:https://drf-messages.readthedocs.io/en/latest/installation/installation.htmlUsageYou can list all your messages with:$ curl -X GET "http://localhost/messages/"Any unread messages will haveread_atasnull.
If you havedjango-filterconfigured, you can also query “http://localhost/messages/?unread=true” to get only unread messages.Getting helpIn case you have trouble while using this module, you may use theGitHub Disccussion.For any bug or issue, open anew GitHub Issue.Contributing
Package: drf-metadata
Installationpipinstall-egit+https://github.com/night-crawler/drf-metadata.git@#egg=drf-metadataModelsclassAuthor(models.Model):name=models.CharField(max_length=255)birth=models.DateField('birth date')def__str__(self):returnself.nameclassPublisher(models.Model):name=models.CharField(max_length=255)state=models.PositiveSmallIntegerField('publisher state',choices=((0,'Active'),(1,'Disabled')),default=1)def__str__(self):returnself.nameclassBook(models.Model):title=models.CharField(max_length=255)authors=models.ManyToManyField(Author)publisher=models.ForeignKey(Publisher)Usagefromdrf_metadata.metaimportMetaData,AbstractField,CustomMetadataclassBookMetadata(MetaData):model=Bookserializers={'publisher':PublisherSerializer}update_fields={'authors':{'omg':{'lol':1}}}# skip serialization (don't include model instances to choice field)dataset_urls={'authors':'/author/','publisher':'/publisher/',}# custom queryset for instance (self has `obj` if you need to filter qs)defget_authors_queryset(self,field):returnAuthor.objects.filter(name='author0')# use custom serializer for field instance(s)defget_authors_serializer(self,field):# self.request, self.view, self.obj are available in MetaData instancereturnAuthorSerializer# update field bundle with runtime valuesdefupdate_authors_field_meta(field,obj):return{'new':1,'obj':str(obj)}# use own serializerdefget_publisher_field_meta(field,obj):return{'new':1,'obj':str(obj)}Usage with django-rest-framework# or redefine OPTIONS handlerclassBookViewSet(viewsets.ReadOnlyModelViewSet):@list_route()defdescribe_book(self,request):md=metadata.BookMetadata().determine_metadata(request,self)returnResponse(md)Sample response{"title":"book","description":"description","fields":[{"type":"CharField","max_length":255,"name":"title","verbose_name":"title","help_text":"","blank":false,"null":false,"editable":true,"required":true},{"type":"ForeignKey","name":"publisher","verbose_name":"publisher","help_text":"","blank":false,"null":false,"editable":true,"required":true,"data":[{"id":47,"name":"pub0"},{"id":48,"name":"pub1"},{"id":49,"name":"pub2"}]},{"type":"ManyToManyField","name":"authors","verbose_name":"authors","help_text":"","blank":false,"null":false,"editable":true,"required":true,"data":[{"id":37,"name":"author0"},{"id":38,"name":"author1"},{"id":39,"name":"author2"}]}]}Non-model MetaDataclassImpersonateMetadata(CustomMetadata):title='View site as another user'action_name='Impersonate'fields=(AbstractField(type='ForeignKey',name='user_id',verbose_name='User',data='/data/',required=True),)# method fieldsdefget_superfield(self,request):return{'name':'hero','super':True}defget_lol(self,request):return{'name':'lol','super':False}# update field `user_id`defget_field_user_id(self,field_name,request):return{'lol':1}
Package: drf-micro-auth
Out-of-the-box solution for AAA services accessible through REST API.Detailed documentation is in the README.md in main folder.Quick startAdd “drf-micro-auth” to INSTALLED_APPSINSTALLED_APPS = [
    ...
    'drf-micro-auth',
]Include the polls URLconf in your project urls.py like this:path('drf_micro_auth/', include('drf_micro_auth.urls')),Runpython manage.py migrateto create the polls models.Start the development server and visithttp://127.0.0.1:8000/drf_micro_auth/docs/to explore endpoints.
Package: drf-microservice
Welcome to drf-microservice documentation!About Drf-microservicedrf-microservice is a ready-to-use API skeleton:Cookiescutter-drf-microservicegenerated it,And you:add your unittest and endpoints,And it will help you to:generate the documentation with drf-yasg,test it with Tox,package it Docker,deploy it (TODO with) Terraform or AnsibleIt sounds simple and it is. Take a look atDrf-microserviceit’s now generated byCookiescutter-drf-microservice.Something disturb you in the code? Don’t hesitate to open a an issue and contribute.docker-compose# create image(s) described in the docker-compose.yml:docker-compose build# Builds, (re)creates, starts, and attaches to containers for a service:docker-compose up -d# Stops, all the containers for a service:docker-compose downurls:xx.xx.xx.xx:8000
xx.xx.xx.xx:8000/admin/
xx.xx.xx.xx:8000/swagger/openapi/Releases notesBugs and evolution policiesWhen you will find a bug or propose an evolution create a ticket on:Issue Cookiescutter-drf-microserviceif it’s about the generation processIssue Drf-microserviceif it’s about a functionality in the generated drf processOnline documentation is here onreadthedocOnline source code available onGithub
Package: drf-misc
drf-miscdrf-misc is a Django DRF (Django Rest Framework) extension library that provides additional functionality to enhance your REST API development experience. This library offers features such as caching, service provision, and various REST API enhancements.FeaturesCaching:drf-misc simplifies caching in Django DRF by providing easy-to-use caching decorators and utilities. You can easily cache the responses of your API views or individual methods to improve performance and reduce unnecessary database queries.Service Provision:With drf-misc, you can leverage the service provision pattern to encapsulate business logic and separate it from your views. This promotes code reusability, maintainability, and testability. By utilizing services, you can keep your views lean and focused on handling request/response operations.REST API Enhancements:drf-misc offers various enhancements to Django DRF for building robust REST APIs. It provides additional mixins, serializers, and utility classes to streamline common tasks such as filtering, pagination, sorting, and more. These enhancements aim to reduce boilerplate code and enhance the development process.InstallationYou can install drf-misc using pip:pip install drf-miscMake sure you have Django and Django Rest Framework installed as well.UsageOnce installed, you can import and use the functionalities provided by drf-misc in your Django DRF projects.For detailed usage instructions and available features, please refer to thedocumentation.ContributingContributions to drf-misc are welcome! If you encounter any issues, have suggestions, or would like to contribute new features, please feel free to open an issue or submit a pull request on theGitHub repository.When contributing, please ensure that you follow the existing coding style, write tests for new functionality, and update the documentation accordingly.LicenseThis project is licensed under theMIT License.
Package: drf_mockable
## SynopsisThis is a package which makes building mockable APIs a breeze for Django developers. The dependencies for this package are:* Django >= 1.8* Django Rest Framework (DRF) >= 3.5## Installationpip install drf-mockable## Code ExampleIn your view class, just inherit the MockableView and define your mock_response. Thats it !!```pythonfrom drf_mockable.mockable import MockableViewclass MyMockAPI(MockableView):'''My Mock API which will return a mock response in case a need arises'''mock_response = {"message": "Here I am with a mock response","status": "success"}def post(self, request):''''''print("Do your stuff here if mocked response is not required")```Now, just hit your MockAPI from any REST client with a header 'Mockable' set as 'True' and you should be able to get the mocked response.Sample Curl Request:```shellcurl -X <MY_HTTP_REQUEST_METHOD> http://<PATH_TO_MY_MOCK_API>/ -H 'content-type: application/json' -H 'mockable: True' -d '<MY_REQUEST_DATA>'```In case you do not want the mock response and want the API to run normally, just remove the Mockable header and your API will work normally.## MotivationIn the world of APIs and Microservices, it often happens the front-end team (Mobile or UI Development) needs a sample API for testing out their integrations. The backend developers need to create mock APIs to help them in this regard. This package solves two problems which occur during this process:1) Provide backend developers with a fast & easy way to get the mock APIs up and running.2) In case the backend APIs are internally calling other third-party APIs and in case those third-party APIs are down, this will still allow you to keep your API unaffected with a mock response.## LicenseThis package comes under the MIT License.