Saravanan666/pypi-org huggingface dataset:
Package: drfrequests
drfrequestsDjango Rest Framework RequestsDocumentationInstallationInstall using pip:pip install drfrequestsAdd 'rest_framework_docs' to yourINSTALLED_APPSsetting:INSTALLED_APPS = [
    ...
    'rest_framework_requests',
]Finally include therest_framework_docsurls in yoururls.py:urlpatterns = [
    ...
    path('docs/', include('rest_framework_requests.urls')),
]SettingsYou can find detailed information about the package's settings atthe docs.REST_FRAMEWORK_DOCS = {
    'HIDE_DOCS': True  # Default: False
}CreditsThis project is a frok ofhttps://github.com/manosim/django-rest-framework-docswhich is a fork ofhttps://github.com/marcgibbons/django-rest-framework-docspackaging: Update VersionUpdating your distribution Down the road, after you’ve made updates to your distribution and wish to make a new release:pip install build
pip install twineincrement the version number in yoursetup.cfgfile$ python3 -m buildUpload package to the Python Package Index:$ twine upload dist/*see:https://packaging.python.org/tutorials/packaging-projects/For developmentpip install -e ../drfrequests/
Package: drf-requests-jwt
This is a simple helper used to communicate between Django instances.It is suited to work well with Django Rest Framework API points and serializers.FeaturesAuthenticate with JWT if not alreadyCache JWT with different backends (for now Django Cache and File System)Request all pages, before delivering the resultDeserialize the result with standard DRF serializer classesInstall itpip install drf_requests_jwtHow to use itAssuming there is adevicespaginated API point on another Django instance and you need all devices fetched.Then you’ll inherit fromHttpRequestServiceand implement the abstract methods something along these lines:from apps.devices.models import Device  # Your Device Django model.
from rest_framework import serializers

from drf_requests_jwt.services import HttpRequestService


class DeviceSerializer(serializers.Serializer):
    eui = serializers.CharField()

    def create(self, validated_data):
        return Device(**validated_data)


class DeviceHttpRequestService(HttpRequestService):
    obtain_jwt_allowed_fail_attempts = 3
    cache_backend_class = 'drf_requests_jwt.backends.django_cache.DjangoCacheBackend'

    def _get_base_url(self):
        return 'https://example.com'

    def _get_jwt_login_url_path(self):
        return 'api/v1/auth/jwt/login/'

    def _get_url_path(self):
        return 'api/v1/devices/'

    def _get_username(self):
        return 'john'

    def _get_password(self):
        return 'snow'

    def _get_params(self):
        return {
            'param1': 'val1',
            'param2': 'val2',
        }

    def get_deserialized_data(self):
        device_list = []

        for device in self.get_results_from_all_pages():
            serializer = DeviceSerializer(data=device)
            if serializer.is_valid():
                device_list.append(serializer.save())

        return device_listNow in your business logic where you need the list of devices you’ll call it like this:devices =DeviceHttpRequestService().get_deserialized_data()MixinsThere is a mixin helping with deserialization.from drf_requests_jwt.deserializers import ObjectListDeserializerMixin
from apps.devices.serializers import DeviceSerializer  # Your device serializer.

class DeviceDeserializerMixin(ObjectListDeserializerMixin):
    serializer_class = DeviceSerializer

class DeviceHttpRequestService(DeviceDeserializerMixin, HttpRequestService):
    # ... Other abstract methods implemented

    def get_deserialized_data(self):
        return self.get_deserialized_object_list()ConclusionThis is quite a specific helper that works well for our use case, but I think it can be easily adjusted to fit other needs.Please feel free to bring your pull requests. Thanks.
Package: drf-restricted-fields
FeaturesRestrict fields returned by DRF serializers using theonlyquery parameterGET http://127.0.0.1:8000/api/users/?only=id&only=nameSerialize only theidandnamefields.{
    "count": 198,
    "next": "http://127.0.0.1:8000/api/users/?only=id&only=name&page=1",
    "previous": null,
    "results":[
        {
            "id": 1,
            "name": "Test"
        },
        ...
    ],
}Defer fields returned by DRF serializers using thedeferquery parameterGET http://127.0.0.1:8000/api/users/?defer=name&defer=ageSerialize only theidandnamefields.{
    "count": 198,
    "next": "http://127.0.0.1:8000/api/users/?defer=name&defer=age&page=1",
    "previous": null,
    "results":[
        {
            "id": 1,
        },
        ...
    ],
}Free software: MIT licenseDocumentation:https://drf-restricted-fields.readthedocs.io.
Package: drfrf
drfrfDjango REST framework - redux-form connectorInstallation$ pipenv install drfrfUsageImport and use one ofValidateCreateMixinorValidateUpdateMixin:fromdrfrfimportValidateCreateMixin,ValidateUpdateMixinfromrest_frameworkimportviewsetsfromrest_framework.decoratorsimportdetail_route,list_routefromshop.modelsimportCartItemfromshop.serializersimportCartItemSerializerclassCartItemViewSet(ValidateCreateMixin,ValidateUpdateMixin,viewsets.ModelViewSet):queryset=CartItem.objects.all()serializer_class=CartItemSerializer@list_route(methods=["post"],url_path="validate")defvalidate_list(self,request):returnself.validate_create(request)@detail_route(methods=["post"],url_path="validate")defvalidate_detail(self,request,**kwargs):returnself.validate_update(request,**kwargs)Posting invalidate data to/items/validatewould return error messages:HTTP/1.1400Bad RequestContent-Length:99Content-Type:application/json{"amount":["Your current credit is 36€, please top-up your account before adding to your cart."]}Browse the complete example here:https://github.com/Theodo-UK/drfrf/tree/master/example/backend/shopAPIValidateCreateMixinExposes one method:validate_createtakesRequest, validates the input data against the provided serializer and returns aResponse.ValidateUpdateMixinExposes one method:validate_updatetakesRequestwith kwargs, validates the input data against the provided serializer and returns aResponse.Frontend integrationIf you're using redux-form in your frontend, check outdrfrf for the front.
Package: drf-role
drf_role is a small, simple and lightweight role manager who can manage READ/WRITE & NoAccess permissions
for each role. It basically work with DRF internal system like permission class, object level permission, etc.Detailed documentation is in the “docs” directory.Quick startAdd “polls” to your INSTALLED_APPS setting like this:INSTALLED_APPS = [
    ...
    'drf_role',
]Include the polls URLconf in your project urls.py like this:url(r'^api/<YOUR VERSION NUMBER>/drf-role/', include('drf_role.urls')),Runpython manage.py migrateto create the drf_role models.Start the development server and visit,http://127.0.0.1:8000/api/v1/roles/http://127.0.0.1:8000/api/v1/permissions/http://127.0.0.1:8000/api/v1/accesses/http://127.0.0.1:8000/api/v1/all-urls/Please look up on docs for details…
Package: drf-rw-serializers
Generic views, viewsets and mixins that extend the Django REST Framework ones
adding separated serializers for read and write operations.DocumentationThe full documentation is athttps://drf-rw-serializers.readthedocs.org.LicenseThe code in this repository is licensed under the MIT unless
otherwise noted.Please seeLICENSE.txtfor details.How To ContributeContributions are very welcome.Please readHow To Contributefor details.PR description template should be automatically applied if you are sending PR
from github interface; otherwise you can find it it atPULL_REQUEST_TEMPLATE.mdIssue report template should be automatically applied if you are sending it
from github UI as well; otherwise you can find it atISSUE_TEMPLATE.mdReporting Security IssuesPlease do not report security issues in public. Please emailcontact@vinta.com.br.Getting HelpHave a question about this repository? Please create an issue!Commercial SupportThis project, as other Vinta open-source projects, is used in products of Vinta
clients. We are always looking for exciting work, so if you need any commercial
support, feel free to get in touch:contact@vinta.com.brCopyright (c) 2020 Vinta Serviços e Soluções Tecnológicas LtdaChange LogUnreleased[1.1.1] - 2024-02-07FixedDjango 5.0 support fixed[1.1.0] - 2023-12-22AddedSupport Django 4.1Support Django 4.2Support Django 5.0Support Python 3.11Support Python 3.12FixedFixes CI workflow by migrating to GitHub ActionsFixes ReadTheDocs failing build[1.0.5] - 2022-03-02AddedSupport Django 3.2Support Django 4.0Support Python 3.10[1.0.4] - 2020-09-02AddedMove from model-mommy to model-bakerySupport Django 3.1RemovedDrop support to Django 1.10Drop support to Python 2.7Drop support to Python 3.6[1.0.2] - 2019-08-30AddedSupport Django 2.2[1.0.1] - 2019-01-16AddedFixed bug in retrieval of success headers in create endpoints (breaking change)Updated dependencies[0.1.1] - 2018-11-12AddedSupport Django 2.1[0.1.0] - 2018-02-21AddedFirst release on PyPI.
Package: drfs
drfsFree software: MIT licenseDocumentation:https://drfs.readthedocs.ioFile systemsAll filesystems defined in this package should:accept full paths in methods likelsetc.
(fullmeans: including protocol and all other parts of path)return full paths or their lists from methods likelsetc.paths returned from methods likelsshould beDRPathobjects
(DRPathis our version ofpathlib.Pathsupporting remote paths
and few other features)Above functionalities are implemented inFileSystemBaseclass. When adding
a new filesystem, one should subclass from it and set an underlying backend
filesystem asfs_clsattribute (see existing implementations).Relation to fsspecfsspecis an attempt to unify interfaces of various filesystems. It also serves
as a tool thatdaskuses to support them.drfs doesn't agree with fsspec in (at least) one assumption: in fsspec
methods likelsreturn paths without protocol. That's why we can't use
classes that adhere to fsspec directly.However, such classes can (and should) be used as backends for filesystems
defined here in drfs. This way we ensure that paths handled by drfs can
also be handled bydask(because importing a backend filesystem that adheres
to fsspec makes it available for Dask).For example,drfs.filesystems.s3.S3Filesystemusess3fs.S3FileSystemas backend which adheres to fsspec.FeaturesTODO
Package: drf-safe-jack
[DRF with api history track][docs]修改说明此包会覆盖drf的rest_frame的包下的内容   drf基础库版本为3.9.2主要修改为增加了signal.py 和修改了mixin的update方法 和引入了track_action的历史记录model安装pipinstalldrf-safe-jackADD   增加了通过post方法请求put、patch、delete方法使用方式：在请求头header加入method 写入对应方法put或者patch等即可用post方法访问put等接口method=putADD  增加了自动记录api接口请求历史历史记录基于api设计而非基于model，使用simple-history等包会引入大量的历史记录表，对数据库整体结构不是很友好，所以自己实现了一个，所有的内容保存到history这个model中,采用多线程不影响正常接口的访问速度特性：1.多线程保存2.单个历史表 ，可根据api对应序列化器serializer内的model名来搜索历史记录3.中文支持 自动转换none，单选choice，多选为中文名显示使用方式：#  settins.pyINSTALLED_APPS=[...,'track_actions',]MIDDLEWARE=[...,'track_actions.requestMiddleware.RequestMiddleware',]pythonmanage.pymigratetrack_actions# url.pyurl(u'^api/',include('track_actions.urls')),# 这个路由可自定义# 即可在 api/history 目录下获取到所有的历史记录记录返回内容# 字段预览"table_name":"basic_basicrescue",# 每个 api 里面对应的表名"created_at":"2021-06-26T14:29:04.838753",# 操作日期"instance_id":"424",#实例id"action":"由未填写更新为是",# 操作内容"field_name":"病人-发病时间",# 中文的字段名"user":62# 操作用户id"user_obj":{# 操作用户详情"id":62,"username":"test_006","first_name":"王五",#"department":}查找某个api对应的历史记录方法/api/history/?table_name=basic_basicrescue&instance_id=412# tablename 为表名  instance_id为对应表的实例id
Package: drfsc
drfscversion: 0.0.6An open-source library for a distributed randomised feature selection and classification algorithm.Authors and Contributors:Mark Chiu Chong,Aida Brankovic.Overviewdrfscis an open-source Python implementation of the Distributed Randomised Feature Selection algorithm for Classification problems (D-RFSC). Beside addressing some of the shortcomings of the conventional FS method, its good performance has previously been shown on a range of benchmark datasets. However, to date no Python implementation is available.drfscoffers an easy to use, parallelized probabilistic population-based feature selection scheme that is flexible and can be adapted to a wide range of binary classification problems and is particularly useful for large data problems where model interpretability and model explainability is of high importance. It provides modules for model fitting, evaluation, and visualization. Tutorial notebooks are provided to demonstrate the use of the package.InstallationThe easiest way to install is from PyPI: just usepip install drfscLicenseWe invite anyone interested to use and modify this code under a MIT license.Dependenciesdrfscdepends on the following packages:numpypandasmatplotlibscikit-learnstatsmodelsReferencesThe package has been developed based on research that came out of the Polytechnical University of Milan. The interested reader is referred to [2] for details related to the distribution procedure, and to [1] for a more thorough mathematical overview and for experimental comparisons to various alternate feature selection methods.[1] Brankovic, A., Falsone, A., Prandini, M., Piroddi, L. (2018).A feature selection and classification algorithm based on randomized extraction of model populations[2] Brankovic, A., Piroddi, L. (2019).A distributed feature selection scheme with partial information sharingCitationsThis package is developed in CSIRO’s Australian e-Health Research Centre. If you usedrfscpackage in your research we would appreciate a citation to the appropriate paper(s):For general use ofdrfscpackage you can read/cite the original article.For information/use of the Randomised Feature Selection and classification concept you can read/cite original article [1].For information/use of the Distributed Feature Selection architecture with partial information you can read/cite original article [2].
Package: drf-secure-token
Add “drf_secure_token” to your INSTALLED_APPS setting like this:INSTALLED_APPS = [
    ...
    'rest_framework',
    'drf_secure_token',
]Add following lines to your settings.py:REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.BasicAuthentication',
        'drf_secure_token.authentication.SecureTokenAuthentication',
     ]
}For updating token add this middleware to your MIDDLEWARE_CLASSES:MIDDLEWARE_CLASSES = (
    ...
    'drf_secure_token.middleware.UpdateTokenMiddleware',
)Add UPDATE_TOKEN to your ‘dev’ settings if you don’t want to update token in DEBUG mode:UPDATE_TOKEN = FalseAdd TOKEN_AGE to your settings:TOKEN_AGE = 60*10 # 10 min(Optional) To cleanup dead tokens celery can be used. Way to enable depends from celery version6.1 Celery 4, just enable it with settings:REMOVE_TOKENS_THROUGH_CELERY = True6.2 Celery 5, add periodic task manually:@app.on_after_finalize.connect
def setup_periodic_tasks(sender, **kwargs):
    from drf_secure_token.tasks import DELETE_OLD_TOKENS

    app.conf.beat_schedule.update({
        'drf_secure_token.tasks.delete_old_tokens': DELETE_OLD_TOKENS,
    })Runpython manage.py migrateto create the drf_secure_token models.
Package: drf-sendables
User messages for Django REST Frameworkdrf-sendablesis aDjangoreusable app providing the backend
for dispatching and managing in-site message-like entities. It can be plugged into a Django project,
utilizing any existing user authentication system. The HTTP REST API is implemented usingDjango REST framework.InstallationThe following versions are supported:Python: 3.10 - 3.12Django: 3.0 - 5.0Django REST Framework: 3.10 - 3.14Install viapip:$pipinstalldrf-sendablesAdd it to yourINSTALLED_APPS:INSTALLED_APPS=[# ..."sendables",]Register the app’s URLs under a path of your choice:urlpatterns=[# ...path("some-path/",include("sendables.urls")),]where"some-path/"could be any URL.Optionally, configure the appsettings.Generate and run the database migrations:$pythonmanage.pymakemigrationssendables$pythonmanage.pymigrateUsageYou can find the description of the app’sendpointsin thedocumentation. For customized usage, see the relevantpage.LicenseDistributed under theMIT License.
Package: drf-serializer-cache
Django REST framework serializers speedupSimple short-living cache implementation for DRF serializers.
It solves two issues with DRF serializers:Serializer.fieldsproperty can be extremely slow in some cases.
Such cases include complexModelSerializer, serializer hierarchies
with repeated serializers and recursive serializers.fieldsis cached and computed once per class for each serialization run.
This leads to limitation -fieldsshould not be dynamically adjusted
inside of serializer, which inherits fromSerializerCacheMixin;By default serializers will re-compute object representation event if
they encounter same object with same serializer twice. This can turn
into an issue, if multiple object include same dependent hard-to-serialize
objects. Cache avoid re-computing instance representation if it encounters
same instances multiple times.Performance resultsCache life-time and invalidationCache is designed to be simple and non-error-prone.
Cache is created when top-level serializerto_representationstarts
and is cleaned up once this method is finished. Thus there is no need
for timeouts or complex cache invalidation. No data is shared between
requests.
Thus, following cases will work fine:user=User.objects.get(name='Lee')data_1=UserSerializer(user).data# OrderedDict([('name', 'Lee')])user.name='Bob'user.save()data_2=UserSerializer(user).data# OrderedDict([('name', 'Bob')])UsageUsage should be pretty simple - injectSerializerCacheMixinbefore
inheriting fromSerializerorModelSerializer:fromdrf_serializer_cacheimportSerializerCacheMixinfromrest_frameworkimportserializersclassUserSerializer(SerializerCacheMixin,serializers.ModelSerializer):classMeta:model=Userfields=('id','name')Common pitfallsToo often cache cleanupCache lives in serializer hierarchy root, but it's life-time is defined
by nearest tree node, which inherits fromSerializerCacheMixin.
Ideal situation is when root inherits fromSerializerCacheMixin.
That's whySerializerCacheMixinuses customlist_serializer_class,
which also inherits fromSerializerCacheMixin.
If you use custom list as root of serializer hierarchy - it's recommended
to useSerializerCacheMixinas it's base class.Too many hierarchiesBy default serializers build nice hierarchy by callingbindon their
child serializers. This case can be broken forserializers.SerializerMethodFieldif it uses some serializer without callingbindon it:fromdrf_serializer_cacheimportSerializerCacheMixinfromrest_frameworkimportserializersclassResultSerializer(SerializerCacheMixin,serializers.Serializer):results=serializers.SerializerMethodField()defget_results(self,instance):# recursive serializerserializer=self.__class__(instance.results,many=True)serializer.bind('*',self)# bind call is essential for efficient cache !returnserializer.data
Package: drf-serializer-fields-permissions
OverviewThis package provides a mixin for setting permissions to separate fields of ModelSerializer which usesDRF permission
classes. You can hide or set a field as read-only for specific users.RequirementsPython (3.5, 3.6, 3.7, 3.8, 3.9, 3.10, 3.11)Django (2.0, 2.1, 2.2, 3.0, 3.1, 3.2, 4.0, 4.1, 4.2)Django REST Framework (3.8, 3.9, 3.10, 3.11, 3.12, 3.13, 3.14)InstallationInstall usingpip$pipinstalldrf_serializer_fields_permissionsExampleTo show a field only for staff users you need to addshow_only_tofield to theMetaclass of a serializer.show_only_forfield must be adictwith two keys -fieldsandpermission_classes.permission_classesis alistor atupleof permission classes. You can use built-in DRF permission or create your
own, but you must overridehas_permissionmethod ofBasePermissionclass.fieldsis list or tuple of serializer fields which will be shown only to staff users, in our case.fromrest_frameworkimportserializersfromrest_frameworkimportpermissionsfrom.modelsimportProjectfromfields_permissions.mixinsimportFieldPermissionMixinclassProjectSerializer(FieldPermissionMixin,serializers.ModelSerializer):classMeta:model=Projectfields=('id','name','status','description','team_lead_user')show_only_for={'fields':('team_lead_user',),'permission_classes':(permissions.IsAdminUser,)}write_only_for={'fields':('status','description'),'permission_classes':(permissions.IsAdminUser,)}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:$tox
Package: drf-serializer-inference
Serializer Inferencepipinstalldrf-serializer-inferenceDocumentation:https://mrthearman.github.io/drf-serializer-inference/Source Code:https://github.com/MrThearMan/drf-serializer-inference/Contributing:https://github.com/MrThearMan/drf-serializer-inference/blob/main/CONTRIBUTING.mdInfer Django Rest Framework serializers from callables like functions and classes.
Package: drf-session-filtering
DRF session filteringAboutThis package provides a Custom Models, Serializers, Backends and Views to facilitate saving filters in sessions.Installpipinstalldrf-session-filteringUsageDefine aSESSION_MODEL_CONTAINER_KEYsetting:# settings.pySESSION_MODEL_CONTAINER_KEY='session_objects'Define a models and filter models that will be stored in session.# models.pyfromdjango.dbimportmodelsfromsession_filtering.modelsimportBaseSessionModelclassBook(models.Model):title=models.CharField(max_length=100)issue_year=models.IntegerField()publisher=models.TextField()price=models.FloatField()...classBookFilterSessionModel(BaseSessionModel):passDefine a filter set.# filters.pyfromdjango_filters.rest_frameworkimportFilterSetfrom.modelsimportBookclassBookFilter(FilterSet):classMeta:model=Bookfields={'title':['exact','icontains'],'issue_year':['gt'],'price':['lt'],'publisher':['exact','contains'],}Define a serializers for models and filter models.# serializers.pyfromrest_frameworkimportserializersfromsession_filtering.serializersimport(FilterBaseSerializer,SessionSaveFilterMixin,)from.filtersimportBookFilterfrom.modelsimportBookclassBookSerializer(serializers.ModelSerializer):classMeta:model=Bookfields='__all__'classBookFilterSerializer(SessionSaveFilterMixin,FilterBaseSerializer):classMeta:filter_class=BookFilterDefine a filter view and a model viewset using filter serializer and filter model defined before.# views.pyfromrest_framework.genericsimportGenericAPIViewfromrest_framework.mixinsimport*fromrest_framework.viewsetsimport*fromsession_filtering.viewsimportBaseFilterMixinfromsession_filtering.backendsimportSessionFilterBackendfrom.filtersimportBookFilterfrom.modelsimportBook,BookFilterSessionModelfrom.serializersimportBookSerializer,BookFilterSerializerclassBookFilterViewSet(BaseFilterMixin,CreateModelMixin,RetrieveModelMixin,UpdateModelMixin,ListModelMixin,GenericViewSet,):filter_class=BookFilterserializer_class=BookFilterSerializerfilter_session_model=BookFilterSessionModelclassBooksViewSet(CreateModelMixin,RetrieveModelMixin,UpdateModelMixin,DestroyModelMixin,ListModelMixin,ViewSetMixin,GenericAPIView,):serializer_class=BookSerializerfilter_backends=[SessionFilterBackend]filter_class=BookFilterfilter_session_model=BookFilterSessionModelfilter_serializer_class=BookFilterSerializerfilter_lookup_field='filterset_id'queryset=Book.objects.all()LicenseThe Django Wicked Historian package is licensed under theFreeBSD
License.
Package: drf-shop
DRF ShopWe try to provide an online shop's basic models, serializers, and views. So you
can quickly create a shopping website. Usually, there are many complicated
logics behind every shopping system that you have to consider, So using a
package to do the basics for us is a good practice.Installationpipinstalldrf-shopOr, if you want the latest version, you can directly install the package from
the source code:pipinstallhttps://github.com/xanigo/drf-shop/archive/refs/heads/master.zipOr using git:pipinstallgit+ssh://git@github.com/xanigo/drf-shop.git