Saravanan666/pypi-org huggingface dataset:
Package: drf_base64
DRF-Base64provides a set of serializers to handle Bas64-encoded
files.Compatibility MatrixDRF-Base64is compatible with the following matrixPy 3.5Py 3.6Py 3.7Django 2.0DRF 3.7+DRF 3.7+DRF 3.7+Django 2.1DRF 3.7+DRF 3.7+DRF 3.7+Django 2.2DRF 3.7+DRF 3.7+DRF 3.7+InstallationDRF-Base64is compatible with Python 3.5+ as well as Django 2.0+ and
DRF 3.7+For previous versions of Python and/or Django, please see theV1.x
branchWith pippip installdrf-base64From sourceWithin the source directory:python setup.py installField SerializersDRF-Base64provides aBase64FileFieldand aBase64ImageFieldvery similar to DRF’sFileFieldandImageFieldwith the added
functionality of accepting base64-encoded file strings as input. If
those serialiers receive an url (ie: when updating a record containing a
file without modifying that said file), it will leave the existing value
untouched.Example usage:from rest_framework import serializers
from base64.fields import Base64ImageField

from .models import Product


class ProductSerializer(serializers.ModelSerializer):

    picture = Base64ImageField(required=False)

    class Meta:
        model = Product
...Model SerializersDRF-Base64also provides aModelSerializerand anHyperlinkedModelSerializeralso similar to DRF’s ownModelSerializerandHyperlinkedModelSerializerwith the added
functionality of mappingdjango.db.models.FileField’s toBas64FileField’s anddjango.db.models.ImageField’s toBase64ImageField’s.Example usage:from drf_base64.serializers import ModelSerializer

from .models import Product


class ProductSerializer(ModelSerializer):

    class Meta:
        model = Product
...Mixinsdrf_base64.fields.Base64FieldMixinIf you’d like to enable base64 uploading of file for other field types
thanFileFieldorImageField,DRF-Base64providesBase64FieldMixinto let you do just that.drf_base64.serializers.Base64ModelSerializerMixinIf you wish to useBase64FileFieldandBase64ImageFieldas
default for model serializers other than the ones provided,DRF-Base64also providesBase64ModelSerializerMixinthat you can
apply on any other model serializer as long as they use`serializer_field_mapping<http://www.django-rest-framework.org/api-guide/serializers/#serializer_field_mapping>`__.License information availablehere.Contributors code of conduct is availablehere. Note that
this COCwillbe enforced.
Package: drf-base64-binaryfield
drf-base64-binaryfieldFeaturesThis package provides aBase64BinaryFieldfor use with Django REST Framework serializers.It allows you to:Serialize binary data into base64 strings for use in JSON responsesDeserialize base64 strings back into binary dataOptionally use url-safe base64 encoding (replacing+and/with-and_)Validate the length of the binary dataWhy?because JSON does not support binary data, and base64 is a common way to represent binary data in JSON.ConsiderationsBase64 encoding isn't very space efficient.If you need to send a lot of binary data quite often, you may want to consider using a more efficient serialization format instead of JSON, such asMessagePack. There is a MessagePack serializer for Django REST Framework available:django-rest-framework-msgpack.If you only occasionally need to send binary data then base64 encoding is probably fine for your use case. This package may be suitable for you.RequirementsPython 3.9+Django 3.2+Django REST Framework 3.14+InstallationYou can installdrf-base64-binaryfieldviapipfromPyPI:$pipinstalldrf-base64-binaryfieldUsageIn this example, we need to send a cryptographic challenge to the client that consists of raw bytes.
Wouldn't it be convenient if there was a way to send this data as part of JSON response?We can useBase64BinaryFieldprovided by this package to serialize the binary data into a base64 string, which can be sent as part of a JSON response.fromrest_frameworkimportserializersfromdrf_base64_binaryfield.fieldsimportBase64BinaryFieldclassChallengerSerializer(serializers.Serializer):# This field accepts a Python bytes object and serializes it into a base64 string. Or it can deserialize a base64 string back into a bytes object.challenge=Base64BinaryField()serializer=ChallengerSerializer(instance={'challenge':b'\x00\x01\x02\x03'})print(serializer.data)# {'challenge': 'AAECAw=='}Web-safe encodingIf you want to use web-safe base64 encoding, you can seturl_safe=True:classCryptographicChallengeSerializer(serializers.Serializer):challenge=Base64BinaryField(url_safe=True)Binary data size validationThis package also supports validating the size of the decoded binary data:classExampleSerializer(serializers.Serializer):# This field will only accept binary data that is between 16 and 32 bytes longexample_binary=Base64BinaryField(min_size=16,max_size=32)ExtendingBase64BinaryFieldYou can extendBase64BinaryFieldto create your own custom fields. You may want to unpack the binary data into a different format, for example.importstructclassCustomBinaryField(Base64BinaryField):defto_internal_value(self,data):binary_data=super().to_internal_value(data)# Do something with the binary data...# For example: unpack it as a little-endian, 32-bit unsigned integerreturnstruct.unpack('<I',binary_data)[0]ContributingContributions are very welcome.
To learn more, see theContributor Guide.LicenseDistributed under the terms of theMIT license,drf-base64-binaryfieldis free and open source software.IssuesIf you encounter any problems,
pleasefile an issuealong with a detailed description.CreditsThis project was generated from@OmenApps'sCookiecutter Django Packagetemplate.
Package: drf-base64-filename
drf-base64-filenamedrf-base64-filenameprovides Serializer fields for using base64-encoded files with file names.SetupInstalldrf-base64-filenameto your Python environmentpipinstalldrf-base64-filenameUsageSample ModelclassSampleBase64ImageModel(models.Model):parent=models.ForeignKey(SampleParentModel,on_delete=models.CASCADE,related_name='image_set',blank=True,null=True,)image=models.ImageField(blank=True)classSampleBase64FileModel(models.Model):parent=models.ForeignKey(SampleParentModel,on_delete=models.CASCADE,related_name='file_set',blank=True,null=True,)file=models.FileField(blank=True)Serializer FieldclassSampleNamedBase64ImageSerializer(serializers.ModelSerializer):image=NamedBase64ImageField(required=False,allow_null=True)classMeta:model=SampleBase64ImageModelfields=('id','image',)classSampleNamedBase64FileSerializer(serializers.ModelSerializer):file=NamedBase64FileField(required=False,allow_null=True)classMeta:model=SampleBase64FileModelfields=('id','file',)Sample request data{"image":{"file_name":"pby.jpg","encoded_str":"aHR0cHM6Ly9naXRodWIuY29tL2xlZWhhbnllb25n"}}Sample response data{"image":"http://test/media/pby.jpg"}Testingcdtest_project
pipinstall-rrequirements.txt
pytestContributingAs an open source project, we welcome contributions.
The code lives onGitHub
Package: drf-batch-requests
Quick startexamples:curl -X POST \
  http://127.0.0.1:8000/batch/ \
  -H 'cache-control: no-cache' \
  -H 'content-type: application/json' \
  -d '{"batch": [
    {
        "method": "get",
        "relative_url": "/test/",
        "name": "yolo"
    },
    {
        "method": "post",
        "relative_url": "/test/?id={result=yolo:$.id}&ids={result=yolo:$.data.*.id}",
        "body": {"data": {"id": "{result=yolo:$.id}", "ids": "{result=yolo:$.data.*.id}"}, "test": "yolo"}
    },
    {
        "method": "post",
        "relative_url": "/test/",
        "body": "{\"data\": 42}",
        "omit_response_on_success": true
    },
    {
        "method": "options",
        "relative_url": "/test/"
    }
]
}'using file uploadingcurl -X POST \
  http://127.0.0.1:8000/batch/ \
  -H 'cache-control: no-cache' \
  -H 'content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' \
  -F 'batch=[
    {
        "method": "get",
        "relative_url": "/test/",
        "name": "yolo"
    },
    {
        "method": "post",
        "relative_url": "/test/?id={result=yolo:$.id}&ids={result=yolo:$.data.*.id}",
        "body": {"data": "{result=yolo:$.data.*.id}", "test": "yolo"},
        "attached_files":{"file": "a.jpg"}
    },
    {
        "method": "post",
        "relative_url": "/test/",
        "body": "{\"data\": 42}",
        "omit_response_on_success": true,
        "attached_files":["a.jpg", "b.png"]
    },
    {
        "method": "options",
        "relative_url": "/test/"
    }
]' \
  -F b.png=@2476.png \
  -F a.jpg=@check_133.pdfFuture features:add support for requests pipelining. use responses as arguments to
next requests (done)build graph based on requests dependencies & run simultaneously
independent.[STRIKEOUT:switchable atomic support. true - all fails if something
wrong. else - fail only dependent (can be very hard to support on
front-end side, but for now seems as good feature)] run all requests
in single transaction. (done)[STRIKEOUT:use native django. we don’t use complicated things that
require drf for work. all can be done with “naked” django.] (since we
validate requests with drf serializers, it’s better to leave as it
is).support files uploading (done)Dependencies:Django starting from 2.2Django rest framework
Package: drf-blog
Django BlogDjango Blog is a Django app that allows you to create and manage blog applications.Quick StartUsageAfter following the Quick Start guide, you're now ready to use the Django Blog app in your project. You can start creating, editing, and managing blog posts through the Django admin panel or through the provided APIs.Install the package from PyPI:pipinstalldrf-blogAdd "blog" to theINSTALLED_APPSsetting in your project'ssettings.pyfile:INSTALLED_APPS=[..."django_summernote","rest_framework","blog",]Include the blog's URLs by adding the following line to your project'surls.pyfile:fromdjango.urlsimportpath,includeurlpatterns=[...path("",include("blog.urls")),]Set up the necessary media and static file configurations in your project'ssettings.pyfile:MEDIA_URL='/media/'MEDIA_ROOT=os.path.join(BASE_DIR,'media')STATIC_ROOT=os.path.join(BASE_DIR,'static')STATIC_URL="static/"Run database migrations to create the Blog models:pythonmanage.pymigrateNow you are ready to use the Django Blog app in your project.Contributing:Feel free to contribute to this project by submitting issues, fork the project and creating pull requests, or simply by suggesting new features.LicenseThis project is licensed under the MIT License
Package: drf-body-token
Provide aDjango REST Frameworkauthentication class, to look for token
in HTTP request’s body, instead of HTTP header.This use case is uncommon and may be less secure,
but some REST client application doesn’t let customize HTTP header,
and hence, user cannot setAuthorizationheader.
One such client isBlynk WebhookWidget.Installpip3installdrf-body-tokenDRF Body Tokenonly supports Python 3.5+.UsageAddBodyTokenAuthenticationtoauthentication_classesatrribute of your viewset.
Example:fromdrf_body_token.authenticationimportBodyTokenAuthenticationclassMyAwesomeViewSet(GenericViewSet):authentication_classes=(TokenAuthentication,BodyTokenAuthentication)You can also add it toREST_FRAMEWORK['DEFAULT_AUTHENTICATION_CLASSES']settings, to make it available for every viewset.By default,BodyTokenAuthenticationlooks foraccess_tokenfield in request’s body. That body can be, for example:{"name":"Cuckoo","type":"bird","access_token":"Vừng ơi mở ra"}If you want it to look for another field, add this to yoursettings.pyfile:DRF_BODY_TOKEN_FIELD='your_field'
Package: drf-buzz
drf-buzzThis is an extension of thepy-buzzpackage.It adds extra functionality especially for DRF. Predominately, it adds
the ability to jsonify an exceptionInstallationpip install drf-buzzUsageAdddrf-buzzexception handler insettings.py:REST_FRAMEWORK={...'EXCEPTION_HANDLER':'drf_buzz.exception_handler'...}Usepy-buzzexceptions in your DRF viewsets:importdrf_buzzfromrest_frameworkimportstatus,viewsetsclassMyException(drf_buzz.DRFBuzz):status_code=status.BAD_REQUESTclassMyViewSet(viewsets.ViewSet):deflist(self,request):raiseMyException('Not implemented yet.')TestsTo run the test suite execute the following command in package root
folder:python setup.py test
Package: drf-cache
drf-cacheDjango Rest Framework Caching ToolsContentHow to useRequirementsDevelop LogHow to useRequirementsdjango >= 2.0djangorestframework >= 3.9.0redisDevelop Log2019-09-10publish test results and coverage results to the Azure in pipelineupload to pypi by azureformat the codeuse tox and flake8 to build and test2019-09-09Use the Azure Pipeline to building and assemble
Package: drf-camel-case
Django REST Framework JSON CamelCase with orjson supportCamel case JSON support for Django REST framework with orjson.InstallationAt the command line:$ pip install drf-camel-caseAdd the render and parser to your django settings file.# ...REST_FRAMEWORK={'DEFAULT_RENDERER_CLASSES':('drf_camel_case.render.CamelCaseJSONRenderer','drf_camel_case.render.CamelCaseBrowsableAPIRenderer',# Any other renders),'DEFAULT_PARSER_CLASSES':(# If you use MultiPartFormParser or FormParser, we also have a camel case version'drf_camel_case.parser.CamelCaseFormParser','drf_camel_case.parser.CamelCaseMultiPartParser','drf_camel_case.parser.CamelCaseJSONParser',# Any other parsers),}# ...Swapping RendererBy default the package usesrest_framework.renderers.JSONRenderer. If you want
to use another renderer (the only possible alternative isrest_framework.renderers.UnicodeJSONRenderer, only available in DRF < 3.0), you must specify it in your django
settings file.# ...JSON_CAMEL_CASE={'RENDERER_CLASS':'rest_framework.renderers.UnicodeJSONRenderer'}# ...Underscoreize OptionsNo Underscore Before NumberAs raised inthis commentthere are two conventions of snake case.# Case 1 (Package default)
v2Counter -> v_2_counter
fooBar2 -> foo_bar_2

# Case 2
v2Counter -> v2_counter
fooBar2 -> foo_bar2By default, the package uses the first case. To use the second case, specify it in your django settings file.REST_FRAMEWORK={# ...'JSON_UNDERSCOREIZE':{'no_underscore_before_number':True,},# ...}Alternatively, you can change this behavior on a class level by settingjson_underscoreize:fromdrf_camel_case.parserimportCamelCaseJSONParserfromrest_framework.genericsimportCreateAPIViewclassNoUnderscoreBeforeNumberCamelCaseJSONParser(CamelCaseJSONParser):json_underscoreize={'no_underscore_before_number':True}classMyView(CreateAPIView):queryset=MyModel.objects.all()serializer_class=MySerializerparser_classes=(NoUnderscoreBeforeNumberCamelCaseJSONParser,)Ignore FieldsYou can also specify fields which should not have their data changed.
The specified field(s) would still have their name change, but there would be no recursion.
For example:data={"my_key":{"do_not_change":1}}Would become:{"myKey":{"doNotChange":1}}However, if you set in your settings:REST_FRAMEWORK={# ..."JSON_UNDERSCOREIZE":{# ..."ignore_fields":("my_key",),# ...},# ...}Themy_keyfield would not have its data changed:{"myKey":{"do_not_change":1}}Running TestsTo run the current test suite, execute the following from the root of he project:$ python -m unittest discoverLicenseFree software: BSD licenseHistory1.0.2 (2021-10-21)Update with upstream changes1.0.1 (2021-10-21)Release fix1.0.0 (2021-10-21)First release
Package: drf-case-middleware
DRF Case MiddlewareCamel case to snake case and snake case to camel case for Django REST framework.Getting Started$pipinstalldrf-case-middlewareAdd the render and parser to your django settings file.MIDDLEWARE=[# ... other middlewares'drf_case_middleware.middlewares.CaseMiddleware',]REST_FRAMEWORK={'DEFAULT_RENDERER_CLASSES':('drf_case_middleware.renders.CaseJSONRenderer','drf_case_middleware.renders.CaseBrowsableAPIRenderer',# ... other renderers),'DEFAULT_PARSER_CLASSES':('drf_case_middleware.parsers.CaseFormParser','drf_case_middleware.parsers.CaseMultiPartParser','drf_case_middleware.parsers.CaseJSONParser',# ... other renderers),}NoteThis project is based on thedjangorestframework-camel-caseproject.LicenseMIT License
Package: drfchangemgmt
OverviewDjango Rest Framework change managementRequirementsPython (2.7, 3.3, 3.4)Django (1.6, 1.7, 1.8)Django REST Framework (2.4, 3.0, 3.1)InstallationInstall usingpip…$pipinstalldrfchangemgmtExamplefrom.modelsimportActorfromdrfchangemgmtimportChangeMgmtSerializerMixinfromrest_framework.serializersimportModelSerializerclassActorSerializer(ChangeMgmtSerializerMixin,ModelSerializer):""" Actor model serializer """classMeta(object):""" DRF ModelSerializer meta object """model=Actor......defpre_save(..):changed=model.get_changed_fields()if'superuser_role'inchanged:raisePermissionDenied("you can't do that!")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_changemgmt
OverviewDjango Rest Framework dirty trackingRequirementsPython (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_changemgmtExamplefrom.modelsimportActorfromdrf_changemgmtimportChangeMgmtSerializerMixinfromrest_framework.serializersimportModelSerializerclassActorSerializer(ChangeMgmtSerializerMixin,ModelSerializer):""" Actor model serializer """classMeta(object):""" DRF ModelSerializer meta object """model=Actor......defpre_save(..):changed=model.get_changed_fields()if'superuser_role'inchanged:raisePermissionDenied("you can't do that!")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-channels
DRF ChannelsDRF Channels provides a simple django-channels bindings and consumer
mixin that can be used to automatically listen and send to groups
everytime a Resource is created/updated/deleted.It requires Python >= 3.5, Channels >= 2.0, Django >=1.11, and Django Rest Framework 3.xThis is like a port of Channels 1.x’sData_BindingandChannels APIwith few differences.The data sent to the clients are based on the Serializer class
provided.How does it work?The API exposes aResourceBindingclass that holds your Model, Serializer class, and Consumer class.
Your Consumer class needs to be a subclass ofAsyncJsonWebsocketConsumerfrom channels and
have aAsyncConsumerActionMixinmixin.TheResourceBindingclass bindspre_save,pre_delete,post_save, andpost_deletesignals
to your model.  These signals will then send to the corresponding Consumer groups that listens to your stream.The first thing you need to do is connect to your consumer and pass the actions you want to subscribe to
via url parameters.For example, you want to subscribe to the create and update actionsJobResource (Model),
and the channels route is/jobs/, You will connect to the websocket like below,
if you are usingChannels Websocket Wrapper:constwebSocketBridge=newchannels.WebSocketBridge()webSocketBridge.connect('/jobs/?subscribe=create,update')You then need to add a listener on your webSocketBridge to receive the messages sent by the Consumer
via signals.webSocketBridge.socket.addEventListener('message',function(event){})
Package: drf-channels-oneway-ws
DRF channels one-way WSSimple one-way bindings for django-channels with some specific support for django-rest-framework serializers and websockets. I.e. enrich your existing API with push notifications.Installationpipenv install drf-channels-oneway-wsorpip install drf-channels-oneway-wsUsageBindingsfromdjango.dbimportmodelsfromrest_frameworkimportserializersfromchannels_oneway.bindingsimportBindingclassFamily(models.Model):name=models.CharField(max_length=255)classBird(models.Model):name=models.CharField(max_length=255)family=models.ForeignKey('Family',models.CASCADE)classBirdSerializer(serializers.ModelSerializer):classMeta:model=Customerfields=('__all__')classBirdBinding(Binding):model=Birdstream='birds'serializer=BirdSerializer@classmethoddefgroup_names(cls,instance):return[instance.family.name]classFamilyBinding(Binding):"""example of a binding not using a drf serializer"""model=Familystream='bird-families'@classmethoddefgroup_names(cls,instance):return[instance.name]defserialize_data(self,instance):return{'id':instance.id,'name':instance.name}Now you make sure you have a WebsocketConsumer, which does something likeself.channel_layer.group_add('thrushes', self.channel_name)in its connect coroutine.Family.objects.create(name='thrushes')will then cause the following to be sent over the associated websocket:{"stream":"bird-families","payload":{"action":"create","data":{"id":1,"name":"thrushes"},"model":"your_app.family","pk":1}}Upon modification ("action": "update") or deletion ("action": "delete") you will receive messages with an equal structure.RegistrationIn order to let the bindings register their signals make sure they are imported at some point. In case you use a dedicated file, import it fromAppConfig.readyjust like your signals.HelpersIn order to send a ws message from outside a binding, but using the same format (stream + payload) (and also the drf json encoder) use the asyncchannels_oneway.utils.groupSend(group, stream, payload)or its sync equivalentgroupSendSync.ContributingInstallationgit clone git@github.com:evocount/drf-channels-oneway-ws.gitcd drf-channels-oneway-wspipenv install --devRunning testspipenv run pytest --covLicenseThis project is licensed under theMIT License.
Package: drf-chaos
drf-chaos extensiondrf-chaos is a small collection of decorators and middlewares for
testingDjango REST FrameworkAPI under unexpected circumstances.SettingsDRF_CHAOS_ENABLEDDecoratorsDelayDelay response of a specific amount of milliseconds@delay(rate, milliseconds)Params:rate: probability that an unexpected event happensmilliseconds: suspend execution of the current thread for the given
number of millisecondsErrorReturn a different response HTTP status code@error(rate, status)Params:rate: probability that an unexpected event happensstatus: integer corresponding to any valid HTTP status code. SeeDRF HTTP status codesMimeReturn a random Mime Content-type@mime(rate)Params:rate: probability that an unexpected event happensChaosApply a random unexpected event to the HTTP response. (A delay between 0
to 3 second and a random HTTP status code)@chaos(rate)Params:rate: probability that an unexpected event happensMiddlewaresChaosMiddlewareExamplefrom rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView

from drf_chaos.decorators import delay, error, mime, chaos


class DelayApiView(APIView):
    @delay(rate=0.5, milliseconds=700)
    def get(self, request):
        return Response(status=status.HTTP_204_NO_CONTENT)


class ErrorApiView(APIView):
    @error(rate=0.5, status=500)
    def get(self, request):
        return Response(status=status.HTTP_204_NO_CONTENT)


class MimeTypeApiView(APIView):
    @mime(rate=0.5)
    def get(self, request):
        return Response(status=status.HTTP_204_NO_CONTENT)


class ChaosApiView(APIView):
    @chaos(rate=0.5)
    def get(self, request):
        return Response(status=status.HTTP_204_NO_CONTENT)RequirementsPython (2.7)Django (1.6+, 1.7+, 1.8)InstallationInstall usingpippip install drf-chaosAdd ‘drf_chaos’ to your INSTALLED_APPS setting.INSTALLED_APPS = (
    ...
    'drf_chaos',
)
Package: drf-client
django-drf-clientDynamic client based on coreapi and drf inspired by dotmap and java scriptExampledef get_client(url,username,password):
    from drf_client.client import DrfClient
    return DrfClient(url, username, password)
  
drfc = get_client('http://server-dns-name','username','password')
doc(drfc) # it will list possible options based on server

# Example
drfc.api.<app-name>.<model>.create(**params)
drfc.api.<app-name>.<model>.list(**params).all()
drfc.api.<app-name>.<model>.list(**params).first()