Saravanan666/pypi-org huggingface dataset:
Package: drf-is-not-authenticated-class
Django Rest Framework Authentication Class for not authorized usersSome DRF views should not be accessible by logged in users.
In such cases we need permission class that will not allow authorized users to access the resource or action.Installationpipinstalldrf_is_not_authenticated_classUse casesOnly not registered users should be able to create new userfromdrf_is_not_authenticated_classimportIsNotAuthenticatedclassRegisterUser(CreateAPIView):queryset=User.objects.all()permission_classes=(IsNotAuthenticated,)Contribution
Package: drfjsonapi
OverviewJSON API reference implementation for Django Rest FrameworkThis is an extremely thorough implementation of the JSON API 1.0 specification
for the Django Rest Framework. It has strict error handling of non-compliant
clients & follows all of the MUST’s of the spec (or will soon where missing).Known incomplete JSON API spec features/guidelines are:Error object pointers“Relationship Links”Error object pointers isn’t very great currently. It handles field-level,
resource-level, & relationship “pointer” construction just fine but I
don’t think it will handle any sort of complex nested field errors. The
pointer may not be accurate. I’ll have to test & figure out a way to do
that properly with DRF & it’s native ValidationError field names.This matters when you look at RFC 6901. We may need something more robust
here as an additional DRF plugin that drfjsonapi requires.Relationship links are the “self” member of the links object for relationships.
Currently, ember doesn’t support relationship modificiation for that endpoint
so I have no incentive yet to write it. Having said that, some abstractions
have already been written in this library to make the transition easy in the
future.Aside from those known limitations this library is REALLY complete. A TON of
focus & attention was spent on meaningful errors & good exception handling.
Much more to come on that front as I’m aware needs to be more thorough but
those enhancements will come without needing to worry about the JSON API spec.A breakdown of notable features currently implemented that you’d want in any
JSON API server implementation are:filterquery params (spanning relationships)includequery params (spanning relationships)pagequery paramssortquery paramsrelated resource linksridiculously easy to follow codecomprehensive error handling (parsers, serializers, views, etc)error coalescinghooks for almost every part of the JSON API processing pipelinegood quality code commentsRequirementsPython (2.7, 3.3, 3.4)Django (1.6, 1.7, 1.8)Django REST Framework (2.4, 3.0, 3.1)InstallationInstall usingpip…$pipinstalldrfjsonapiExampleTODO: Write example.TestingInstall testing requirements.$pipinstall-rrequirements.txtRun with runtests.$./runtests.pyYou can also use the excellenttoxtesting tool to run the tests
against all supported versions of Python and Django. Install tox
globally, and then simply run:$toxDocumentationTo build the documentation, you’ll need to installmkdocs.$pipinstallmkdocsTo preview the documentation:$mkdocsserveRunningat:http://127.0.0.1:8000/To build the documentation:$mkdocsbuild
Package: drf-jsonapi
OverviewDjango Rest Framework tools which are compliant with the JSONAPI 1.0 specification.Documentation:django-rest-framework-jsonapi.rtfd.orgRequirementsPython (2.7, 3.4)Django (1.6, 1.7, 1.8)Django REST Framework (3.1)InstallationInstall usingpip…$pipinstalldrf-jsonapiTestingInstall 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:$toxDocumentationThe documentation is browsable on Read the Docs:django-rest-framework-jsonapi.rtfd.orgTo build the documentation, you’ll need to installmkdocs.$pipinstallmkdocsTo preview the documentation:$mkdocsserveRunningat:http://127.0.0.1:8000/To build the documentation:$mkdocsbuild
Package: drf-json-api-atomic-operations
drf-json-api-atomic-operationExtension fordjango-rest-framework-json-apito supportatomic operations.See theusagesection of the docs for example integration.Implemented Featurescreating, updating, removing multiple resources in a single request (sequential db calls optional bulk db calls for create and delete)Updating To-One RelationshipsUpdating To-Many Relationshipserror reporting with json pointer to the concrete operation and the wrong attributesToDopermission handlinglocal identity (lid)handling
Package: drf-json-api-utils
DRF Json Api UtilsUtilities to massivly reduce the boiler-plating ofdjango-rest-framework.This project currenly only supports and is specific todjango-rest-framework-json-api, if requested will extend it to generaldjango-rest-frameworksupport.The source for this project is available here.Add better docs.Example UsageBy just doing this:user_urls=JsonApiViewBuilder(model=MyUser,resource_name='users',allowed_methods=[json_api_spec_http_methods.HTTP_GET])\.fields(['email','first_name','last_name'])\.add_filter(name='email',lookups=(lookups.EXACT,lookups.IN))\.add_filter(name='order',field='orders__id',lookups=(lookups.EXACT,lookups.IN))\.add_relation(field='orders',many=True)\.get_urls()order_urls=JsonApiViewBuilder(model=Order,resource_name='orders',allowed_methods=[json_api_spec_http_methods.HTTP_GET])\.fields(['product','date','price'])\.add_relation(field='user',resource_name='users')\.get_urls()You can get this:GET /api/users?filter[email]=amit.assaraf@gmail.com{"links":{"first":"http://localhost:8000/api/users?filter%5Bemail%5D=soit48%40gmail.com&page%5Bnumber%5D=1","last":"http://localhost:8000/api/users?filter%5Bemail%5D=soit48%40gmail.com&page%5Bnumber%5D=1","next":null,"prev":null},"data":[{"type":"users","id":"76f7c463-b6a8-4b20-917a-ef98c546eec4","attributes":{"first-name":"Amit","last-name":"Assaraf","email":"amit.assaraf@gmail.com",},"relationships":{"orders":{"meta":{"count":2},"data":[{"type":"orders","id":"6b99e044-462f-472e-9fed-307436b73549"},{"type":"orders","id":"304f7f60-7e24-494e-98e2-e9786a3eb588"}],"links":{"self":"http://localhost:8000/api/users/76f7c463-b6a8-4b20-917a-ef98c546eec4/relationships/orders","related":"http://localhost:8000/api/orders/76f7c463-b6a8-4b20-917a-ef98c546eec4/"}}}}],"meta":{"pagination":{"page":1,"pages":1,"count":1}}}
Package: drf-jsonresponse
DRF-jsonresponsedjango restframework 默认是遵循restful api在中国生产环境中一般不会采用restful规则，返回的结果是通过json_code状态码和message来完成的该文档修改了原有的mixins，修改返回内容格式list：有分页效果，需要在settings文件中单独设置REST_FRAMEWORK={'DEFAULT_PAGINATION_CLASS':'base.pagination.LargeResultsSetPagination','PAGE_SIZE':20,}create，update，retrieve
Package: drf-jsonschema
drf-jsonschema, created by Kiratech from extendingjsonschemapackage.
This package provides JsonSchemaField and constructs JsonSchema validation error into error tree for Django Rest Framework with custom error message.This package will installjsonschemaautomatically so manual installation is not necessary.Quick StartYou can use JsonSchemaFieldValidator in Django’smodels.pyas such:from drf_jsonschema import JsonSchemaFieldValidator
...
...
json_data = models.JSONField(validators=[JsonSchemaFieldValidator(schema=your_json_schema)])Onserializers.py, modify the serializer field mapping fromJSONFieldtoJSONSchemaFieldas the example below:from drf_jsonschema.serializers import JsonSchemaModelSerializer

class YourSerializer(JsonSchemaModelSerializer):
    ...For more information, visitjsonschema
Package: drf-jsonschema-serializer
Version:2.0.0Source:https://github.com/maykinmedia/drf-jsonschema-serializerKeywords:django, rest, jsonschemaJSON Schema support for Django REST FrameworkOverviewdrf-jsonschema-serializer is a library built around Django REST Framework. It does the
following:Convert a DRF serializer into a JSON Schema.ProvidesJSONSchemaFieldthat can validate JSON data according to
a JSON schema.Provides aSerializerJSONFieldthat can validate JSON data according to
a serializer for a field.This lets you use client-side form libraries such as react-jsonschema-form to
generate a web form from a serializer. This way you can use the same schema for
client-side form generation and validation as you use for REST service input
validation.See thedocumentationfor getting started and usage examples.Credits and roadmapMany thanks tohttps://github.com/isprojectsfor the initial work on this library.
As of September 2021, Maykin Media has taken up maintenance of this package after
transferring it from isprojects. See the issues on Github for the roadmap.See also CREDITS.txt for a full history of authorship.
Package: drf-jwt
REST framework JWT AuthJSON Web Token Authentication support for Django REST FrameworkOverviewThis package providesJSON Web Token Authenticationsupport
forDjango REST framework.If you want to know more about JWT, check out the following resources:DjangoCon 2014 - JSON Web TokensVideo|SlidesAuth with JSON Web TokensJWT.ioRequirementsPython 2.7, 3.4+Django 1.11+Django REST Framework 3.7+Installation$pipinstalldrf-jwtDocumentation & SupportFull documentation for the project is available atdocs.
Package: drf-jwt-auth
DRF JWT AuthDjango REST Framework JWT Authentication package enables to authenticate to Django REST Framework's API Views and ViewSets by using JWT (in header or as query param).In difference with other packages, this package offers the following features:The user autheticated is based on the payload info, sono user is loaded from database.So that, the user model that you will find on everyrequest.userwill be an instance ofdrfjwtauth.user.JWTUser, a class that keeps the same API thatdjango.contrib.auth.models.Userbut is not loaded from database and no write operations can be made over that user (due to it's not a model).Provides a view (indrfjwtauth.views.VerifyJWTView) to verify a token using a POST request.NO login or token renew views are providedInstallation$pipinstalldrf-jwt-authSetupAuthentication classYou can setup DRF JWT Auth as authentication class in two ways:As default authentication class adding to theDEFAULT_AUTHENTICATION_CLASSESkey in the the global DRF settings:REST_FRAMEWORK={[...]'DEFAULT_AUTHENTICATION_CLASSES':['...','drfjwtauth.auth.JWTAuth','...'],[...]}In every APIView/ViewSet/view function:fromrest_framework.viewsimportAPIViewfromdrfjwtauth.authimportJWTAuthclassExampleView(APIView):authentication_classes=[JWTAuth]@authentication_classes([JWTAuth])defexample_view(request,format=None):[...]Token Verify ViewIn your project'surls.py:fromdjango.urlsimportpathfromdrfjwtauth.viewsimportVerifyJWTViewurlpatterns=[[...],path('token/verify/',VerifyJWTView.as_view(),name='token-verify')[...],]Available settings and defaultsIn your Django project's settings you can setup the following dict and keys:DRF_JWT_AUTH={'ALGORITHM':JWTalgorithmtosigntokens(HS256bydefault).'SIGNING_KEY':Secretkeytosigntokens(samevalueasDjangoSECRET_KEYsettingsbydefault).'AUTH_HEADER':ValuebeforethetokenintheHTTPAuthorizationheader(Bearerbydefault).'QUERY_PARAM_NAME':ValuebeforethequeryparamnameforHTTPGETrequests(jwtbydefault).}Django management commandsThis package adds two management commands that let's you to create JWT with a specific expiration date,generate_jwtandgenerate_jwt_from_db:generate_jwt: Accept the next arguments to create a JWT without database based on default's Django User Model:username[positional][mandatory]-d,--expiration_date[mandatory]. A date in isoformat  to invalidate the JWT.--id[optional]--first_name[optional]--last_name[optional]--email[optional]--is_active[optional]--is_staff[optional]--is_superuser[optional]--channels...  [optional]--groups...  [optional]--permissions...  [optional]For example:python manage.py generate_jwt new_user -d 2030-12-31 --id 1 --first_name New --last_name User --email new_user@company.com --is_active --is_staff --channels a b --groups web_users --permissions can_visit_dashboardsgenerate_jwt_from_db: Given a username and a expiration date will return a JWT for the matched user in the database:username[positional][mandatory]-d,--expiration_date[mandatory]. A date in isoformat  to invalidate the JWT.For example:python manage.py generate_jwt existing_user -d 2030-12-31
Package: drf-jwt-knox
DRF JWT + KnoxThis package provides an authentication mechanism for Django REST
Framework based onJSON Web Tokensin the browser backed up byKnox-powered tokens in the database.This package aims to take the better parts of both worlds, including:Expirable tokens: The tokens may be manually expired in the
database, so a user can log out of all other logged-in places, or
everywhere.Different tokens per login attempt (per user-agent), meaning that a
user's session is tied to the specific machine and logging can be
segregated per usage.JWT-based tokens, so the token can have an embedded expiration time,
and further metadata for other applications.Tokens are generated via OpenSSL so that they are cryptographically more secure.Only the tokens' hashes are stored in the database, so that even if
the database gets dumped, an attacker cannot impersonate people
through existing credentialsOther applications sharing the JWT private key can also decrypt the JWTUsageAdd this applicationand knoxtoINSTALLED_APPSin yoursettings.py.Then, add this app's routes to some of yoururlpatterns.You can use theverifyendpoint to verify whether a token is valid
or not (which may be useful in a microservice architecture).TestsTests are automated withtoxand run on Travis-CI automatically. You
can check the status in Travis, or just runtoxfrom the command
line.ContributingThis project uses the GitHub Flow approach for contributing, meaning
that we would really appreciate it if you would send patches as Pull
Requests in GitHub. If for any reason you prefer to send patches by email, they are also welcome and will end up being integrated here.LicenseThis code is released under the Apache Software License Version 2.0.
Package: drf-jwt-wechat
drf-jwt-wechat 是在jwt，跟rest_framework_jwt基础上进行修改过的，用于微信小程序登录，
前端只需post方法传code即可进行jwt登录验证Usage在django项目settings中添加修改APP_ID=xxxx，APP_SECRET=xxxxx,以及跟rest_framework_jwt包同样配置如下REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
    'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
    'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
    'rest_framework.authentication.SessionAuthentication',
    'rest_framework.authentication.BasicAuthentication',
),在url中引用from drf_jwt_wechat.views import obtain_jwt_token
#...

urlpatterns = [
    '',
    # ...

    url(r'^api-token-auth/', obtain_jwt_token),
]后续因为水平有限，目前只有登录，没有Refresh Token，以及Verify Token，不影响rest_framework_jwt的api使用。
任何问题请联系https://github.com/liazylee/源码详解https://blog.csdn.net/liazylee/article/details/90717939
Package: drf-keycloak
In this project, we implement authentication using theAuthorization Code Flowwith Keycloak as the identity and access management service. Here is how the authentication flow is structured:Frontend Responsibility:User Registration and Login: The frontend handles user registration and login through Keycloak, facilitating a seamless user experience.Backend Responsibility:Token Validation: Once a user is authenticated, the backend takes over by validating the JWT (JSON Web Token) from the header of each incoming request to ensure it is valid and secure.This approach allows us to keep the backend implementation relatively simple, focusing mainly on token validation, while leveraging Keycloak’s robust authentication and authorization features through the frontend.SettingsYou can find a selection of variables indrf_keycloak.settings.py, just overwrite them in the Django settings.KEYCLOAK_CONFIG={"SERVER_URL":"http://localhost:8080/","REALM":"master","CLIENT_ID":"account","CLIENT_SECRET":None,"AUDIENCE":None,"ALGORITHM":"RS256","ISSUER":"http://localhost:8080/realms/master","VERIFY_TOKENS_WITH_KEYCLOAK":False,"PERMISSION_PATH":"resource_access.account.roles","USER_ID_FIELD":"username","USER_ID_CLAIM":"preferred_username",# user mapping# django keys, keycloak keys"CLAIM_MAPPING":{"first_name":"given_name","last_name":"family_name","email":"email","username":"preferred_username",},}By setting the variableKEYCLOAK_CONFIG={# ..."VERIFY_TOKENS_WITH_KEYCLOAK":True# ...}This means that the token is validated with the Keycloak API and locally.EnableAddkeycloaktoINSTALLED_APPS.INSTALLED_APPS=["django.contrib.auth",# ..."drf_keycloak"]Adddrf_keycloak.authentication.KeycloakAuthBackendto DRF settingsREST_FRAMEWORK={"DEFAULT_AUTHENTICATION_CLASSES":[# ..."drf_keycloak.authentication.KeycloakAuthBackend",# ...],}PermissionsTo create permissions for your API follow the example inHasViewProfilePermissionindrf_keycloak.permissions.py.Use it as usual…fromdrf_keycloak.permissionsimportHasPermissionclassExamplePermission(HasPermission):permission="view-profile"classUserApi(generics.RetrieveAPIView):permission_classes=[ExamplePermission]MiddlewareFor security reasons, use the optional middleware indrf_keycloak.middleware.HeaderMiddlewareat the top of the settings.MIDDLEWARE=["drf_keycloak.middleware.HeaderMiddleware",# ...]You should also look at Mozilla’sdjango-csppackage.OpenAPI Schema with drf-spectacularIn anyapps.pyor file that is loaded at startupfromdjango.appsimportAppConfigclassMyAppConfig(AppConfig):"""app config"""default_auto_field="django.db.models.BigAutoField"name="myapp"defready(self):importdrf_keycloak.schema# noqa: E402ThanksThanks todjango-rest-framework-simplejwt, the code was inspirational for this package.
Package: drf-keyed-list
Keyed Lists for Django REST FrameworkThis package supports the serialization and deserialization of a list of objects stored in adictwhere a unique
value from the object (often apk) is used as the key in the dict.  For example,{
    "1": {<other fields for object with id 1>},
    "2": {<other fields for object with id 2>},
    ...
}Installpip install drf-keyed-listUsageThe following is a usage example:class MySerializer(ModelSerializer):

    class Meta:
        list_serializer_class = KeyedListSerializer
        keyed_list_serializer_field = 'id'By replacing thelist_serializer_class, this behavior will only be enabled when themany=Trueflag is used:instance = {
   "id": "pk_val",
   "field1": "val1",
   "field2": "val2",
   ...
}

serializer = MySerializer(data=instance)
# this should work
serializer.is_valid()
serializer.save()

keyed_list = {
   "pk_val": {
       "field1": "val1",
       "field2": "val2",
       ...
   }
}

# many=True will trigger the keyed-list behavior
serializer = MySerializer(data=keyed_list, many=True)
# this should also work
serializer.is_valid()
serializer.save()NOTE:keyed_list_serializer_fieldMUSTrefer to a Unique field or key collision may occur during serialization,
plus undefined deserializaiton behavior if used in combination with nested writable serializers (e.g.drf-writable-nested).  At this time, the package does not
make any effort to verify that a Unique field has been selected.Authors2018, Clayton Daley III
Package: drf-keyed-list-bihealth
Keyed Lists for Django REST FrameworkThis package supports the serialization and deserialization of a list of objects stored in adictwhere a unique
value from the object (often apk) is used as the key in the dict.  For example,{
    "1": {
        <other fields for object with id 1> 
    },
    "2": {
        <other fields for object with id 2>
    },
    ...
}Installpip install drf-keyed-listUsageThe following is a usage example:fromdrf_keyed_listimportKeyedListSerializerclassMySerializer(ModelSerializer):classMeta:list_serializer_class=KeyedListSerializerkeyed_list_serializer_field='id'By replacing thelist_serializer_class, this behavior will only be enabled when themany=Trueflag is used:instance={"id":"pk_val","field1":"val1","field2":"val2",# ...}serializer=MySerializer(data=instance)# this should workserializer.is_valid()serializer.save()keyed_list={"pk_val":{"field1":"val1","field2":"val2",# ...}}# many=True will trigger the keyed-list behaviorserializer=MySerializer(data=keyed_list,many=True)# this should also workserializer.is_valid()serializer.save()NOTE:keyed_list_serializer_fieldMUSTrefer to a Unique field or key collision may occur during serialization,
plus undefined deserializaiton behavior if used in combination with nested writable serializers (e.g.drf-writable-nested).  At this time, the package does not
make any effort to verify that a Unique field has been selected.Non-String Keys (e.g. UUIDs)Per theJSON RFCthe keys (a.k.a. "names") in a JSON structure
must be strings.  The JSON Encoder in Py2 only accepts strings; in Py3, the encoder accepts some additional types (i.e.int,float,boolorNone), but these must eventually be converted to strings.  Other types are not supported,
including common key types like UUID.Per the discussion in issue #6, the recommended strategy for non-string keys is to use an expicit (if necessary, custom)
serializer field.  This field should implementto_representationandto_internal_valueto convert the data to a
string. For a UUID, the built-inUUIDFieldis sufficient.Authors2018, Clayton Daley III
Package: drf-lafv
OverviewA better way than DRF proposed for do some basic filtersRequirementsPython (2.7,3.2,3.3,3.4, 3.5 -with Django 1.8-)Django (1.7, 1.8)Django REST Framework (3.0, 3.1, 3.2)InstallationInstall usingpip…$pipinstalldrf-lafvExampleImagine that you have the following models.pyfromdjango.dbimportmodelsclassAuthor(models.Model):name=models.CharField(max_length=250)nickname=models.CharField(max_length=100)classBook(models.Model):title=models.CharField(max_length=200)description=models.TextField()publication_date=models.DateField()isbn=models.CharField(max_length=17)author=models.ForeignKey(Author)And you want to filter your list of books by author’s nickname, isbn and create
a custom filter which will allow to get you books that were published less than
30 days ago. Well, DRF per se, ask you to install django-filter and write a
bunch of stuff that maybe hard. Withlafvyou can accomplish this doing this:fromlafv.viewsimportListAPIFilteredViewfromserializersimportBookSerializerclassBookView(ListAPIFilteredView):queryset=Book.objects.all()serializer_class=BookSerializerfilter_fields=('author__nickname','isbn')custom_filters=('new',)deffilter_new(self,queryset):"""
        get books that publication date is no longer than 1 month
        """last_month=datetime.today()-timedelta(days=30)queryset=queryset.filter(publication_date__gte=last_month)returnquerysetAnd that’s it!, please check the examples on the test appTestingInstall testing requirements.$pipinstall-rrequirements.txtRun with runtests.$./runtests.pyYou can also use the excellenttoxtesting tool to run the tests
against all supported versions of Python and Django. Install tox
globally, and then simply run:$toxDocumentationTo build the documentation, you’ll need to installmkdocs.$pipinstallmkdocsTo preview the documentation:$mkdocsserveRunningat:http://127.0.0.1:8000/To build the documentation:$mkdocsbuild