Saravanan666/pypi-org huggingface dataset:
Package: drfaddons
Django REST Framework Add OnsA collection package for Django REST FrameworkDjango REST Framework Add Onsis a collection package collected over a period of one year from various sources.In each function/class I've specified its source indocstringsinsideSource/Sources.Wherever there isn't any source, the module has been created by me for my personal use.This may come in handy to all those who are going to useDjango REST Frameworkfor creatingAPI.Contributors:WE'RE LOOKING FOR SOMEONE WHO CAN CONTRIBUTE IN DOCSCivil Machines Technologies Private Limited: For providing me platform and
funds for research work. This project is hosted currently withCMTonly.Himanshu Shankar: Himanshu Shankar has initiated this project and worked on this
project to collect useful functions and classes that are being used in various projects.Mahen Gandhi: For making this repository into a library. At the time of this commit,
he is an intern withCMTand is assigned with the task of making this as aPython Packagehosted onPyPi.Aditya Gupta: For updating this repository and projects using this repository as per
the latest standards. He is also an intern withCMTand is assigned with same task asMahen. He updated various
projects using this library to useGenericAPIView, such asCreateAPIView,ListAPIViewrather thanValidateAndPerformView ViewInstallationDownload and Install viapippip install drfaddonsorDownload and Install viaeasy_installeasy_install drfaddonsAdd, if wanted,drfaddonsinINSTALLED_APPS(This is although not required!)INSTALLED_APPS = [
    ...
    'drfaddons',
    ...
]
Package: drf-admin
DRF-AdminA package to generate CRUD endpoints for registered models with the Django-REST Framework.RequirementsDjangoDjango Rest FrameworkInstallationTo install run:pip install drf-adminUsageImport restadmin in the admin.pyCallrestadmin.site.register(Model)Model being the model to registerAdd rest admin to your urls.py filePrerequisiterest_framework should be properly set up to use this package hitch freeA sample of it's configuration in the settings file:REST_FRAMEWORK={'DEFAULT_SCHEMA_CLASS':'rest_framework.schemas.coreapi.AutoSchema','TEST_REQUEST_RENDERER_CLASSES':['rest_framework.renderers.MultiPartRenderer','rest_framework.renderers.JSONRenderer','rest_framework.renderers.TemplateHTMLRenderer',],"DEFAULT_AUTHENTICATION_CLASSES":['rest_framework.authentication.SessionAuthentication','rest_framework.authentication.BasicAuthentication'],"DEFAULT_PERMISSION_CLASSES":['rest_framework.permissions.AllowAny',]}For example:models.pyfromdjango.dbimportmodelsclassTestModel(models.Model):age=models.IntegerField()admin.pyfrom.modelsimportTestModelimportrestadminrestadmin.site.register(TestModel)urls.pyfromrestadminimportsitefromdjango.urlsimportpathurlpatterns=[...path('restadmin/',site.urls),...]CustomizationThis package allows you to specify the following when registering your modelserializer: A Model Serializer Classpermission_classes: A list of Permission classespagination_classs: A Pagination ClassAn example of how a call to the register method with all 3 would look is :restadmin.site.register(TestModel,serializer=AdminSerializer,permission_classes=[ReadOnly],pagination_class=LargeResultsSetPagination)Endpoint DocumentationThis requires you to have coreapi installedA page to document the Endpoints generated can be accessed by adding the following to your base urls filefromrestadminimportsiteurlpatterns=[...path('restadmin-docs/',site.docs)...]Using this would require you to have your default schema Class set in your REST_FRAMEWORK config in your settings.py file
E.gREST_FRAMEWORK = { 'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema' }Run your server and you can find the documentation athttp://127.0.0.1:8000/restadmin-docsNOTE: The Documentation page is restricted to staff only(is_staff has to be True)TestsTo run the tests:From the base directory run :python load_tests.py
Package: drf-advanced-auth
DRF Advanced AuthenticationDjango REST Frameworkprovides just about everything needed to turn your Django app into a REST-based web application. One area that DRF lacks functionality is in the non-happy path scenarios related to authentication, namely password changes and password resets. This module aims to simplify setting up a full auth subsystem for your REST application.The functions provided by this package are:login: an endpoint for authenticating a userlogout: an endpoint for ending a user's sessionchange password: an endpoint for changing the password of a logged-in userreset password: two endpoints that together can be used to reset the password of a logged-out user (lost password, etc)Note:This package is a work in progress (that's why it's not yet at version 1.0). I am active seeking contributions to help with making it more usable, see"Contributing"below.InstallationInstall the package:$pipinstalldrf-advanced-authAdd it toINSTALLED_APPS:INSTALLED_APPS=[...'drf_advanced_auth',...]Update your URLs by adding thedrf_advanced_authurls under whatever prefix you want, and another url namedpassword_reset_confirmthat you want users to be redirected to when they click the link in the password reset email:urlpatterns=[url(r'^auth/',include('drf_advanced_auth.urls',namespace='authentication')),url(r'^password-reset/update/(?P<uidb64>.*)/(?P<token>.*)',FakeView.as_view(),name='password_reset_confirm'),]Usage(IN PROGRESS)Sample AppYou can see a sample app using these fields buy running the following:$pythonmanage.pymigrate
$pythonmanage.pyloaddatafixtures/base.json
$pythonmanage.pyrunserverThis app has the following endpoints (assuming they are under theauthprefix as shown above):/auth/login//auth/logout//auth/change_password//auth/reset_password_request//auth/reset_password_complete/The username for the admin user isadmin, and the password ispass.ContributingI am actively seeking contributions to this package. Check the "Issues" section of the repository for my current hit list.If you have suggestions for other features I am open to hearing them. Use the "Issues" section of the repository to start a conversation.
Package: drf-aggregates
django-rest-framework-aggregatesExposes aggregation features of the Django model queryset to the DRF API.RequirementsPython 3.6+Django 1.11+Django Rest Framework 3.5.3+OverviewThis renderer overwrites default behaviour for calls made to api v2 .agg endpoints.SupportsGETcalls to list endpoints in the format:endpoint.agg/?aggregate[Count]=(field to count)
endpoint.agg/?aggregate[Sum]=(field to sum)
endpoint.agg/?aggregate[custom_function]=arguments
endpoint.agg/?group_by[field to group by]&aggregate[Count]=id
endpoint.agg/?group_by[field to group by]&aggregate[Count]=id&aggregate[Sum]=(field to sum)Supports date part extraction for aggregation:endpoint.agg/?group_by[created__year]&aggregate[Count]=idSupports choices to representation extract:endpoint.agg/?group_by[choiceField]&aggregate[Count]=idSupport aggregating over multiple fields, either ofendpoint.agg/?aggregate[Sum]=id&aggregate[Sum]=number
endpoint.agg/?aggregate[Sum]=id,numberCustom AggregationsThe default aggregate functions supported are defined indjango.db.models.aggregates.Custom aggregate functions have been defined indrf_aggregates.aggregatesUser defined aggregation are passed to a custom queryset managercalculate_aggregatesas kwargs if defined.Custom aggregate functions set on the queryset should return a dictionary of field names to aggregate functions, which will then be processed with the other aggregates.ExamplesExample setup can be found in theexample/folder.To enable the renderer, update your Django settings file:REST_FRAMEWORK={'DEFAULT_RENDERER_CLASSES':('drf_aggregates.renderers.AggregateRenderer',...),...}In theCars ViewSetwe are outputting the result to json:deflist(self,request,*args,**kwargs):queryset=self.filter_queryset(self.get_queryset())data=request.accepted_renderer.render({'queryset':queryset,'request':request})returnResponse(data,content_type=f'application/json')TestsIn order to run tests locally:Install development requirements:pip3 install -r requirements-dev.txtUpdate your environment to point to test Django settings file:export DJANGO_SETTINGS_MODULE=example.settings.testRun tests:py.test
Package: drf-allauthmail
drf_allauthmail provide REST endpoints of allauth’s EmailAddress Model.Quick startAdd “polls” to your INSTALLED_APPS setting like this:INSTALLED_APPS = [
    ...
    'drf_allauthmail',
]Include the polls URLconf in your project urls.py like this:path('mails/', include('drf_allauthmail.urls')),Visithttp://127.0.0.1:8000/mails/to refer your e-mail addresses.
Package: drf-amsterdam
Django REST Framework extensions by Amsterdam DatapuntExtensions to Django REST Framework by Amsterdam Datapunt. Amsterdam Datapunt
provides access to municipal data through, at times, public APIs. This project
provides some basic classes and instructions to set the behavior
of Django REST Framework API to the standards of Amsterdam Datapunt.Installation instructionsGiven that you have a Django project that generates a REST API using Django
REST Framework:pipinstalldrf_amsterdamTo use the API page styling provided by this package you must add it to the
Django settings file in INSTALLED_APPS, ahead of 'rest_framework' so that the
templates and static files included in drf_amsterdam override those included
with Django REST Framework.Running testsRun the tests in a virtualenv and run the script runtests.py from project root.requirements: spatialite, sqlite extensionor use docker-compose:docker-composebuild
docker-composerun--rmtestspytest--covChangelog1.0.0Added typesTidied up codeAdded tests to reach 100% code coverageBreaking changesLinksFieldnow extendsRelatedFieldinstead ofHyperLinkedIdentityField. The reason for this is thatHyperLinkedIdentityFieldhas to return aHyperLinkobject in order to comply with the rules of covariance,
which is not what we desire it to return.
Package: drf-anonymous-login
DRF Anonymous LoginDjango rest framework module to allow login via token (without User instance). Any request with valid token in the
AUTH_HEADER (name configurable viasetting.py, "HTTP_X_AUTHORIZATION_ANONYMOUS" by default) will be accepted.InstallationInstall using pip:pipinstalldrf-anonymous-loginIntegratedrf_anonymous_logininto yoursettings.pyINSTALLED_APPS=[# ...'drf_anonymous_login',# ...]UsageThere are multiple ways to include theAnonymousLoginfunctionality to your endpoints. We recommend to use one of
the following approaches:Inherit from theAnonymousLoginAuthenticationModelViewSetfor any model that is supposed to be accessible via
valid token header. You'll find a simple exemplary usage scenario provided thetestapp.ORDirectly add theAnonymousLoginAuthenticationandIsAuthenticatedto your ViewSet'sauthentication_classesandpermission_classesas implemented in theAnonymousLoginAuthenticationModelViewSet.Configure token expirationThe tokens will not expire by default (expiration_datetime remainsNone). You can  configure theANONYMOUS_LOGIN_EXPIRATIONin your application'ssettings.pyto define a default expiration in minutes, e.g.
to have any token only valid for 15 minutes, use:# settings.py...ANONYMOUS_LOGIN_EXPIRATION=15Unit TestsSee foldertests/. The provided tests cover these criteria:success:access public endpoint without tokenaccess private endpoint with valid tokencleanup task does not remove tokens before their expiration_datetimecleanup task removes tokens after their expiration_datetimefailure:access private endpoint without tokenaccess private endpoint with invalid tokenaccess private endpoint with expired tokenFollow below instructions to run the tests.
You may exchange the installed Django and DRF versions according to your requirements.
:warning: Depending on your local environment settings you might need to explicitly callpython3instead ofpython.# install dependenciespython-mpipinstall--upgradepip
pipinstall-rrequirements.txt# setup environmentpipinstall-e.# run testscdtests&&pythonmanage.pytestContributingContributions are welcomed! Read theContributing Guidefor more information.LicensingSeeLICENSEfor more information.
Package: drf-api-actions
===============drf-api-actions===============提供django下rest framework的coreapi便捷调用Quick start for django 2.0+-----------1. Install::pip install drf_api_actions>=2.02. [Optional] Include the drf_api_actions URLconf in your project urls.py like this::if settings.DEBUG:urlpatterns += [url('^', include('drf_api_actions.urls'))]# after add this you can visit: /docs /schema /api.js3. No migrate needed:4. Sample::# Add "sample" to your INSTALLED_APPS setting like this ::INSTALLED_APPS = [...'sample',]# Include the sample URLconf in your project urls.py like this::urlpatterns += [url('^', include('sample.urls'))]# Run server and visit /docs /schema /api.js5. Examples::# Viewsclass UsersAPIView(APIView):"""获得用户列表返回值：用户列表 `['a', 'b', ...]`"""def get(self, request):return Response(['a', 'b'])class UsersActionReadAPIView(ActionReadMixin, APIView):"""获得用户列表, 用了`ActionReadMixin`后这是一个用 Read返回值：用户列表 `['a', 'b', ...]`"""def get(self, request):return Response(['a', 'b'])class UsersExtraFieldsAPIView(APIView):"""获得用户列表, 带user_id/user_name会过滤返回值：- 带user_id: `['a']`- 不带user_id: `['a','b']`"""schema = AutoSchema(manual_fields=[coreapi.Field(name='user_id', location='query', required=True,schema=coreschema.String(description='用户的id')),])def get(self, request):user_id = request.GET.get('user_id', '')if user_id:return Response(['a'])else:return Response(['a', 'b'])# Url settingsurl('^docs/', Views.docs_as_view(title='API'))url('^schema/', Views.schema_as_view(title='API'))url('^api.js', Views.api_js_as_view(title='API'))Quick start for django 1.0+-----------1. Install::pip install drf_api_actions==0.2.02. [Optional] Include the drf_api_actions URLconf in your project urls.py like this::if settings.DEBUG:urlpatterns += [url('^', include('drf_api_actions.urls'))]# after add this you can visit: /docs /schema /api.js3. No migrate needed:4. Sample::# Add "sample" to your INSTALLED_APPS setting like this ::INSTALLED_APPS = [...'sample',]# Include the sample URLconf in your project urls.py like this::urlpatterns += [url('^', include('sample.urls'))]# Run server and visit /docs /schema /api.js5. Examples::# Viewsclass UsersAPIView(APIView):"""获得用户列表返回值：用户列表 `['a', 'b', ...]`"""def get(self, request):return Response(['a', 'b'])class UsersActionReadAPIView(ActionReadMixin, APIView):"""获得用户列表, 用了`ActionReadMixin`后这是一个用 Read返回值：用户列表 `['a', 'b', ...]`"""def get(self, request):return Response(['a', 'b'])class UsersExtraFieldsAPIView(APIView):"""获得用户列表, 带user_id/user_name会过滤返回值：- 带user_id: `['a']`- 不带user_id: `['a','b']`"""extra_fields = [coreapi.Field(name='user_id', location='query', required=False,schema=coreschema.String(description='用户id'))]def get(self, request):user_id = request.GET.get('user_id', '')if user_id:return Response(['a'])else:return Response(['a', 'b'])# Url settingsurl('^docs/', Views.docs_as_view(title='API'))url('^schema/', Views.schema_as_view(title='API'))url('^api.js', Views.api_js_as_view(title='API'))
Package: drf-api-dump
This Django app is intended fordump data from apps or models via HTTP. Basically exposes
dumdata command to http.Features:Just accesible by superusersAbility to include or exclude any specific app or modelRequirements:Django (Developed under v1.11)Django Rest Framework (Developed under v3.4.3)More onhttps://github.com/davidvicenteranz/drf-api-dump/
Package: drfapikey
# django-rest-framework-api-key [![travis][travis-image]][travis-url] [![codecov][codecov-image]][codecov-url] [![pypi][pypi-image]][pypi-url]Authenticate Web APIs made with Django REST Framework### Supports- Python (2.7, 3.3, 3.4, 3.5)- Django (1.8, 1.9, 1.10)- Django Rest Framework (3+)### InstallationInstall using pip:pip install drfapikeyAdd 'rest_framework_api_key' to your `INSTALLED_APPS` setting:INSTALLED_APPS = (...'rest_framework_api_key',)Finally set the django-rest-framework permissions under your django settings:REST_FRAMEWORK = {'DEFAULT_PERMISSION_CLASSES': ('rest_framework_api_key.permissions.HasAPIAccess',)}### Example Request```pythonresponse = requests.get(url="http://0.0.0.0:8000/api/login",headers={"Api-Key": "fd8b4a98c8f53035aeab410258430e2d86079c93",},)```### Testspyvenv envsource env/bin/activatepip install -r requirements/requirements-testing.txtpython runtests.py### Contributing1. Fork it!2. Create your feature branch: `git checkout -b my-new-feature`3. Commit your changes: `git commit -am 'Add some feature'`4. Push to the branch: `git push origin my-new-feature`5. Submit a pull request6. Make sure tests are passing[travis-image]: https://travis-ci.org/ekonstantinidis/django-rest-framework-api-key.svg?branch=master[travis-url]: https://travis-ci.org/ekonstantinidis/django-rest-framework-api-key[codecov-image]: https://codecov.io/github/ekonstantinidis/django-rest-framework-api-key/coverage.svg?branch=master[codecov-url]:https://codecov.io/github/ekonstantinidis/django-rest-framework-api-key?branch=master[pypi-image]: https://badge.fury.io/py/drfapikey.svg[pypi-url]: https://pypi.python.org/pypi/drfapikey/
Package: drf-app-generators
DRF Application GeneratorsGenerate DRF standard apps with a single command.InstallationInstall with pip$pipinstalldrf-app-generatorsTo use DRF app generators, add it to INSTALLED_APPS.INSTALLED_APPS = (
    ...
    'rest_framework',
    'drf_app_generators',
    ...
)UsageGenerate a new Django app.To use the generators, run the following command.$pythonmanage.pygenerate{app}{options}OptionsDescription--modelsA list of model names.--apidocGenerate written API document--nestedCreate nested folders for models, apis, factories and serializers--forceOverride existed filesExample: Generate a new app with 3 models.$pythonmanage.pygeneratebooks--modelsBook,Author,Labelsrc/books/├──__init__.py├──admin.py├──apis.py├──apps.py├──factories.py├──filters.py├──migrations│├──0001_initial.py│└──__init__.py├──models.py├──permissions.py├──serializers.py└──tests├──__init__.py├──test_books_apis.py└──test_books_models.pyUpdate an existing Django app.When you finished adding fields to your models, you can update factories & admins by the following commands.$pythonmanage.pyapp_update{app}{options}OptionsDescription--nestedIf you app is nested--factoryUpdate your factories.--apiUpdate your APIs.--adminUpdate your admin.--serializerUpdate your serializers.--unittestUpdate your unittest.--filterUpdate your filters.--allUpdate all components.--add-modelsAdd more models to your app.Example: Update books app we just generated.pythonmanage.pyapp_updatebooks\--factory\--admin\--api\--serializer\--unittest\--filter\--add-modelsLabel,CategoryTestsA full application built with drf-generators can be found in the tests directory.LicenseMIT License. SeeLICENSE.
Package: drfasyncview
drf-async-viewDjango supportsAsyncViewfrom 4.1 to support writing asynchronous handlers.AsyncAPIViewallows you to use async handlers keeping the compatibility with django-rest-framework as well.InstallationYou can install the latest release from pypi:$pipinstalldrfasyncviewHow to useExampleimportasynciofromdjango.contrib.auth.modelsimportUserfromdjango.dbimportmodelsfromdjango.httpimportHttpRequest,JsonResponsefromrest_framework.authenticationimportBaseAuthenticationfromrest_framework.permissionsimportBasePermissionfromrest_framework.throttlingimportBaseThrottlefromtypingimportOptional,TuplefromdrfasyncviewimportAsyncRequest,AsyncAPIViewclassAsyncAuthentication(BaseAuthentication):asyncdefauthenticate(self,request:AsyncRequest)->Optional[Tuple[User,str]]:awaitasyncio.sleep(0.01)returnNoneclassAsyncPermission(BasePermission):asyncdefhas_permission(self,request:AsyncRequest,view:AsyncAPIView)->bool:awaitasyncio.sleep(0.01)returnTrueclassAsyncThrottle(BaseThrottle):asyncdefallow_request(self,request:AsyncRequest,view:AsyncAPIView)->bool:awaitasyncio.sleep(0.01)returnTrueclassProduct(models.Model):name=models.CharField(max_length=256,unique=True)price=models.IntegerField()classProductsView(AsyncAPIView):authentication_classes=[AsyncAuthentication]permission_classes=[AsyncPermission]throttle_classes=[AsyncThrottle]asyncdefpost(self,request:HttpRequest)->JsonResponse:name=request.data["name"]price=request.data["price"]product=awaitProduct.objects.acreate(name=name,price=price)returnJsonResponse(data={"name":product.name,"price":product.price},status=200,)
Package: drf_authentication
Django Rest Framework-Angular Authorization===================## InstallationInstall the package```bash$ pip install drf_authentication$ python manage.py bower_install```You must add 'bower' and 'drf_authentication' to INSTALLED_APPS.## Dependenciesdjangodjangorestframeworkjack_bower## Demo[Demo ](https://drf-auth-angular.herokuapp.com/) you can check it out.##TestingRun all tests:```bash$ tox```Start test with nose and code coverage:```bash$ nosetests --with-cov  --cov-report html  --cov  drf_angular_auth tests/```
Package: drf-auth-jwt
JSON Web Token Authentication support for Django REST FrameworkFull documentation for the project is available atdocs.OverviewThis package providesJSON Web Token Authenticationsupport forDjango REST framework.RequirementsPython (3.8, 3.9, 3.10)Django (3.2, 4.0)Django REST Framework (3.13)InstallationInstall usingpip…$pipinstalldrf-auth-jwtDocumentation & SupportFull documentation for the project is available atdocs.You may also want to follow theauthoron Twitter.
Package: drfauto
# Django Rest Framework auto creator
### Creates serializers, filters and generics for created modelInstallation:pip install drfautoIncludedrfautointo DjangoInstalled appsand usepython manage.py makeserializer | makefilter | makeviewsfor your-m model_nameor-a app_nameor-Aall project. This commands generate serializers.py, filters.py and views.py in your apps directories and create suitable classes.
Also u can importdrfauto.dynamicfor creating class as python object in your code. This classes can be used as abstract for inheritance or ready functional classes.
Package: drf-autoview
django-drf-autoviewExpose CRUD DRF compatible api's for any django model with one line.
This patten can be used to quickly bootstrap an api server app based on django DRF.Example# Add below snippet in api.py of the django app
from drf_autoview.api import get_api_views_with_all_fields_readonly
api_views = get_api_views_with_all_fields_readonly([
    models.DemoModel,
])

# Add below snippet in site/api.py
from drf_autoview.api import register_with_router
def get_router():
    _router = routers.DefaultRouter()
    _apps = filter(lambda x: '<appName>' in x[1].name, apps.app_configs.items())
    for _app_name, _app_obj in _apps:
        if module_has_submodule(_app_obj.module, 'api'):
            api = import_module('{0}.api'.format(_app_obj.module.__name__))
            register_with_router(_router, api.api_views)
    return _router
router = get_router()