Saravanan666/pypi-org huggingface dataset:
Package: drf-model-serializer
drf-model-serializerDescriptionThe scope of this module is to enhance DRF'sModelSerializerclass, and provide object-level validation out of the box.The idea is that the model defines its object-level validation in itscleanmethod. The serializer classModelSerializerprovided by this module, overrides itsvalidatemethod so that it invokes the model'scleanmethod. Therefore whenever invoking the serializer'sis_validmethod, thevalidatemethod runs and provides the object-level validation.This way, object-level validation is defined once in the model and is used automatically by the Django admin, the model when explicitly invokingfull_cleanand the serializer whenever invokingis_valid. This follows the convention forfield-levelvalidation. When defined correctly usingmodel validators, the field-level validation is used out of the box by the Django admin, serializer and model.Proving the validation ideaIn this module, we also provide a Django project that will show you how the object level validations works together with Django admin, Serializer, and a model by implementingdrf-model-serializerand modelclean()method. A main focus of the test project lives on create/update actions over any drinks or main dishes recipe, which all any incoming data either from Admin or Serializer must be validated. See theRecipe modeland thetests sectionto understand it in more detail.PrerequisiteEnsure pip installed on your local machine. If you don't have it, you can follow the installation guidehere.How to run the testsOpen terminal and go to the root directory of where the package live, for instance:$ cd Documents/py-projects/drf-model-serializer.Run$ ./scripts/requirement-install.shfrom your command line.Run$ ./scripts/checker.sh.How to run the test projectCurrently only Recipe admin page that available to be explored, and to try it out you can follow these steps:Open terminal and go to the root directory of where the package live, for instance:$ cd Documents/py-projects/drf-model-serializer.Run$ ./scripts/requirement-install.shfrom your command line (you can skip this if you already did it when running the tests).Run$ source venv/bin/activate && cd test_project && python manage.py migrate.Create admin user, run$ python manage.py createsuperuser --email admin@mail.com --username admin.Run$ python manage.py runserver 0.0.0.0:8000and when server is ready, open the admin page and logged in with the previous Admin account.Installation$pipinstalldrf-model-serializeror add this on yourrequirements.txtdrf-model-serializer==0.0.1Get involved!We are happy to receive bug reports, fixes, documentation enhancements, and other improvements.Please report bugs via the githubissue tracker.Master git repositorydrf-model-serializer.
Package: drf-msal-jwt
This package allows user to authenticate using Microsoft Account in Django REST Framework.This library rely onDjango REST FrameworkandDjango Rest Framework JWTto works properly.Please make sure you setup these packages successfully before using this package.DocumentationThe full documentation is athttps://drf-msal-jwt.readthedocs.io.QuickstartInstall Django Rest Framework MSAL + JWT:pip install drf-msal-jwtAdd it to yourINSTALLED_APPS:INSTALLED_APPS=(...'drf_msal_jwt',...)Add Django Rest Framework MSAL + JWT’s URL patterns:fromdrf_msal_jwtimporturlsasdrf_msal_jwt_urlsurlpatterns=[...url(r'^',include(drf_msal_jwt_urls)),...]Config the settings.pyDEFAULTS={'MSAL_CLIENT_ID':"{AZURE_AD_CLIENT_ID}",'MSAL_CLIENT_SECRET':"{AZURE_AD_CLIENT_SECRET}",'MSAL_AUTHORITY_URL':'https://login.microsoftonline.com/common/','MSAL_REDIRECT_URL':"{AZURE_AD_REDIRECT_URL}",'MSAL_SCOPES':["User.ReadBasic.All"],'MSAL_USER_HANDLER':'django.contrib.auth.models.User','MSAL_ALLOW_DOMAINS':['*'],'MSAL_CHECK_STATE':True}Features[API] for generating Microsoft Login URL[API] for logging/creating user based on Authorization Code, and generate JWT tokenRunning TestsDoes the code actually work?source <YOURVIRTUALENV>/bin/activate
(myenv) $ pip install tox
(myenv) $ toxDeploymentBumb version & deploybumpversion <major/minor/patch>
python setup.py publish
Package: drf-msgspec-json-renderer
Django Rest Framework msgspec RendererDjango Rest Framework renderer usingmsgspecInstallationpip install drf-msgspec-json-rendererYou can then set theMsgspecJSONRendererclass as your default renderer in yoursettings.pyREST_FRAMEWORK={'DEFAULT_RENDERER_CLASSES':('drf_msgspec_json.renderers.MsgspecJSONRenderer',),...}Also you can set theMsgspecJSONParserclass as your default parser in yoursettings.pyREST_FRAMEWORK={'DEFAULT_PARSER_CLASSES':('drf_msgspec_json.parsers.MsgspecJSONParser',),...}
Package: drf-multi-lookup
DRF Multi LookupThis is a package written on top ofdrf-writable-nestedinorder to make calls to serializer without knowing exact Primary Key
but using candidate keys.RequirementsPython (2.7, 3.5, 3.6, 3.7)Django (1.9, 1.10, 1.11, 2.0, 2.1, 2.2)djangorestframework (3.5+)drf-writable-nested (0.5.1)Installationpip install drf-multi-lookupDevelopmentDeploymentChange version ininit.pypython setup.py sdist bdist_wheeltwine upload dist/*Authors2020, Spoonshot
Package: drf-multiple-serializer
DRF multiple serializerExtension for using multiple serializer in Django REST Framework.InstallationInstall fromPyPIpip install drf-multiple-serializerThere is no need to modify your INSTALLED_APPS setting.UsageAction BaseSet the serializer to serializer_classes with the viewset action.The rest of the actions use the default serializer.from rest_framework import viewsets
from drf_multiple_serializer import MultipleSerializerMixin


class CategoryViewSet(ActionBaseSerializerMixin,
                      viewsets.ModelViewSet):
    queryset = Category.objects.all()
    serializer_classes = {
        'default': CategorySerializer,
        'list': CategoryListSerializer,
        'retrieve': CategoryReadSerializer,
    }Read & WriteSet the read & write serializer to serializer_classes.List, Retrieve actions use a read serializer,and the other actions (include delete) use a write serializer.from rest_framework import viewsets
from drf_multiple_serializer import ReadWriteSerializerMixin


class ItemViewSet(ReadWriteSerializerMixin,
                  viewsets.ModelViewSet):
    queryset = Item.objects.all()
    serializer_classes = {
        'read': ItemReadSerializer,
        'write': ItemWriteSerializer,
    }Test> python3 -m venv venv
> source venv/bin/activate
(venv) > pytest
Package: drf-multitokenauth
Django Rest Multi Token AuthThis django app is an extension for the Django Rest Framework.
It tries to overcome the limitation of Token Authentication, which only uses a single token per user.How to useInstall:pipinstalldrf-multitokenauthAdd'drf_multitokenauth'to yourINSTALLED_APPSin your Django settings file:INSTALLED_APPS=(...'django.contrib.auth',...'rest_framework',...'drf_multitokenauth',...)Configure Django REST Framework to use'drf_multitokenauth.coreauthentication.MultiTokenAuthentication':REST_FRAMEWORK={...'DEFAULT_AUTHENTICATION_CLASSES':[...'drf_multitokenauth.coreauthentication.MultiTokenAuthentication',...],...}And add the auth urls to your Django url settings:fromdjango.conf.urlsimportincludefromdjango.urlsimportre_pathurlpatterns=[...re_path(r'^api/auth/',include('drf_multitokenauth.urls',namespace='multi_token_auth')),...]The following endpoints are provided:login- takes username and password; on success an auth token is returnedlogoutSignalspre_auth(username, password)- Fired when an authentication (login) is startingpost_auth(user)- Fired on successful authTestsSee foldertests/. Basically, all endpoints are covered with multiple
unit tests.Use this code snippet to run tests:pipinstalltox
toxCache BackendIf you want to use a cache for the session store, you can installdjango-memoizeand add'memoize'toINSTALLED_APPS.Then you need to useCachedMultiTokenAuthenticationinstead ofMultiTokenAuthentication.pipinstalldjango-memoizeDjango Compatibility MatrixIf your project uses an older verison of Django or Django Rest Framework, you can choose an older version of this project.This ProjectPython VersionDjango VersionDjango Rest Framework2.0.*3.7+3.2, 4.0, 4.13.12, 3.131.5.*3.7+3.2, 4.0, 4.13.12, 3.131.4.*3.6+2.2, 3.23.9, 3.10, 3.11, 3.121.3.*2.7, 3.4+1.11, 2.03.6, 3.7, 3.81.2.*2.7, 3.4+1.8, 1.11, 2.03.6, 3.7, 3.8Make sure to use at leastDRF 3.10when usingDjango 3.0or newer.Releases prior to2.0.0where published asdjango-rest-multitokenauth.
Newer releases are published asdrf-multitokenauth.Migrating from 1.x to 2.xUninstalldjango-rest-multitokenauthInstalldrf-multitokenauthRun the migration SQL bellow:ALTER TABLE django_rest_multitokenauth_multitoken RENAME to drf_multitokenauth_multitoken;
UPDATE django_migrations SET app = 'drf_multitokenauth' WHERE app = 'django_rest_multitokenauth';Run Django migrationsChangelog / ReleasesAll releases should be listed in thereleases tab on github.SeeCHANGELOG.mdfor a more detailed listing.LicenseThis project is published with theBSD 3 Clause License. Seehttps://choosealicense.com/licenses/bsd-3-clause-clear/for more information about what this means.
Package: drf-nest
drf-nestWritable nested serialisers for Django Rest FrameworkThe sampleA sample project is included which implements a retail type use case.Sales have a foreign key to a storeSale items have foreign keys to the sale.To run sample:pipinstall-rrequirements.txt
pythonmanage.pymigrate
pythonmanage.pycreatesuperusersupersuper@super.comsuper
pythonmanage.pyrunserverTo usepythonsetup.pyinstallIn your serialisers.py file import extensions:fromdrf_nest.serializersimportExtendedHyperlinkedSerialiserfromdrf_nest.serializer_fieldsimportExtendedModelSerialiserFieldFor each model serialiser using nested field use the ExtendedHyperlinkedSerialiserclassSaleSerialiser(ExtendedHyperlinkedSerialiser):For each nested representation in the parent object use the ExtendedModelSerialiserFieldclassSaleSerialiser(ExtendedHyperlinkedSerialiser):sale_items=ExtendedModelSerialiserField(SaleItemSerialiser(),many=True,required=False,allow_null=True)We won't know the foreign key to fulfill the relationship if we are creating the parent so in each sub objects serialiser, the parent object must be made optional.classSaleItemSerialiser(ExtendedHyperlinkedSerialiser):sale=serializers.HyperlinkedRelatedField(required=False,view_name='sale-detail',queryset=Sale.objects.all())How does it workThe serialiser field overrides the to internal function to return a dictionary (or list of dictionaries) rather than the django model instance.
This is done because the fields do not know if the parent exists already but may have a required foreign key constraint.FeaturesSee the sample project tests for example POST requests.During POST, PUT and PATCH user can specify nested object either by URL or full serialised representationAdds type field to allow for generic foreign keys (in development)Serialisation of model with foreign keySerialisation of model with reverse relationshipSerialisation of model with many to many relationship
Package: drf-nested
DRF Nested UtilsThis package provides a set of utils to help developers implement nested data handling for Django Rest Framework.This package adds support for:Direct relation handling (ForeignKey)Reverse relation handling (i.e. allows working with models that have current asForeignKey)Direct and reverseManyToMany, with special flow for the m2m relationships with customthroughmodelsGenericRelationwith special mixinsIt also provides mixins for handlingUniqueandUniqueTogethervalidators.MixinsNested Serializer MixinsBaseNestedMixinBase mixin that contains the methods for retrieval of all related fields of the serializer model.
It also provides all theupdate_or_createmethods for each type of fields
(direct relation,reverse relation,many-to-many relationandgeneric relation).CreateNestedMixinMixin that allows creation of the nested models on serializercreatecall.
You can provide a list of fields that should be forbidden on create,
the list of fields should be placed into theforbidden_on_createfield on serializerMetaclass.
Mixin usesBaseNestedMixinproperties andupdate_and_createmethods to create nested fields.UpdateNestedMixinMixin that allows modification of the nested models on serializerupdatecall.
Mixin usesBaseNestedMixinproperties andupdate_and_createmethods to update nested fields.Validator MixinsUniqueFieldMixinMixin that allows usage of theuniquefields with nested mixins.
This mixin moves the validation process fromis_validtocreate/updatecall.
This is done because the fields that should be used in theuniquevalidation may not be
set on the initialis_validcall and are set just before the nestedcreate/updatecall.UniqueTogetherMixinMixin that allows usage of theunique_togetherfields with nested mixins.
This mixin moves the validation process fromis_validtocreate/updatecall.
This is done because the fields that should be used in theunique_togethervalidation may not be
set on the initialis_validcall and are set just before the nestedcreate/updatecall.Helper MixinsNestableMixinMixin that allows to specify the name of the nested field by settingwrite_sourceif the initialsourceof the field is different
from the field name or the initialsourceis not writable (a property, for example).ThroughMixinMixin that allows to specify ifthroughmodel should be connected to current model after thethroughmodelcreate/updatecall.GenericRelationMixinMixin that should be used on serializers that represent connected byGenericRelationmodels.ExamplesYou can see an example project inexamples/directory.NotesIf you are using a Many-to-Many field withsourceproperty or you have athroughmodel on your serializer,
you should add aNestableMixinto the target serializer and add awrite_sourcefield when you initialize that serializer.In case of thesourceproperty you should add an actual model field that would allow you to properly connect your model with related ones.In case of thethroughmodel you should have it set to therelated_nameof the connectedthroughmodelYou can also useThroughMixinand setconnect_to_modelto False if you want to have the ability to keep thethroughmodel connection in case thethroughmodel ForeignKey should be different from the current model.
Package: drf-nested-browsable
:warning: Work In Progress :warning:Writable Nested Serializers with Browsable API FormsThis plugin is intended to provide writable nested serializers (similar tothe recommended plugin from DRF documentation) that bring their own forms for the Browsable API renderer.Try it outThis project's dependencies are managed usingpoetrygitclonehttps://github.com/pcouy/drf-nested-browsablecddrf-nested-browsable
poetryinstallcdexample
poetryshell
pythonmanage.pymigrate
pythonmanage.pyrunserverThe above commands will install the dependencies, run the DB migrations, and launch a development server of the example project that uses the provided serializers.Current state of the projectDoneAbility to write to a reverseForeignKeyrelationship using serializerMetaclassDynamic form forWritableNestedListSerializerthat allows adding and removing children from the Browsable APIArbitrary nesting depthDynamically removing the parent field from serializers when used as an inner serializerBasic exampleTo doWrite documentation / Auto-generate it from the docstrings (pdoc?)Write tests/specs (from example ?)Better form designAddManyToManyto example (and test it)Consider database schema constrains :Look into whatdrf-writable-nesteddoes with uniquenessWhen the foreign key can benull, show a multiple select field for attaching orphan instances to a parent instanceShow a multiple select field forManyToManyrelationships
Package: drf-nested-decorator
# drf-nested-decoratorA decorator that allows view actions to be nested and seeks to be integrated into DRF after proper tests are written.I didn't try to create a lot of new stuff, i just edited the SimpleRouter and added a decorator**Use at own risk.** No tests yet! 'Works for me' though.. :)I've created this functionality because i was in need, and will try to add tests and better organisation to it when i have time.Want to use it? Star so i know there's someone else besides me that will benefit from my efforts.## Usagemy_app/views.pyfrom drf_nested_decorator.decorator import nested_detail_routefrom rest_framework.response import Responsefrom rest_framework.permissions import IsAuthenticatedfrom my_users.permission_classes import ActuallyOwnsCard, IsAwesomefrom my_users.serializers import CardSerializerfrom my_users.models import Cardclass MyUserViewSet(mixins.RetrieveModelMixin, mixins.ListModelMixin, GenericViewSet):authentication_classes = (SessionAuthentication, )permission_classes = (IsAuthenticated, )queryset = MyUser.objects.all()serializer_class = MyUserSerializer@nested_detail_route(['DELETE'], url_path='cards', permission_classes=(IsAwesome, ActuallyOwnsCard) + permission_classes)def nested_cards(self, request, pk=None, nested_pk=None)serializer = CardSerializer(Card.objects.get(pk=nested_pk))return Response(serializer.data)urls.pyfrom drf_nested_decorator.routers import NestedDecoratorSimpleRouterfrom my_app.views import MyUserViewSetrouter = NestedDecoratorSimpleRouter()router.register(r'myuser', MyUserViewSet, base_name="myuser")## To do:- Add tests, for everything (no decorator tests in DRF found, find or create)- Test with other packages like drf-nested-routers and drf-extensions- No formal parameter nested_lookup on decorated method supplied ->> good error message- Find out from what lower version this is supported, I'm using 3.1.3.- Automatic lookup of nested model through a nested_queryset?
Package: drf-nested-field-multipart
# drf-nested-field-multipartParser for nested params in multipart file upload# Usage```pythonfrom drf_nested_field_multipart import NestedMultipartParserfrom rest_framework import viewsetsclass YourViewSet(viewsets.ViewSet):parser_classes = (NestedMultipartParser,)```To enable JSON and multipart```pythonfrom drf_nested_field_multipart import NestedMultipartParserfrom rest_framework.parsers import JSONParserfrom rest_framework import viewsetsclass YourViewSet(viewsets.ViewSet):parser_classes = (JSONParser, NestedMultipartParser)```# Installation`pip install drf-nested-field-multipart`
Package: drf-nested-multipart-parser
drf-nested-multipart-parserDRF Parser for nested params in multipart file upload.Usagefromdrf_nested_multipart_parserimportNestedMultipartParserfromrest_frameworkimportviewsetsclassYourViewSet(viewsets.ViewSet):parser_classes=(NestedMultipartParser,)To enable JSON and multipartfromdrf_nested_multipart_parserimportNestedMultipartParserfromrest_framework.parsersimportJSONParserfromrest_frameworkimportviewsetsclassYourViewSet(viewsets.ViewSet):parser_classes=(JSONParser,NestedMultipartParser)Example:Input datauser[email] = 'test@test.test'
user[name] = 'John Doe'

user[profile][balance] = 100.00
user[profile][phone_number] = '+996325698201'
user[profile][avatar] = avatar_file

user[roles][] = 1 
user[roles][] = 2 
user[roles][] = 3 
...Viewfromdrf_nested_multipart_parserimportNestedMultipartParserfromrest_frameworkimportviewsetsclassYourViewSet(viewsets.ViewSet):parser_classes=(NestedMultipartParser,)defpost(self,request):user_data=request.data.get('user')email=user_data['email']# test@test.testbalance=user_data['profile']['balance']# 100.0roles=user_data['roles']# [1, 2, 3]...Installationpip install drf-nested-multipart-parser
Package: drf-nested-resources
drf-nested-resourcesThis is a django rest framework extension to allow developers to create nested
resources.How to useConfiguration of nested resourcesFor this example we are going to create a simple API with the following
endpoints:/developers/
/developers/<id>
/developers/<id>/languages/
/developers/<id>/languages/<id>First we start with the following Django models:fromdjango.db.modelsimportCASCADEfromdjango.db.models.baseimportModelfromdjango.db.models.fieldsimportCharFieldfromdjango.db.models.fields.relatedimportForeignKeyclassDeveloper(Model):name=CharField(max_length=20)classProgrammingLanguage(Model):name=CharField(max_length=20)author=ForeignKey(Developer,related_name='programming_languages',on_delete=CASCADE,)We will have the two viewsets for both thedevelopersandlanguagesresource
collections.fromrest_framework.viewsetsimportModelViewSetfromdrf_nested_resources.fieldsimportHyperlinkedNestedModelSerializerclass_DeveloperSerializer(HyperlinkedNestedModelSerializer):classMeta(object):model=Developerfields=('url','name','programming_languages')classDeveloperViewSet(ModelViewSet):queryset=Developer.objects.all()serializer_class=_DeveloperSerializerclass_ProgrammingLanguageSerializer(HyperlinkedNestedModelSerializer):classMeta(object):model=ProgrammingLanguagefields=('url','name','author')classProgrammingLanguageViewSet(ModelViewSet):queryset=ProgrammingLanguage.objects.all()serializer_class=_ProgrammingLanguageSerializerThe related fields in the ViewSetsauthorandprogramming_languagesshould
follow the model representation so thatauthorwill give us a url for the
developer who wrote the ProgrammingLanguage and theprogramming_languagesshould give us a list of urls for the ProgrammingLanguages that the Developer
wrote.This is how you would generate the urlpatterns for them:_RESOURCES=[Resource('developer','developers',DeveloperViewSet,[NestedResource('language','languages',ProgrammingLanguageViewSet,parent_field_lookup='author',)],),]urlpatterns=make_urlpatterns_from_resources(_RESOURCES)For more examples of different relationships and authorization check the test
suite.ChangelogVersion 2.0.0Added support for Django 2.2 and removed support for Django < 2.2Version 1.3Updated dependencies and added coverage configVersion 1.2 Beta 3Fixed error when urlconf was not explicitly set on the requestVersion 1.2 Beta 2Fixed support for non-session-based authenticators when checking permissions in
viewsets in the ancestry.Version 1.2 Beta 1Implemented ability to force a field value in a nested resource to be set to
the URL of an ascending resource. This is done using the optional attributefield_forced_to_ancestoron the serializer'sMetaclass.Version 1.1Re-worked the mechanism for URL generation to support cross-linking resource
trees.Breaking change: Any previous usage of many-to-many fields on variables
in the current request's URL will now break.Version 1.0 Release Candidate 3Added proper support for namespaced URLsVersion 1.0 Release Candidate 1Added support for Django 1.10 and Rest Framework 3.4.3Version 1.0 Beta 1 (unreleased)Initial release.
Package: drf-nested-serializer
DRF Nested SerializerNested Serializer support for Django Rest Framework.Installationpip install drf-nested-serializerExampleclassGoods(models.Model):name=models.CharField(max_length=10)category=models.CharField(max_length=20)classGoodsImage(models.Model):goods=models.ForeignKey(Goods,related_name='goods_images',on_delete=models.CASCADE)image_key=models.CharField(max_length=10)classGoodsSerializer(NestedModelSerializer):classMeta:model=Goodsfields='__all__'nested_fields={'goods_images':'goods'}# {related_name: field_name}The above will allow to create the following queriesPOST
{
    "name": "string",
    "category: "string",
    "goods_images": [
        {"image_key": "string"},
        {"image_key": "string"},
        {"image_key": "string"}
    ]
}