Saravanan666/pypi-org huggingface dataset:
Package: drf-notification-system
DRF Notification SystemAn app that sends notifications to internal users.RequirementsDjango (2.2 <= 3.2 )Django REST frameworkdjango_filtersCeleryInstallationpip install drf-notification-systemPost-Install SetupDjango SettingsINSTALLED_APPS=[...'notification_system',]Include the notification system urls in your project urls.py like thispath('notification-system/',include('notification_system.urls')),Runpython manage.py migrateto create the notification system models.If you want to change send email notification default queue name, setEMAIL_NOTIFICATION_QUEUE_NAMEconstance on thesettings.pyfile. the default value is 'send_email_notification'If you want to change send update outgoing message status default queue name, setUPDATE_OUTGOING_MESSAGE_STATUS_QUEUE_NAMEconstance on thesettings.pyfile. the default value is 'update_outgoing_message_status'If you want to change send email notification rate limit, setNOTIFICATION_SYSTEM_SEND_EMAIL_RATE_LIMITconstance on thesettings.pyfile. the default value is '700/m'If you want to change user fields to pass template as context data, setNOTIFICATION_SYSTEM_DEFAULT_USER_FIELDconstance on thesettings.pyfile. the default value is ['id', 'username', 'first_name', 'last_name', 'email']Run Celery worker with the following commandcelery -A 'project_name' worker --loglevel DEBUG -Q 'queue_name' --concurrency=1celery -A 'project_name' worker --loglevel DEBUG -Q send_email_notification --concurrency=1celery -A 'project_name' worker --loglevel DEBUG -Q update_outgoing_message_status --concurrency=1
Package: drf-ns
This is a Django Rest Framework addon to rezolve folowing problemsinfinit level of nested serializerdifferent level of nested objectswritable nested objectsDetailed documentation is in the “docs” directory.Quick startAdd “drf-ns” to your INSTALLED_APPS setting like this:INSTALLED_APPS = [
    ...
    'drf-ns',
]This also includes ModelTracker as Base model class for your appRunpython manage.py migrateto create the models.
Package: drfobserver
OverviewDjango Rest Framework object observer patternRequirementsPython (2.7, 3.3, 3.4)Django (1.6, 1.7, 1.8)Django REST Framework (2.4, 3.0, 3.1)InstallationInstall usingpip…$pipinstalldrfobserverExamplefromdjango.dbimportmodelsfromdrfobserverimportObserverMixin,observerclassActor(ObserverMixin,models.Model,):""" Actor model """first_name=models.CharField(max_length=50)last_name=models.CharField(max_length=50)@observer('first_name','last_name')def_setter_name(self):""" Set the full name from first & last """self.name='%s%s'%(self.first_name,self.last_name)TestingInstall testing requirements.$pipinstall-rrequirements.txtRun with runtests.$./runtests.pyYou can also use the excellenttoxtesting tool to run the tests
against all supported versions of Python and Django. Install tox
globally, and then simply run:$toxDocumentationTo build the documentation, you’ll need to installmkdocs.$pipinstallmkdocsTo preview the documentation:$mkdocsserveRunningat:http://127.0.0.1:8000/To build the documentation:$mkdocsbuild
Package: drf_observer
OverviewDjango Rest Framework object observer patternRequirementsPython (2.7, 3.3, 3.4)Django (1.6, 1.7, 1.8)Django REST Framework (2.4, 3.0, 3.1)InstallationInstall usingpip…$pipinstalldrf_observerExampleTODO: Write example.TestingInstall testing requirements.$pipinstall-rrequirements.txtRun with runtests.$./runtests.pyYou can also use the excellenttoxtesting tool to run the tests
against all supported versions of Python and Django. Install tox
globally, and then simply run:$toxDocumentationTo build the documentation, you’ll need to installmkdocs.$pipinstallmkdocsTo preview the documentation:$mkdocsserveRunningat:http://127.0.0.1:8000/To build the documentation:$mkdocsbuild
Package: drf-openapi-schema
Django Rest Framework OpenAPI Schemapipinstalldrf-openapi-schemaDocumentation:https://mrthearman.github.io/drf-openapi-schema/Source Code:https://github.com/MrThearMan/drf-openapi-schema/Contributing:https://github.com/MrThearMan/drf-openapi-schema/blob/main/CONTRIBUTING.md...
Package: drf-optionalfields
drf-optionalfields gives you the flexibility to specify which fields you want to serialized.There are two mixins available:OptionalFieldsMixin: Which allows you to set some optional fields. These fields can be requested via GET paramsDynamicFilterMixin: Which allows you to specify only the fields you need.fromrest_framework.serializersimportModelSerializerfromdrf_optionalfieldsimportOptionalFieldsMixinclassMyModelSerializer(OptionalFieldsMixin,ModelSerializer):classMeta:model=SomeModelfields=("id","username","address","full_name")optional_fields=("address","full_name")# or combined with DynamicFilterMixinclassMyModelSerializer(OptionalFieldsMixin,DynamicFilterMixin,ModelSerializer):classMeta:model=SomeModelfields=("id","username","address","full_name")optional_fields=("address","full_name")# You want to see an "address" you have set in the Meta:
GET /users/1/?fields=address

# You want only to return "username":
GET /users/1/?filter=username

# You want only to return the optional "full_name":
GET /users/1/?fields=full_name&filter=usernameThanks to Wim Glen for providing great bootstrap code with <https://github.com/wimglenn/djangorestframework-queryfields>(djangorestframework-queryfields)
Package: drf-optional-fields
drf-optional-fieldsA django-restframework extension to dynamically specify the returned field.RequirementsPython: 3.6, 3.7Django: 2.0, 2.1, 2.2DRF: 3.9InstallationInstall using pip:pip install django-queryset-exts
pip install drf-optional-fieldsExample:Usefieldsin query parameters to specify the returned field.
For example,fields=id,name,info{city{name},location}will return a dict like below:{
    "id": "id",
    "name": "A",
    "info": {
        "city": {
            "name": "city name"
        },
        "location": "localtion"
    }
}Obviously, it refers tofacebook fieldUsageFirst, make your serializer class inherit fromdrf_optional_fields.serializers.OptionalFieldsMixinfromdjango.db.models.queryimportPrefetchfromrest_frameworkimportserializersfromdjango_queryset_exts.queryimportSelectAPIRelatedfromdrf_optional_fields.serializersimportOptionalFieldsMixinclassMyModelsOptionalFieldsSerializer(OptionalFieldsMixin,serializers.ModelSerializer):classMeta:models=MyModelfields=('field1','field2','foreign_key_field','reverse_many_to_one_field','remote_uuid_field')# use those configs to reduce queries to dbfields_related_query={'foreign_key_field':('foreign_key_field',),# use foreign key field name directly'remote_uuid_field':(SelectAPIRelated('remote_uuid_field'),),'reverse_many_to_one_field':(Prefetch('reverse_many_to_one_field'))}default_fields=deepcopy(fields)# change this line to specify default fields, for example: default_fields = ('field1', )Then, make your api view inherit fromdrf_optional_fields.views.OptionalFieldViewMixinfromrest_framework.genericsimportListAPIViewfromdrf_optional_fields.viewsimportOptionalFieldViewMixinclassMyModelListView(OptionalFieldViewMixin,ListAPIView):queryset=MyModel.objects.filter(is_deleted=False)serializer_class=MyModelsOptionalFieldsSerializerIt's done.
Package: drf-passage-identity
A Django App that allows you to easilty integrate Passwordless authentication provided by Passage (by 1Password). Leverage a custom PassageUser module over the User module provided by Django but with built-in Passage user integration and token authentication for seamless passwordless authentication via REST APIs.SetupInstall frompip:python-mpipinstalldrf-passage-identityand then add it to your installed apps:INSTALLED_APPS=[...,"passage_auth",...,]Make sure you add the trailing comma or you might get aModuleNotFoundError(seethis blog
post).You will also need to add a path to listen in get responses:urlpatterns=[...,path('api/client/',include("passage_auth.urls")),...,]ConfigurationConfigure the Passage object in your Django settings. Here, for Header Auth, auth strategy is 2 and for Cookie Auth it is 1. You must set the following settings:AUTH_USER_MODEL='passage_auth.PassageUser'PASSAGE_APP_ID="your-app-id"PASSAGE_API_KEY="your-api-key"PASSAGE_AUTH_STRATEGY=2
Package: drf-payload-customizer
drf-payload-customizerThis package allows you to customize yourdjango-rest-frameworkserializer i/o to make modern frontend frameworks happy.
The following modifications are supported:Transformation: Convert allkeysin API output tocamelCase. Also
on reception of an input on an API, transform all inputs tosnake_case.Translation: Rename akeyin your API schema. (works in both
direction).Nullify/Balankify: Replace""withNoneon output direction and
vice versa in the other direction.We introduce 3 seperateMixinsthat can you can subclass yourAPIViewfrom to achieve 1-3. They are:PayloadTransformationMixin: Perform transformation (1) above. Has an
optional parameterPAYLOAD_TRANSFORM_NESTED(see tests) which you can set
toTruein yourSerializer.Metaclass to recursively convert all nested
dictionaries. This feature only works in the output direction.PayloadTranslationMixin: Perform translation (2) above. You can specify
custom mappings using afield_mappingsdict in yourSerializer.Metaclass.PayloadNoNullOrNoneMixin: Perform nullify/blankify (3) above.RequirementsThemixinrequires you to have the following dependencies:djangorestframework==3.8.2We are positive it would work with other versions of Django Rest Framework
as well. However, you will requireDjango==2.1.2to run the unit tests.Use it in your projectYou can use all three of the mixins together like this in your project using
ourdrf_payload_customizer.mixins.PayloadConverterMixinmixin. The mixin
performs (1-3) modifications listed above. Here is how it is implemented:class PayloadConverterMixin(PayloadTransformationMixin,
                            PayloadTranslationMixin,
                            PayloadNoNullOrNoneMixin):
    """
    Use this mixin in all of our Serializers, to convert the JSON into a
    format that is easier consumed by modern front-ends.
    """

    def to_representation(self, instance):
        return super().to_representation(instance)

    def to_internal_value(self, camel_cased):
        return super().to_internal_value(camel_cased)Now, subclass yourAPIViewswithPayloadConverterMixinas given below:from drf_payload_customizer.mixins import PayloadConverterMixin

class CustomTestModelSerializer(PayloadConverterMixin, ModelSerializer):
    class Meta:
        model = TestModel
        fields = ('parama', 'param_b',)
        PAYLOAD_TRANSFORM_NESTED = True
        # The mapping is the snake_case of your expected o/p
        field_mappings = {
            'parama': 'param_a' 
        }
        
# Now your serializer would output: 
test_serializer = CustomTestModelSerializer(obj)
JSONRenderer().render(test_serializer.data)
> {'paramA': '', 'paramB': None}

# Your serializer also admits input in the same format: 
content = json.dumps({'paramA': 'testA', 'paramB': 3}).encode()
stream = BytesIO(content)
data = JSONParser().parse(stream)
serializer = CustomTestModelSerializer(data=data)
self.assertTrue(serializer.is_valid())
> TrueTo run testscddrf_payload_customizer# Make sure you change to a virutal environment according to your project setuppythonsetup.pyinstallpipinstall-rrequirements.txtcdtests/test_app/pythonmanage.pytest
Package: drf-payments
DRF paymentsPackage to handle various payments provider inside your drf projectThis package will allow you to create transactional payments on various payment providers:StripePaypalBraintreeAuthorize.netUpon creation of your appPaymentmodel this library will handle:Creation of payment on selected providerDirect chargeCheckout sessionHandling webhook event from payment gateway to updatePaymentstatusHandle Refund on the payment if payment was processedWrite along the way all payment gateway responses inextra_datajson field of yourPaymentmodelFor example of usage please seeexampleapp inside repository.Installationpip install drf-paymentsAdd toINSTALLED_APPSINSTALLED_APPS=["django.contrib.admin","django.contrib.auth","django.contrib.contenttypes","django.contrib.sessions","django.contrib.messages","django.contrib.staticfiles","drf_payments",...]Add callback urlfromdjango.contribimportadminfromdjango.urlsimportinclude,pathurlpatterns=[path("admin/",admin.site.urls),...path("drf-payments/",include("drf_payments.urls")),]Provide required settingsPAYMENT_MODEL="stripe_checkout.StripeCheckoutPayment"PAYMENT_CALLBACK_URL="http://localhost:8000/drf-payments/callback/"PAYMENT_SUCCESS_URL="http://localhost:3000/payments/success/"PAYMENT_FAILURE_URL="http://localhost:3000/payments/failure/"PAYMENT_VARIANTS={"stripe":("drf_payments.stripe.StripeCheckoutProvider",{"secret_key":os.environ.get("STRIPE_SECRET_KEY"),"public_key":os.environ.get("STRIPE_PUBLIC_KEY"),},),"paypal":("drf_payments.paypal.PaypalProvider",{"client_id":os.environ.get("PAYPAL_CLIENT_ID"),"secret":os.environ.get("PAYPAL_SECRET_KEY"),"endpoint":os.environ.get("PAYPAL_URL","https://api.sandbox.paypal.com"),},),}UsageFor usage you can check example implementation in repoInheritdrf_payments.models.BasePaymentmodel in your appfromdrf_payments.modelsimportBasePaymentclassStripeChargePayment(BasePayment):...classMeta:db_table="stripe_charge"Usedrf_payments.mixins.PaymentViewMixinin view that handles your payment modelfromrest_framework.routersimportSimpleRouterfromdrf_payments.mixinsimportPaymentViewMixinapp_name="shop"router=SimpleRouter()router.register("payment",PaymentViewMixin,basename="payment")urlpatterns=[*router.urls]Point your payments events to endpoint from settingsPAYMENT_CALLBACK_URLFor more info please checkexampleapp inside repositoryFor even more detail checkdocumentation
Package: drf-pdf
# DRF-PDF[![Documentation Status](https://readthedocs.org/projects/drf-pdf/badge/?version=latest)](https://readthedocs.org/projects/drf-pdf/?badge=latest)[![Build Status](https://travis-ci.org/drgarcia1986/drf-pdf.svg?branch=master)](https://travis-ci.org/drgarcia1986/drf-pdf)[![Coverage Status](https://coveralls.io/repos/drgarcia1986/drf-pdf/badge.svg)](https://coveralls.io/r/drgarcia1986/drf-pdf)[![Code Health](https://landscape.io/github/drgarcia1986/drf-pdf/master/landscape.svg?style=plastic)](https://landscape.io/github/drgarcia1986/drf-pdf/master)A simple PDF utils for Django Rest Framework## Install```pip install drf-pdf```## Example```python# coding: utf - 8from rest_framework import statusfrom rest_framework.response import Responsefrom rest_framework.views import APIViewfrom drf_pdf.renderer import PDFRendererfrom my_pdf_package import PDFGeneratorclass PDFHandler(APIView):renderer_classes = (PDFRenderer, )def get(self, request):pdf = PDFGenerator('foo')headers = {'Content-Disposition': 'filename="foo.pdf"','Content-Length': len(pdf),}return Response(pdf,headers=headers,status=status.HTTP_200_OK)```### With two or more renderer_classes```python# coding: utf - 8from rest_framework import statusfrom rest_framework.response import Responsefrom rest_framework.renderers import JSONRendererfrom rest_framework.views import APIViewfrom drf_pdf.response import PDFResponsefrom drf_pdf.renderer import PDFRendererfrom my_pdf_package import get_pdfclass PDFHandler(APIView):renderer_classes = (PDFRenderer, JSONRenderer)def get(self, request, pdf_id):pdf = get_pdf(pdf_id)if not pdf:return Response({'error': 'Not found'},status=status.HTTP_404_NOT_FOUND)return PDFResponse(pdf=pdf,file_name=pdf_id,status=status.HTTP_200_OK)```
Package: drf-pdf-renderer
DRF PDF RendererA simplistic/very extendable pdf renderer.If you use or like the project, clickStarandWatchto generate metrics and i evaluate project continuity.OBSThis project is aBetaversion, however is used in production in a big project (with custom pdf template, and manually fields instead of automatic).however, due to my low availability, updates may take some time.
but i will keep an eye on the PR.Install:pip install drf-pdf-rendererUsage:Add to yourINSTALLED_APPS, insettings.py:INSTALLED_APPS = [  
    ...
    'drf_pdf_renderer',
    ...
]In your file:from rest_framework.settings import api_settings
from drf_pdf_renderer.renderer import PDFRendererPaginated

class YourView(...)
    renderer_classes = (*api_settings.DEFAULT_RENDERER_CLASSES, PDFRendererPaginated)
    pdf_display_fields = (['id', 'Label for ID'], )  # used only in automatic field (caution: refactor planned in futures versions)
    pdf_display_fields = ''  # contains two built-in templates ['pdf/list_landscape.html', 'pdf/list_portrait.html']
    ...
...Mixin for paginated resultsif you have a pagination on DRF, but require a PDF with all registries, you can use this Mixinfrom rest_framework.settings import api_settings
from drf_pdf_renderer.mixin import PdfAllResultsMixin

class YourView(PdfAllResultsMixin, ...)
    pdf_display_fields = (['id', 'Label for ID'], )  # used only in automatic field (caution: refactor planned in futures versions)
    pdf_display_fields = ''  # contains two built-in templates ['pdf/list_landscape.html', 'pdf/list_portrait.html']
    ...
...AdvancedCustom PDF Templatethis project usexhtml2pdf, check documentation of html constructorhere.Changing PDF title# First way
class YourView(...)
    pdf_title = 'My Title'

# Second way
class YourView(...)
    def pdf_get_title(self, data, context)
        return ''Changing PDF download name# First way
class YourView(...)
    pdf_filename = 'My Title'

# Second way
class YourView(...)
    def pdf_get_filename(self, pdf, data)
        return ''Custom data to render context- By default `data`, `request`, `title` and `fields` will always be present (but can be rewrited)
# Second way
class YourView(...)
    def pdf_mount_context(data)
        return {'adm': True}
Package: drf-permission-rules
drf-permission-rulespermission rules for DRF base on drf access policyInstallationpip install drf-permission-rulesUsageViewSet permissionsclass UserViewSet(ModelViewSet, PermissionsActionMixin):
    ...

    @action(methods=["GET", "POST"], detail=False)
    def some_action(self, request, *args, **kwargs):
        ...


GET /api/users/permissions
Response:
{
    "create": true,
    "list": true,
    "some_action": false
}Multiple ViewSet permissions# views.py
class UserViewSet(ModelViewSet, PermissionsActionMixin):
    ...

class BookViewSet(ModelViewSet, PermissionsActionMixin):
    ...

class AuthorViewSet(ModelViewSet, PermissionsActionMixin):
    ...


# urls.py
urlpatterns = [
    ...
    path("api/", include("permission_rules.urls")),
]


GET /api/users/permissions
Response:
{
    "User": {
        "create": true
        "list": true,
        "some_action": false
    }
    "Book": {
        "create": true,
        "list": true
    },
    "Author": {
        "create": false,
        "list": true
    }
}SpeedupYou can get permissions from a file instead of a database.# settings.py


PERMISSION_RULES_SETTINGS = {
    "use_file_instead_db": true,
    "permission_rules_file_path": "/path/to/permissions.json"
}
Package: drf-pipeline-views
Django REST Framework Pipeline Viewspipinstalldrf-pipeline-viewsDocumentation:https://mrthearman.github.io/drf-pipeline-views/Source Code:https://github.com/MrThearMan/drf-pipeline-views/Inspired by a talk onThe Clean Architecture in Pythonby Brandon Rhodes,drf-pipeline-viewsaims to simplify writing testable API endpoints withDjango REST frameworkusing thePipeline Design Pattern.The main idea behind the pipeline pattern is to process data in steps. Input from the previous step
is passed to the next, resulting in a collection of "data-in, data-out" -functions. These functions
can be easily unit tested, since none of the functions depend on the state of the objects in the other parts
of the pipeline. Furthermore, IO can be separated into its own step, making the other parts of the
logic simpler and faster to test by not having to mock or do any other special setup around the IO.
This also means that the IO block, or in fact any other part of the application, can be replaced as long as the
data flowing through the pipeline remains the same.frompipeline_viewsimportBasePipelineViewfrom.my_serializersimportInputSerializer,OutputSerializerfrom.my_validatorsimportvalidatorfrom.my_servicesimportio_func,logging_func,integration_funcclassSomeView(BasePipelineView):pipelines={"GET":[InputSerializer,validator,io_func,integration_func,logging_func,OutputSerializer,],}Have a look at thequickstartsection in the documentation on basic usage.
Package: drfpolicy
OverviewAn ad-hoc DRF policy service to assist with complex authorization requirementsRequirementsPython (2.7, 3.3, 3.4)Django (1.6, 1.7, 1.8)Django REST Framework (2.4, 3.0, 3.1)InstallationInstall usingpip…$pipinstalldrfpolicyExampleTODO: Write example.TestingInstall testing requirements.$pipinstall-rrequirements.txtRun with runtests.$./runtests.pyYou can also use the excellenttoxtesting tool to run the tests
against all supported versions of Python and Django. Install tox
globally, and then simply run:$toxDocumentationTo build the documentation, you’ll need to installmkdocs.$pipinstallmkdocsTo preview the documentation:$mkdocsserveRunningat:http://127.0.0.1:8000/To build the documentation:$mkdocsbuild
Package: drf-polymorphic
DRF-polymorphicVersion:1.0.0Source:https://github.com/maykinmedia/drf-polymorphicKeywords:django, rest, polymorphicPolymorphic support for DRF without Django modelsOverviewPolymorphism happens when a resource takes a certain shape depending on the type
of the resource. Usually they have a common base type. The exact type/shape is not
statically known, but depends on the run-time values.Unlikedjango-rest-polymorphicthis implementation doesn’t require the usage ofdjango-polymorphicmodel classes
and can be used even without django models.The implementations also includes the extension forDRF spectacularschema generation.See thedocumentationfor getting started and usage examples.
Package: drf-pretty-exception-handler
Django Rest Framework pretty exception handlerDjango Rest Framework pretty exception handlerDependenciesPython 3.7+Django 2.0+Django Rest Framework 3.10+SetupYou can install the library directly from pypi using pip:$ pip install drf-pretty-exception-handlerEdit your REST_FRAMEWORK settings in settings.py file:REST_FRAMEWORK={...'EXCEPTION_HANDLER':'drf_pretty_exception_handler.exception_handler',...}LicenseFree software: MIT licenseFeaturesDefault Django Rest Framework exception handler return errors in different formats.Examples:
Response onraise exceptions.APIException.{"detail":"A server error occurred."}Response onraise exceptions.ValidationError.["Invalid input."]Response onraise exceptions.ValidationErrorif error in field serializator.{"email":["This field is required."]}Response onraise exceptions.ValidationErrorin serializator.validate().{"non_field_errors":["Passwords does not match"]}This greatly complicates error handling in the frontend. This package provide own format of errors.{"status_code":500,"errors":{"non_field_errors":["A server error occurred."]}}{"status_code":400,"errors":{"non_field_errors":["Invalid input."]}}{"status_code":400,"errors":{"email":["This field is required."]}}{"status_code":400,"errors":{"non_field_errors":["Passwords does not match"]}}And this package handle default Python exceptions.l=[1,2,3,4]l[10]{"status_code":500,"errors":{"non_field_errors":["IndexError: list index out of range"]}}CreditsThis package was created withCookiecutterand theaudreyr/cookiecutter-pypackageproject template.