Saravanan666/pypi-org huggingface dataset:
Package: drf-extra-utils
Django Rest Extra UtilsA collection of useful tools, serializers and views to help and DRY your code.Full documentation:OverviewThis is a useful tool for developers working with Django Rest Framework, as it provides a range of useful features that
can help streamline development and improve the functionality of your API.RequirementsPython (3.8, 3.9, 3.10, 3.11)Django (3.0, 3.1, 3.2, 3.3, 4.0, 4.1, 4.2)Django Rest Framework (3.10, 3.11, 3.12, 3.13, 3.14, 3.15)Installation$ pip install drf-extra-utilsAdddrf_extra_utilsto your INSTALLED_APPS setting:INSTALLED_APPS = (
    ...
    'drf_extra_utils'
)TestingInstall testing requirements$ pip install -r requirements-test.txtRun with pytest$ pytestRun with tox$ pip install tox
$ tox
Package: drfexts
drfextsExtensions for Django REST FrameworkInstallation$ pip install drfextsUsageviews.pyfrom rest_framework.views import APIView
from rest_framework.settings import api_settings
from drfexts.viewsets import ExportMixin

class MyView (ExportMixin, APIView):
    ...Ordered FieldsBy default, aCSVRendererwill output fields in sorted order. To
specify an alternative field ordering you can override theheaderattribute. There are two ways to do this:Create a new renderer class and override theheaderattribute
directly:class MyUserRenderer (CSVRenderer):
    header = ['first', 'last', 'email']

@api_view(['GET'])
@renderer_classes((MyUserRenderer,))
def my_view(request):
    users = User.objects.filter(active=True)
    content = [{'first': user.first_name,
                'last': user.last_name,
                'email': user.email}
               for user in users]
    return Response(content)Use therenderer_contextto override the field ordering on the
fly:class MyView (APIView):
    renderer_classes = [CSVRenderer]

    def get_renderer_context(self):
        context = super().get_renderer_context()
        context['header'] = (
            self.request.GET['fields'].split(',')
            if 'fields' in self.request.GET else None)
        return context

    ...Labeled FieldsCustom labels can be applied to theCSVRendererusing thelabelsdict attribute where each key corresponds to the header and the value
corresponds to the custom label for that header.1) Create a new renderer class and override theheaderandlabelsattribute directly:class MyBazRenderer (CSVRenderer):
    header = ['foo.bar']
    labels = {
        'foo.bar': 'baz'
    }PaginationUsing the renderer with paginated data is also possible with the new
[PaginatedCSVRenderer]{.title-ref} class and should be used with views
that paginate dataFor more information about using renderers with Django REST Framework,
see theAPI
Guideor theTutorial.Running the testsTo run the tests against the current environment:$ ./manage.py testChangelog1.0.0Initial releaseThanks
Package: drf-fancy-permissions
DRF fancy permissionsAboutThis package provides utilities for defining fine-grained permissions in the Django Rest Framework based API views.Installpipinstalldrf-fancy-permissionsUsageUse the fancy_permissions.model_action_permission_factory, fancy_permissions.object_action_permission_factory and
fancy_permissions.parent_object_action_permission_factory functions in order to define authorization rules.fromrest_framework.mixinsimport(CreateModelMixin,ListModelMixin,RetrieveModelMixin,UpdateModelMixin,)fromrest_framework.viewsetsimportViewSetfromfancy_permissionsimport(model_action_permission_factory,object_action_permission_factory,parent_object_action_permission_factory,)classSomeViewSet(CreateModelMixin,RetrieveModelMixin,UpdateModelMixin,ListModelMixin,ViewSet,):serializer_class=SomeModelSerializerpermission_classes=[model_action_permission_factory(create=['some_app.add_somemodel'],retrieve=None,# open for all userspartial_update=['some_app.change_somemodel'],list=None,# open for all users,),object_action_permission_factory(create=None,retrieve=None,partial_update=[lambdaobj,user:obj.status=='SOME_STATUS'andnotobj.has_something_meaningful()],list=None,close=None,),parent_object_action_permission_factory(create=[lambdaobj,user:obj.can_create_children()],retrieve=None,partial_update=[lambdaobj,user:obj.can_update_children()],list=None,close=None,),]queryset=SomeModel.objects.all()LicenseThe Django Wicked Historian package is licensed under theFreeBSD
License.
Package: drf-feedback
Django REST Framework - FeedbackFeedback App for Django REST Framework with API Views.DRF Feedbackis a Django App that can for collecting feedback from end user. It's view are based uponDjango REST Framework's GenericAPIViewand hence it contains a RESTful API views also.Contributors:Civil Machines Technologies Private Limited: For providing platform and funds
for research work. This project is hosted currently withCMTonly.Himanshu Shankar: Ideation, modification & Quality Assurance in the app.Mahen Gandhi: Developed this app from scratch.Aditya Gupta: Testing, Modification suggestions & intial works. This app is inspire
his work in live project ofHisab KitabInstallationDownload and Install viapippip install drf_feedbackorDownload and Install viaeasy_installeasy_install drf_feedbackAdddrf_feedbackinINSTALLED_APPSINSTALLED_APPS = [
    ...
    'drf_feedback',
    ...
]Include urls ofdrf_feedbackinurls.pyurlpatterns = [
    ...
    path('feedback/', include('feedback.urls')),
    ...
]

# or

urlpatterns = [
    ...
    url(r'feedback/', include('feedback.urls')),
    ...
]Finally, runmigratecommandpython manage.py migrate drf_feedback
Package: drf-fields-limiting
DRF fields limitingAboutThis package provides utils for Django Rest Framework API views and serializers for limiting fields returned in responses thus limiting size and complexity of database requests.Installpipinstalldrf-fields-limitingUsageInherit fromLimitedFieldsVieworLimitedFieldsViewSetand configure it to enable fields limiting.
View limits fields of serialized object in response with respect toFieldsHTTP header.If header is not present or is empty show all fields. Fields limiting works only in GET requests.LIMITED_FIELDS_CONFIG holds map of field name - operation to perform on queryset (fromfields_limiting.operations).
It should contains entries for all fields declared in serializer_class....classMySerializer(LimitedFieldsSerializer,serializers.ModelSerializer):classMeta:model=MyModelfields=('char_field','int_field','foreign',)...classMyViewSet(LimitedFieldsViewSet,viewsets.ModelViewSet):...LIMITED_FIELDS_CONFIG={'char_field':Only('char_field'),'int_field':Only('int_field'),'foreign':SelectRelated('foreign'),}serializer_class=MySerializer...All available operations are indrf_fields_limiting.operationsmodule.Example GET query:GET /api/v1/base/my/ HTTP/1.1
Authorization: Token h3r315myt0k3n
Accept: application/json
Content-Type: application/json
Fields: char_field,int_fieldLicenseThe DRF complete autocomplete package is licensed under theFreeBSD
License.
Package: drf-filestream
A file stream application for DjangoRestFrameworkInstallationpython3-mpipinstalldrf_filestreamUsageeditproject/settings.pyfromrest_frameworkimportpermissionsINSTALL_APPS+=['drf_filestream',]MEDIA_ROOT='data/'# default: /FILE_ACCESS_PERMISSIONS=[permissions.IsAuthenticated]Demogitclonehttps://github.com/suqingdong/drf_filestream.gitcddemo

python3-mpipinstall-rrequirements.txt

python3manage.pycreatesuperuser

python3manage.pyrunserver
Package: drf-file-upload
DRF File UploadA reusable django library to handle file upload with the Django Rest Framework.It provides views, serializers and models for simplifying file uploads and their model association in your RESTful application.How it worksUpload the file using this library multi-part APIs:POST https://example.com/api/upload/
# A multipart request with a `file` field that contains your fileIf upload is complete, an unique identifier for that file is returned, along an URL for accessing it:{
   "url": "https://example.com/media/upload/file.png",
   "uuid: "1ad29aa9-d470-442d-a5a3-5922e7ce0182"
}Use theuuidin your APIs for associating the uploaded file with your django model instance:POST https://example.com/api/foo/
{
   [...],
   "my-file-attribute": "1ad29aa9-d470-442d-a5a3-5922e7ce0182"
}If you want to update the resource but leave the file unchanged, simply pass the file url as value:PUT https://example.com/api/foo/2/
{
    [...],
    "my-file-attribute": "https://example.com/media/upload/file.png"
}Quick startAdd “drf_file_upload” to your INSTALLED_APPS setting like this:INSTALLED_APPS = [
    ...
    'drf_file_upload',
]Include the polls URLconf in your project urls.py like this:path('upload/', include('drf_file_upload.urls')),This will add both separate authenticated and anonymous users to file upload endpoints.
Todo: add single view examplesAdd the UploadedFileField to your serializers todoRunpython manage.py migrateto create the file upload models.Run the cleanup management commanddeleted_expired_uploaded_filesin a cron task or add a celery taskTODO: Improvehttps://docs.djangoproject.com/en/3.1/intro/reusable-apps/TODOs & IDEASAdd support for Image filecheck if DRF dedicated fields can be exploitedlots of config (e.g.permission_classes)check ifclean_uploaded_filescan be called somewhere else to avoidsavemethod overrideDocumentation!Check if the file field can be set globally for all model FileFieldsAdd better spectacle openapi docsAdd missing tests
Package: drf-fileupload-api
A file upload application for DjangoRestFrameworkInstallationpython3-mpipinstalldrf-fileupload-apiUsageeditproject/settings.pyINSTALL_APPS+=['drf_fileupload',]MEDIA_ROOT='data/'# default: /FILE_UPLOAD_TO='upload/%Y/%m/%d'# support strftime format, default: MEDIA_ROOTFILE_UPLOAD_MAX_SIZE='10M'# limit max file size, default: Noneeditproject/urls.pyfromdjango.confimportsettingsfromdjango.conf.urls.staticimportstaticurlpatterns=[path('api/admin/',admin.site.urls),path('api/fileupload/',include('drf_fileupload.urls')),]urlpatterns+=static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)APIDemogitclonehttps://github.com/suqingdong/drf_fileuploadcddemo

python3-mpipinstall-rrequirements.txt

python3manage.pymakemigrations

python3manage.pymigrate

python3manage.pycreatesuperuser

python3manage.pyrunserver
Package: drf-filtermapbackend
FilterMapBackendTable Of ContentIntroductionInstallationUsageIntroductionFilterBackend which takes mapping of query params to field name.It takes the query_param to filter map and enables filter option in list view.InstallationInstalldrf-filtermapbackendusingpipinstalldrf-filtermapbackendThen includefilter_mapin your installed appsINSTALLED_APPS=[...,'rest_framework','filter_map',...]UsageYou can use FilterMapBackend by adding it to your filter backends and setting filter_map attribute.
For examplefromrest_framework.viewsetsimportModelViewSetfromfilter_map.backendsimportFilterMapBackendclassProfileViewSet(ModelViewSet):"""Consider Profile Model has user FK,"""queryset=...serializer_class=...filter_backends=(FilterMapBackend,)filter_map={# plain map'first_name':'user__first_name',# used with lte operator'joined_before':'date_joined__date__lte',# also supports separate field name and operator'last_name':('user__last_name','iexact'),}You can also defineget_filter_mapmethod to return the filter map.
This will allow you to change filter_map in runtime. Here's an examplefromrest_framework.viewsetsimportModelViewSetfromfilter_map.backendsimportFilterMapBackendclassProfileViewSet(ModelViewSet):"""Consider Profile Model has user FK,"""queryset=...serializer_class=...filter_backends=(FilterMapBackend,)defget_filter_map(self):# Disable joined_before filter for non staff usersifself.request.user.is_authenticatedandself.request.user.is_staff:return{'first_name':'user__first_name','joined_before':'date_joined__date__lte','last_name':('user__last_name','iexact'),}else:return{'first_name':'user__first_name','last_name':('user__last_name','iexact'),}
Package: drf-firebase3-auth
DRF Firebase3 AuthRequirementsPython (tested with 2.7, 3.6)DjangoDjango Rest FrameworkInstallation$ pip install drf-firebase3-authAdd the application to your project'sINSTALLED_APPSinsettings.py.INSTALLED_APPS = [
    ...
    'drf_firebase3_auth',
]In your project'ssettings.py, add this to theREST_FRAMEWORKconfiguration. Note that if you want to retain access to the browsable API for locally created users, then you will probably want to keeprest_framework.authentication.SessionAuthenticationtoo.REST_FRAMEWORK = {
  ...
  'DEFAULT_AUTHENTICATION_CLASSES': [
    ...
    'rest_framework.authentication.SessionAuthentication',
    'drf_firebase3_auth.authentication.FirebaseAuthentication',
  ]
}Thedrf_firebase3_authapplication comes with the following settings as default, which can be overridden in your project'ssettings.pyfile. Make sure to nest them withinDRF_FIREBASE_AUTHas below:DRF_FIREBASE_AUTH = {
    # path to JSON file with firebase secrets
    'FIREBASE_SERVICE_ACCOUNT_KEY': '',
    # allow creation of new local user in db
    'FIREBASE_CREATE_LOCAL_USER': True,
    # attempt to split firebase user.display_name and set local user
    # first_name and last_name
    'FIREBASE_ATTEMPT_CREATE_WITH_DISPLAY_NAME': True,
    # commonly JWT or Bearer (e.g. JWT <token>)
    'FIREBASE_AUTH_HEADER_PREFIX': 'JWT',
    # verify that JWT has not been revoked
    'FIREBASE_CHECK_JWT_REVOKED': True,
    # require that firebase user.email_verified is True
    'FIREBASE_AUTH_EMAIL_VERIFICATION': False
}You can get away with leaving all the settings as default except forFIREBASE_SERVICE_ACCOUNT_KEY, which is obviously required. As a minimum, you will need to set this in your project'ssettings.py. This must be the JSON service account key that you receive from the Firebase console for your application....
DRF_FIREBASE_AUTH = {
    'FIREBASE_SERVICE_ACCOUNT_KEY': 'project/config/firebase.json'
}Now that you have configured the application, run the migrations so that the Firebase data can be stored.$ ./manage.py migrate drf_firebase3_authAll you need to do now is have your client code handle the Firebase popup/redirect authentication flow, retrieve the idToken from the currentUser (Firebase explains this flow well in their docs:https://firebase.google.com/docs/auth/admin/verify-id-tokens), and then use the idToken for the user in anAuthorizationheader in requests to your API.JWT <token>Voila!ContributingIf you test this code with a Python version not listed above and all is well, please fork and update the README to include the Python version you used :)I almost always setup Django with a custom user class inheriting from AbstractUser, where I switch the USERNAME_FIELD to be 'email'. This backend is setup to assign a username still anyway, but if there are any issues, please raise them and/or make a pull request to help the community!
Package: drf-firebase-auth-cavoke
DRF Firebase Auth (Forked fromdrf-firebase-auth by garyburgman)RequirementsPython (tested with 2.7, 3.6)DjangoDjango Rest FrameworkInstallation$ pip install drf-firebase-auth-cavokeAdd the application to your project'sINSTALLED_APPSinsettings.py.INSTALLED_APPS = [
    ...
    'drf_firebase_auth_cavoke',
]In your project'ssettings.py, add this to theREST_FRAMEWORKconfiguration. Note that if you want to retain access to the browsable API for locally created users, then you will probably want to keeprest_framework.authentication.SessionAuthenticationtoo.REST_FRAMEWORK = {
  ...
  'DEFAULT_AUTHENTICATION_CLASSES': [
    ...
    'rest_framework.authentication.SessionAuthentication',
    'drf_firebase_auth_cavoke.authentication.FirebaseAuthentication',
  ]
}Thedrf_firebase_auth_cavokeapplication comes with the following settings as default, which can be overridden in your project'ssettings.pyfile. Make sure to nest them withindrf_firebase_auth_cavokeas below:drf_firebase_auth_cavoke = {
    # path to JSON file with firebase secrets
    'FIREBASE_SERVICE_ACCOUNT_KEY': '',
    # allow creation of new local user in db
    'FIREBASE_CREATE_LOCAL_USER': True,
    # attempt to split firebase user.display_name and set local user
    # first_name and last_name
    'FIREBASE_ATTEMPT_CREATE_WITH_DISPLAY_NAME': True,
    # commonly JWT or Bearer (e.g. JWT <token>)
    'FIREBASE_AUTH_HEADER_PREFIX': 'JWT',
    # verify that JWT has not been revoked
    'FIREBASE_CHECK_JWT_REVOKED': True,
    # require that firebase user.email_verified is True
    'FIREBASE_AUTH_EMAIL_VERIFICATION': False
}You can get away with leaving all the settings as default except forFIREBASE_SERVICE_ACCOUNT_KEY, which is obviously required. As a minimum, you will need to set this in your project'ssettings.py. This must be the JSON service account key that you receive from the Firebase console for your application....
drf_firebase_auth_cavoke = {
    'FIREBASE_SERVICE_ACCOUNT_KEY': 'project/config/firebase.json'
}Now that you have configured the application, run the migrations so that the Firebase data can be stored.$ ./manage.py migrate drf_firebase_auth_cavokeAll you need to do now is have your client code handle the Firebase popup/redirect authentication flow, retrieve the idToken from the currentUser (Firebase explains this flow well in their docs:https://firebase.google.com/docs/auth/admin/verify-id-tokens), and then use the idToken for the user in anAuthorizationheader in requests to your API.JWT <token>Voila!ContributingIf you test this code with a Python version not listed above and all is well, please fork and update the README to include the Python version you used :)I almost always setup Django with a custom user class inheriting from AbstractUser, where I switch the USERNAME_FIELD to be 'email'. This backend is setup to assign a username still anyway, but if there are any issues, please raise them and/or make a pull request to help the community!
Package: drf-firebase-authentication
Django Rest Framework Firebase AuthenticationThis package provides a base Firebase Authentication backend class for the Django rest framework. Two key methods are not implemented for more flexebility. Let'skeep it simple, stupid.RequirementsPython 2.7 or 3.4+Django(version 1.11+)Django Rest FrameworkFirebase Admin PythonInstallationpip install drf-firebase-authenticationUsage1. SubclassBaseFirebaseAuthenticationand implement its template methods:Decide by yourself how you want to associate Firebase users with local django users by implementing the.get_django_user()method accordingly.Put your code into aauthentication.pyfile inside an app dedicated to your projects REST Api.fromdrf_firebase.authenticationimportBaseFirebaseAuthenticationfromfirebase_adminimportcredentials,initialize_appfromdjango.contrib.authimportget_user_modelfirebase_creds=credentials.Certificate('path/to/firebase/credentials.json')firebase_app=initialize_app(firebase_creds)classFirebaseAuthentication(BaseFirebaseAuthentication):"""Example implementation of a DRF Firebase Authentication backend class"""defget_firebase_app(self):returnfirebase_appdefget_django_user(self,firebase_user_record):returnget_user_model().objects.get_or_create(username=firebase_user_record.uid,)[0]2. Add the just created Firebase authentication backend to yoursettings.py:ReplaceYOUR_RESTAPI_APPwith the app you put yourauthentication.pyfile in.REST_FRAMEWORK={'DEFAULT_AUTHENTICATION_CLASSES':('rest_framework.authentication.SessionAuthentication',# default'rest_framework.authentication.BasicAuthentication',# default'YOUR_RESTAPI_APP.authentication.FirebaseAuthentication',),}
Package: drf-firebase-token-auth
Inspired bygaryburgmann/drf-firebase-authand based onRest Framework’s TokenAuthentication,drf-firebase-token-authshould be just what you need to enable client
authentication usingFirebase Authentication.How Does It WorkFor each REST request, a Firebase ID Token is extracted from the
Authorization header.The ID Token is verified against Firebase.If the Firebase user is already known (A record with the corresponding UID
exists in theFirebaseUsertable), then the corresponding localUseris
successfully authenticated.Otherwise, the unfamiliar Firebase user is attempted to be matched against
a localUserrecord byemailorusername. If no match exists,
then a newUseris created. Itsusernameis assigned either to the
Firebase email or UID (in case an email is not available).
Finally, the newly created localUseris successfully authenticated.InstallationInstall the pip package:$pipinstalldrf-firebase-token-authAdd the application to your project’sINSTALLED_APPS:# settings.pyINSTALLED_APS=[...'drf-firebase-token-auth',]AddFirebaseTokenAuthenticationto Rest Framework’s list of default
authentication classes:# settings.pyREST_FRAMEWORK={...'DEFAULT_AUTHENTICATION_CLASSES':[...'drf_firebase_token_auth.authentication.FirebaseTokenAuthentication',]}Note: It’s perfectly fine to keep other authentication classes as well.
For example, you may want to keeprest_framework.authentication.SessionAuthenticationto allow access to the browsable API for local users with password.Configure the application:# settings.pyDRF_FIREBASE_TOKEN_AUTH={# REQUIRED SETTINGS:# Path to JSON file with firebase secrets'FIREBASE_SERVICE_ACCOUNT_KEY_FILE_PATH':r'/mnt/c/Users/ronhe/Google Drive/ProgramsData/WizWot/paywiz-c4b4f-firebase-adminsdk-ekbjf-9b7776879a.json',# OPTIONAL SETTINGS:# Create new matching local user in db, if no match found.# Otherwise, Firebase user not matching a local user will not# be authenticated.'SHOULD_CREATE_LOCAL_USER':True,# Authentication header token keyword (usually 'Token', 'JWT' or 'Bearer')'AUTH_HEADER_TOKEN_KEYWORD':'Token',# Verify that Firebase token has not been revoked.'VERIFY_FIREBASE_TOKEN_NOT_REVOKED':True,# Require that Firebase user email_verified is True.# If set to True, non verified email addresses from Firebase are ignored.'IGNORE_FIREBASE_UNVERIFIED_EMAIL':True,}Migrate:$pythonmanage.pymigratedrf-firebase-token-authHave your clients addingToken <Firebase ID Token>in the
Authorization Header of their REST requests.