Saravanan666/pypi-org huggingface dataset:
Package: djangorestframework-discovery
Django Rest Framework DiscoverySummaryDiscovery allows you to create an API from an existing database with minimal effort. This project is based on Shabda Raaj'sBookrest. You can also leverage the capabilties of the Django Rest Framework to applyfiltering,paginationanddocumentationgeneration. Examples can be found in theexamplesdirectory.Problem StatementThe data is not always accessible in legacy applications. You might be in a situation where you need access to the data for reporting or prototyping new tools. Adding new functionality to legacy software can be cost prohibitive and this solution aims to work-around this issue.RequirementsFor successful schema generation, you need to have a primary key present in the table. Otherwise, it will be silently ignored.Installationpipinstalldjangorestframework-discoveryIn yoursettings.py:INSTALLED_APPS=[# ..."rest_framework","rest_framework_discovery",]Add a variable to yoursettings.pynamedDISCOVERY_ALIAS_NAME. You can use any value, butdiscoveryis recommended. You will use that to define the database you would like to use for viewset generation.DISCOVERY_ALIAS_NAME='discovery'DATABASES={'default':{'ENGINE':'django.db.backends.sqlite3','NAME':os.path.join(BASE_DIR,'db.sqlite3'),},'discovery':{'NAME':'YOUR_DB_NAME','ENGINE':'django.db.backends.postgresql','USER':'YOUR_DB_USER','PASSWORD':'YOUR_DB_PASSWORD','HOST':'YOUR_DB_HOST','PORT':'YOUR_DB_PORT',},}Add the generated patterns to the rest of your application by modifying theurls.py.urlpatterns=[# ...url(r'^api/discovery/',include('rest_framework_discovery.urls')),]You will also need to includeDEFAULT_SCHEMA_CLASSexplicitly insettings.pyto get this to work.See additional details..REST_FRAMEWORK={...'DEFAULT_SCHEMA_CLASS':'rest_framework.schemas.coreapi.AutoSchema'}TestingYou can run through the testing suite by runningruntests.pyortox.ConfigurationYou can configure the following insettings.py:DISCOVERY_ALIAS_NAME: (required) The database alias name to use with discovery.DISCOVERY_READ_ONLY: (optional)TrueorFalse, whether or not the viewsets should be read-only.DISCOVERY_INCLUDE: (optional) A list of tables that you would like toonlyinclude.DISCOVERY_EXCLUDE: (optional) A list of tables that you would like to ignore.
Package: djangorestframework_emailuser
OverviewA user for djangorestframework that uses an email as the username.FeaturesUse email as username for loging inOne name field instead of first name and last nameEndpoints for creating an account, viewing, and updating accountsDjango admin to work with EmailUser model.RequirementsPython 3.5+Django 2.2+Djangorestframework 3.10+Installation and ConfigurationInstall usingpip:$pipinstalldjangorestframework_emailuserAdd'emailuser'toINSTALLED_APPS:# mysite/settings.pyINSTALLED_APPS=[...'emailuser',]Add the following line tosettings.pyto override django’s default User
model with the ‘EmailUser’ model:# mysite/settings.pyAUTH_USER_MODEL='emailuser.EmailUser'Add urls to url conf:# mysite/urls.pyfromdjango.urlsimportpath,includeurlpatterns=[...path('accounts/',include('emailuser.urls')),]UsingTo create a user programatically:fromdjango.contrib.authimportget_user_modelnormal_user=get_user_model().objects.create_user(email='me@example.com',name='My Name',password='MyPassword')superuser=get_user_model().objects.create_superuser(email='admin@example.com',name='Super Name',password='MySuperPassword')Using Endpoints:Assuming emailuser urls were set to/accounts/:Creating userPOST{"email": email, "name": name, "password": password}to/accounts/users/registerUpdating UserPUT{"email": email, "name": name, "password": password}to/accounts/users/<int:pk>/orPATCHthe attribute you want to change
to/accounts/users/<int:pk>/Referencing UserTo reference user object in your code as a string (As for foreign keys):fromdjango.confimportsettingsuser_model=settings.AUTH_USER_MODELTo reference the user class directly:fromdjango.contrib.authimportget_user_modeluser_model=get_user_model()SeeDjango docsfor more details.AttributesThe EmailUser model has the following attributes:emailThe email address used as the login username.nameA single field for the name of the user.passwordThe password is hashed as set by the django settings.is_superuserA boolean attribute that can only be set programatically.is_staffA boolean attribute that can be set by the admin site or
programatically.EmailUser also subclassesdjango.contrib.auth.models.PermissionsMixin.
Package: django-rest-framework-expandable
Django Rest Framework ExpandableDescriptionExpandable serializers for Django REST Framework. Allow for selective object
expansion through query parameters or serializer class kwargs.Installationpip install django-rest-framework-expandableUsage# apps/users/api.serializers.py# (User serializer)classUserSerializer(ExpandableHyperlinkedModelSerializer):classMeta:model=Userfields=("username","id",...)# apps/users/api/fields.py# (User expandable serializer field)classUserRelatedField(ExpandableHyperlinkedRelatedField):queryset=User.objects.all()lookup_field="id"view_name="api:user-detail"expand_settings={"comparison_fields":["id"],"serializers":[{"paths":["example.user"],"serializer":"apps.users.api.serializers.UserSerializer","skipped":[],}]}# apps/example/api/serializers.py# Example serializer (using nested expandable serializer fields)fromapps.users.api.fieldsimportUserRelatedFieldfromapps.another.api.fieldsimportAnotherRelatedFieldclassExampleSerializer(ExpandableHyperlinkedModelSerializer):another_related_field=AnotherRelatedField()user=UserRelatedField()...Returns...GET http://localhost:8000/api/examples/?expand=example.user
{
  id: 1,
  another_related_field: "http://localhost:8000/api/another/1",
  user: {
    id: 1,
    username: "Alex",
    ...
  }
}
Package: djangorestframework-extras
DRFE generates RESTful API’s for any Django models. It builds on Django Rest Framework.Table of ContentsPrerequisiteInstallationFeature ListUsageTipsUnit TestingLicensePrerequisitepip installdjangorestframeworkAddrest_frameworkto yourINSTALLED_APPSsetting insettings.py.InstallationInstall or adddjangorestframework-extrasto your Python path.Addrest_framework_extrasto yourINSTALLED_APPSsetting insettings.py.Feature ListGenerating default serializers and viewsets for all known applications to create RESTful API’s.Registering all viewsets known to the application with the Django Rest Framework router.Custom serializers and permissions for the default user, the staff users and superusers.Custom FormMixin that Delegates validation to a normal Django form.Custom Hyperlink fields and serializer,HyperlinkedRelatedFieldandHyperlinkedModelSerializerUsageUser permissions and the custom UsersViewSetdjangorestframework-extrasprovides a custom ViewSetUsersViewSetwith serializers and permissions for the default user, the staff user and the superuser.Register UsersViewSet through the DefaultRouter:from rest_framework_extras.users.viewsets import UsersViewSet

router = routers.DefaultRouter()

router.register(r'users', UsersViewSet, 'user')Discovery and registration of ViewSetsEnable discovery and registration of default serializers and viewsets by adding the following tourls.py:from rest_framework import routers
import rest_framework_extras
router = routers.DefaultRouter()

rest_framework_extras.discover(router)
rest_framework_extras.register(router)

urlpatterns = [
    url(r"^api/(?P<version>(v1))/", include(router.urls))
]Going through the code line by line:Line 1 & 3: The router and DefaultRouter classes connects the views and urls automatically and also creates the API root.Line 5: The new discover function generates default serializers and viewsets. This function should be run before normal registration.Line 6: The new register function registers all viewsets (including the UsersViewSet), overriding any items already registered with the same name.Line 9: Define the urls by including router.urls.Available SettingsREST_FRAMEWORK_EXTRASblacklist: A dictionary of the models to blacklist. By default the following models are blacklisted:"REST_FRAMEWORK_EXTRAS": {
   "blacklist": {
        "sessions-session": {},
        "admin-logentry": {}
   },
   "authentication-classes": (SessionAuthentication, BasicAuthentication),
   "permission-classes": (DjangoModelPermissions,)
}TipsChange the name of the registered user model by changing themappingparameter, such as:rest_framework_extras.register(router, mapping=(("user", UsersViewSet),))Restrict models that will be displayed through the Django Rest Framework by using theonlyandoverrideparameters. Define a comma separated list, such as:rest_framework_extras.discover(router, only=["auth-user", "auth-permission"])todo: document overrideUnit TestingRun tests by using the following command:python manage.py test rest_framework_extras.tests --settings=rest_framework_extras.tests.settings.111LicensePlease see the License requirements in the LICENSE file of this repository.
Package: djangorestframework-files
REST framework filesFile download and upload support for Django REST framework.OverviewREST framework files allows you to download a file in the format used to
render the response and also allows creation of model instances by
uploading a file containing the model fields.RequirementsPython (2.7, 3.5, 3.6)Django REST framework (3.4, 3.5, 3.6, 3.7, 3.8)InstallationInstall usingpip:pip install djangorestframework-filesExamplemodels.pyfromdjango.dbimportmodelsclassABC(models.Model):name=models.CharField(max_length=255)serializers.pyfromrest_frameworkimportserializersfrom.modelsimportABCclassABCSerializer(serializers.ModelSerializer):classMeta:model=ABCfields='__all__'views.pyfromrest_framework.parsersimportJSONParser,MultiPartParserfromrest_framework_files.viewsetsimportImportExportModelViewSetfrom.modelsimportABCfrom.serializersimportABCSerializerclassABCViewSet(ImportExportModelViewSet):queryset=ABC.objects.all()serializer_class=ABCSerializer# if filename is not provided, the view name will be used as the filenamefilename='ABC'# renderer classes used to render your content. will determine the file type of the downloadrenderer_classes=(JSONParser,)parser_classes=(MultiPartParser,)# parser classes used to parse the content of the uploaded filefile_content_parser_classes=(JSONParser,)Some third party packages that offer media type support:ParsersRenderersurls.pyfromrest_frameworkimportroutersfrom.viewsimportABCViewSetrouter=routers.ImportExportRouter()router.register(r'abc',ABCViewSet)urlpatterns=router.urlsDownloadingTo download ajsonfile you can go to the url/abc/?format=json.
Theformatquery parameter specifies the media type you want your
response represented in. To download anxmlfile, your url would be/abc/?format=xml. For this to work, make sure you have the
respectiverenderersto render your response.UploadingTo create model instances from a file, upload a file to the url/abc/. Make sure the content of the file can be parsed by the
parsers specified in thefile_content_parser_classesor else it will
return aHTTP_415_UNSUPPORTED_MEDIA_TYPEerror.For sample file examples you can upload, check theassets
folderFor more examples on how to use the viewsets or generic views, check thetest
application
Package: djangorestframework-filters-mini
Forked fromDjango Rest Framework Filters.This package conflicts with Django Rest Framework Filters;
don’t install both of them in the same environment.Copyright (c) 2013-2015 Philip Neustrom <philipn@gmail.com>,2016-2020 Ryan P Kilby <kilbyr@gmail.com>Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the “Software”), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
Package: djangorestframework-firebase
Django Rest Framework Firebase AuthInstallationpip install djangorestframework-firebaseOn your project'ssettings.pyadd this to theREST_FRAMEWORKconfigurationREST_FRAMEWORK = {
  ...
  'DEFAULT_AUTHENTICATION_CLASSES': (
    'rest_framework_firebase.authentication.FirebaseAuthentication',
  )
  ...
}Get admin credentials.jsonfrom the Firebase SDK and add them to your projectAlso in your project'ssettings.py:FIREBASE_AUTH = {
    'FIREBASE_ACCOUNT_KEY_FILE': 'path_to_your_credentials.json',
}Alternatively, you can configure the Firebase credentials directly, like so:FIREBASE_AUTH = {
    'FIREBASE_CREDENTIALS': {
        'type': "service_account",
        'project_id': "",
        'private_key_id': "",
        'private_key': "",
        'client_email': "",
        'client_id': "",
        'auth_uri': "https://accounts.google.com/o/oauth2/auth",
        'token_uri': "https://accounts.google.com/o/oauth2/token",
        'auth_provider_x509_cert_url': "https://www.googleapis.com/oauth2/v1/certs",
        'client_x509_cert_url': ""
    }
}Publishingpython setup.py sdisttwine upload dist/*
Package: djangorestframework-gis-distance
Django-Rest-Framework-Gis-DistanceThis is a extension toDjango-Rest-Framework-Gisthat adds sorting and distance distance to theDistanceToPointerFilter.RequirementsPython 2.7Django 1.7+Django-Rest-Framework-Gis 0.10+InstallationInstall the library with pip:$ pip install djangorestframework-gis-distanceQuick SetupMake surerest_framework_gis_distanceis added to yourINSTALLED_APPS, afterrest_frameworkandrestframework_gis.INSTALLED_APPS=(# ...'rest_framework','rest_framework_gis','rest_framework_gis_distance',)UsageRegular implementationFirst include DistanceField in your serializer.fromrestframework_gis_distance.fieldsimportDistanceFieldclassRecordSerializer(serializers.ModelSerializer):distance=DistanceField(unit='m')classMeta:model=Recordfields=('location','title','created','distance')Then use the filterOrderedDistanceToPointFilterin your view.fromrestframework_gis_distance.filtersimportOrderedDistanceToPointFilterclassRecordListView(mixins.ListModelMixin,generics.GenericAPIView):permission_classes=(AllowAny,)serializer_class=RecordSerializerqueryset=Record.objects.all()filter_backends=(OrderedDistanceToPointFilter,)distance_filter_field='location'distance_filter_convert_meters=Truedistance_filter_add_distance=TrueAfter this, set up your urls as usual and call your endpoint like this:example.com/api/endpoint/?dist=1000&point=long,latOptional fieldUsing distance as a optional field (for the cases when you only want to
display distance when geo coordinates is supplied)Instead of declaring a straight DistanceField, wrap the DistanceField as
a SerializerMethodField, like this:fromrestframework_gis_distance.filtersimportOrderedDistanceToPointFilterclassRecordOptionalSerializer(serializers.ModelSerializer):distance=serializers.SerializerMethodField()classMeta:model=Recordfields=('location','title','created','distance')defget_distance(self,obj):distance=getattr(obj,"distance",None)returnDistanceField(unit='m').to_representation(distance)OptionsThese belong in your DRF view:distance_filter_field: Target geo filtering field (inherited from
DistanceToPointerFilter).distance_srid: (Optional) The srid you want to use on your
distance. (Default4326)distance_sort_order: (Optional) Indicates the sort order, closest
(True) or farthest (False). (Default:True)QuestionsHow do I change distance unit?Add the param unit=DESIRED_UNIT to your DistanceField, make sure
you use adjango supported
unit.TestsThis library include tests, just runpython runtests.py.ContributingWant to contribute? Awesome. Just send a pull request.LicenseDjango-Rest-Framework-Gis-Distance is released under theMIT
License.
Package: django-rest-framework-google-json-style-api
Django REST Framework Google JSON Style APIFormat specificationhttps://google.github.io/styleguide/jsoncstyleguide.xmlInstallationAt the command line:$ pip install django-rest-framework-google-json-style-apiAdd the render and parser to your django settings file.# ...REST_FRAMEWORK={'PAGE_SIZE':10,'DEFAULT_PAGINATION_CLASS':'rest_framework_google_json_style_api.pagination.GoogleJsonStylePageNumberPagination','DEFAULT_RENDERER_CLASSES':('rest_framework_google_json_style_api.renderers.JSONRenderer',# Any other renders),'DEFAULT_PARSER_CLASSES':('rest_framework_google_json_style_api.parsers.JSONParser',# Any other parsers),}# ...GoalsBy default, Django REST Framework will produce a response like:{"id":1,"username":"scott","full_name":"Scott Chang"}and[{"id":1,"username":"scott","full_name":"Scott Chang"},{"id":2,"username":"pocheng","full_name":"Pocheng Huang"}]Google JSON Style Guide shows a response to look like the following:{"data":{"id":1,"username":"scott","fullName":"Scott Chang"}}and{"data":{"items":[{"id":1,"username":"scott","fullName":"Scott Chang"},{"id":2,"username":"pocheng","fullName":"Pocheng Huang"}]}}Google JSON Style Guide uses camel case for field names. So, by default the package uses camel case.
If you want to use underscores, you must specify it in your django settings file.GOOGLE_JSON_STYLE_API={# ...'CAMELIZE':False# ...}Pagination{"method":"list","params":{"page":"1","pageSize":"2"},"data":{"currentItemCount":2,"itemsPerPage":2,"totalItems":200,"pageIndex":1,"totalPages":100,"nextLink":"http://example.com/api/v1/?page=2&page_size=2","previousLink":null,"items":[{"id":1,"username":"scott","fullName":"Scott Chang"},{"id":2,"username":"pocheng","fullName":"Pocheng Huang"}]}}Attach meta to data objectExampleLet's add the count of items in the data object.classAuthorViewSet(viewsets.ModelViewSet):queryset=Author.objects.all()# ...deflist(self,request,*args,**kwargs):response=super(AuthorViewSet,self).list(request,*args,**kwargs)response.data={'meta':{# Add meta data in here'num_items':self.queryset.count(),},# Keep original data in results'results':response.data}Response{"data":{"numItems":2,"items":[{"id":1,"username":"scott","fullName":"Scott Chang"},{"id":2,"username":"pocheng","fullName":"Pocheng Huang"}]}}Underscoreize OptionsThere are two conventions of snake case.Case 1 (default)v2Counter -> v_2_counter
fooBar2 -> foo_bar_2Case 2v2Counter -> v2_counter
fooBar2 -> foo_bar2By default, the package uses the first case. To use the second case, specify it in your django settings file. The setting only works when you use camel case(default).GOOGLE_JSON_STYLE_API={# ...'JSON_UNDERSCOREIZE':{'no_underscore_before_number':True,},# ...}
Package: djangorestframework-hstore
Django Rest Framework tools fordjango-hstore.Tribute toNodeshotThis code was originally written forNodeshotand then extracted into this generic python package.Compatibility with DRF, Django and PythonDRF-hstore versionDRF versiondjango-hstore versionDjango versionPython version1.33.1.x1.3.1to1.4.01.6,1.7,1.82.7,3.41.23.1.x1.3.1to1.4.01.6,1.7,1.82.7,3.41.12.4.x1.3.1to1.3.51.6,1.72.7,3.41.02.4.x1.3.1to1.3.51.6,1.72.7,3.4Installpipinstalldjangorestframework-hstoreHStoreField UsageThis field is not sufficient to supportdjango-hstoreschema-mode.fromrest_frameworkimportserializersfrommyapp.modelsimportMyModel# rest_framework_hstorefromrest_framework_hstore.fieldsimportHStoreFieldclassMyHStoreSerializer(serializers.ModelSerializer):data=HStoreField()classMeta:model=MyModelHStoreSerializer UsageSupportsdjango-hstoreDictionaryFieldandschema-modeout of the box.Prefer this toHStoreField.frommyapp.modelsimportMyModel# rest_framework_hstorefromrest_framework_hstore.serializersimportHStoreSerializerclassMyHStoreSerializer(HStoreSerializer):classMeta:model=MyModelContributingJoin theDjango REST Framework HStore Mailing
Listand announce your intentionsFollow thePEP8 Style Guide for Python
CodeFork this repoWrite codeWrite tests for your codeEnsure all tests passEnsure test coverage is not under 90%Document your changesSend pull requestBSD LicenseCopyright (C) 2014 Federico CapoanoPermission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the “Software”), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
Package: djangorestframework-include-mixin
Django REST framework light includable serializer fieldsRequirementsPython (2.7, 3.4, 3.5, 3.6)Django REST Framework(>=3.0)Usageserializers.pyclassGroupSerializer(SerializerIncludeMixin,ModelSerializer):@classproperty# django.utils.decoratorsdefextra_objects(cls):return{'users':UserSerializer(source='user_set',many=True),'active_users':UserSerializer(many=True),}classMeta:model=Groupfields=('id','name')views.pyclassGroupViewSet(QueryOptimizerMixin,ReadOnlyModelViewSet):"""Groups.list:Available includable objects:* users - all users;* active_users - only active users."""queryset=Group.objects.all()serializer_class=GroupSerializerselect_related={}prefetch_related={'users':'user_set','active_users':Prefetch(lookup='user_set',queryset=User.objects.filter(is_active=True),to_attr='active_users',),}And now we can to do that:client=APIClient()response=client.get(# GET /groups/?include[]=active_users'/groups/',data=[('include[]','active_users'),],)This will make only 2 query:all groupsprefetch only active usersDocumentationrest_framework_include_mixin.SerializerIncludeMixinUsed in any serializer to automatically replace and add serializer fields.extra_objectsclass variablekey:str - value from GET parameterinclude[].
For example,profilefor/users/?include[]=profile.value:Serializer - any field serializer.Example:classUserSerializer(SerializerIncludeMixin,ModelSerializer):extra_objects={'profile':ProfileSerializer(),'groups':GroupSerializer(many=True),}classMeta:model=Userfields=('id','profile_id')GET parametersResult serializer fields'id': IntegerField(), 'profile_id': IntegerField()?include[]=profile'id': IntegerField(), 'profile': ProfileSerializer()?include[]=groups'id': IntegerField(), 'profile_id': IntegerField(), 'groups': GroupSerializer(many=True)?include[]=profile&include[]=groups'id': IntegerField(), 'profile': ProfileSerializer(), 'groups': GroupSerializer(many=True)Note: standard serializer fields with/without_idwill be replaced to field fromextra_objects.For?include[]=profile:profileandprofile_idwill be replaced toprofilefromextra_objects.rest_framework_include_mixin.QueryOptimizerMixinUsed with ModelViewSet to optimize database queries.select_relatedclass variablekey:str - value from GET parameterinclude[].value:str - field name that can be passed to select_related (model manager function).prefetch_relatedclass variablekey:str - value from GET parameterinclude[].value:Union[str, Prefetch] - field name or Prefetch object that can be passed to prefetch_related (model manager function).