Saravanan666/pypi-org huggingface dataset:
Package: drf-swaggify
OverviewA Django Rest Framework API documentation generator.RequirementsPython 2.7Django 1.8Django REST Framework 3.2.2InstallationInstall usingpip…$pipinstalldrf-swaggifyExampleTODO: 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: drft
DRFTDjango REST Framework Toolkit (DRFT)Installationpip install drftLocal DevelopmentPyenvIt's recommended that you usepyenvpyenv-installercurl-Lhttps://github.com/pyenv/pyenv-installer/raw/master/bin/pyenv-installer|bashInstallpoetryThis project usespoetry. Install it using the following command.curl-sSLhttps://raw.githubusercontent.com/python-poetry/poetry/master/get-poetry.py|python-More instructionshereInstall the dependencies:poetry installInstall pre-commit hooks:poetry run pre-commit installRunning Tests:poetry run tests
Package: drf-temptoken
drf-temptokenDRF temporary authentication tokenInstallationpipinstalldrf-temptokenUsageInclude drf_temptoken in INSTALLED_APPSINSTALLED_APPS=[...,'drf_temptoken']Add drf_temptoken.auth.TempTokenAuthentication into your authentication classesREST_FRAMEWORK={'DEFAULT_AUTHENTICATION_CLASSES':('drf_temptoken.auth.TempTokenAuthentication',)}Create token for userfromdjango.contrib.authimportget_user_modelfromdrf_temptoken.utilsimportcreate_token,get_user_tokensUser=get_user_model()user=User.objects.first()token=create_token(user)# Sets token's expiration date to currenttoken=token.expire()key=token.key# Used in authentication processtokens=get_user_tokens(user)# Returns a queryset of TempTokens belonging to the userDefault settings (can be overriden in Django's settings)TMP_TOKEN_HEADER_PREFIX='TMP'TMP_TOKEN_AUTH_HEADER='Authorization'# Set any value in order to get the token from queryTMP_TOKEN_QUERY_PARAM=None# Python's timedelta kwargs passed in order to set token's expiration dateTMP_TOKEN_TIME_DELTA_KWARGS={'days':7# Token will be expired in 7 days by default}Auth backend will check for HTTP_AUTHORIZATION: TMP {token} by defaultAssuming your token (token.key) is equal to "123", your request should look like this:importrequestsheaders={'Authorization':'TMP 123'}response=requests.get(url,headers=headers)Or like this if you set query param to _api_key:importrequestsurl='https://example.com?_api_key=123'response=requests.get(url)
Package: drf_timeordered_pagination
OverviewPagination utilities for Django REST Framework to allow for pagination by a mutable, but time-ordered field (like ‘modified’).RequirementsPython (2.7, 3.3, 3.4)Django (1.8+)Django REST Framework (3.1+)Important notesThe layout of the docs and the Git project were borrowed from:
- drf-proxy-pagination
- django-nsync (which was borrowed from other people too!)InstallationInstall usingpip…$pipinstalldrf-timeordered-paginationInviews.py, hook up your own integration into the pagination, or use one of the provided ones like so:classExampleClass(django.Model):...modified=DateTimeField(...)...fromtimeordered_pagination.viewsimportTimeOrderedPaginationViewSetMixinclassExampleClassView(TimeOrderedPaginationViewSetMixin,...,viewsets.ModelViewSet)...Examplehttp://api.example.org/examples/gives default pagination.http://api.example.org/examples/?modified_after=1900-01-01T00:00:00Zgives all examples, modified after (greater than) Midnight, 1 Jan 1900, in modified orderhttp://api.example.org/examples/?modified_from=1900-01-01T00:00:00Zgives all examples, modified from (greater than or equal to) Midnight, 1 Jan 1900, in modified orderTestingInstall testing requirements.$pipinstall-rrequirements.txtRun with pytest.$py.testYou 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-tracking-logger
DRF Request loggerA spinoff of thedrf-trackingto forward the logging to the standard output instead of saving it in the databaseInstallationpipinstalldrf-tracking-loggerUsageTo use a specific logger name, set an environment variableTRACKING LOGGER.The package provides a mixinLoggingMixinwhich you can include to your class based views to log the requests.Example,fromrest_framework.genericsimportGenericAPIViewfromrest_framework.mixinsimportListModelMixinfromdrf_tracking_logger.mixinsimportLoggingMixinclassAnyRandomView(LoggingMixin,ListModelMixin,GenericAPIView):...Optionslogging_methods: This attribute can used to strip down the request methods which needs to be logged.It logs all the methods by default.should_log: This method can be used to customize the logic to determine the logging.handle_log: You can override this method to change the logging behavior. It sends the log to the configured logger by default.sensitive_fields: By default, any key name which has any of'key', 'secret', 'password', 'signature'in its name, will get its value hidden. But you can extend this list by adding more using this attribute.Logging OverviewYou'll get these attributes for every request/response cycle to a view that uses the mixin:Model field nameDescriptionModel field typeuserUser if authenticated, None if notForeign Keyrequested_atDate-time that the request was madeDateTimeFieldresponse_msNumber of milliseconds spent in view codePositiveIntegerFieldpathTarget URI of the request, e.g.,"/api/"CharFieldviewTarget VIEW of the request, e.g.,"views.api.ApiView"CharFieldview_methodTarget METHOD of the VIEW of the request, e.g.,"get"CharFieldremote_addrIP address where the request originated (X_FORWARDED_FOR if available, REMOTE_ADDR if not), e.g.,"127.0.0.1"GenericIPAddressFieldhostOriginating host of the request, e.g.,"example.com"URLFieldmethodHTTP method, e.g.,"GET"CharFieldquery_paramsDictionary of request query parameters, as textTextFielddataDictionary of POST data (JSON or form), as textTextFieldresponseJSON response data.This will be skipped for GET requestsTextFieldstatus_codeHTTP status code, e.g.,200or404PositiveIntegerField
Package: drf-translated
drf-translateddjango-modeltranslation DRF serializersFeaturesQuery/context translation supportHighly customizableInstallationpipinstalldrf-translatedUsageCreate a drf_translated.serializers.TranslatedModelSerializer serializer for your registered translation model:fromdrf_translated.serializersimportTranslatedModelSerializerclassMovieSerializer(TranslatedModelSerializer):classMeta:model=Moviefields='__all__'SettingDefaultDescriptionDRF_TRANSLATED_QUERY_PARAMlanguageQuery language param to convert translated values from dict to strDRF_TRANSLATED_LOCALE_CONTEXTlocaleSerializer context key for getting translation language
Package: drf-tree-router
Django REST Framework Tree Routerpipinstalldrf-tree-routerDocumentation:https://mrthearman.github.io/drf-tree-router/Source Code:https://github.com/MrThearMan/drf-tree-router/A Django REST Framework router that can be nested with other routers to create a tree-like structure
of your API endpoints. The router also accepts APIViews in addition to ViewSets.
Package: drf-tus
A Tus (tus.io) library for Django Rest FrameworkDocumentationThe full documentation is athttps://drf-tus.readthedocs.io.QuickstartInstall drf-tus:pip install drf-tusAdd it to yourINSTALLED_APPS:INSTALLED_APPS=(..."rest_framework_tus",...)Add the middleware toMIDDLEWARE:MIDDLEWARE=(..."rest_framework_tus.middleware.TusMiddleware",...)Add URL patterns for drf-tus:urlpatterns=[...path(r"^",include("rest_framework_tus.urls",namespace="rest_framework_tus")),...]FeaturesThis library implements the following TUS API v1.0.0 protocols:Core Protocol (http://tus.io/protocols/resumable-upload.html#core-protocol)Creation Protocol (http://tus.io/protocols/resumable-upload.html#creation)Expiration Protocol (http://tus.io/protocols/resumable-upload.html#expiration)Checksum Protocol (http://tus.io/protocols/resumable-upload.html#checksum)Termination Protocol (http://tus.io/protocols/resumable-upload.html#termination)Running TestsDoes the code actually work?source <YOURVIRTUALENV>/bin/activate
(myenv) $ pip install tox
(myenv) $ toxCreditsTools used in rendering this package:Cookiecuttercookiecutter-djangopackageHistory2.0.1 (2023-10-13)Repair CI and tests.2.0.0 (2023-07-06)Django 4.2 LTS compatibility.1.21.2 (2018-09-04)Fixed Django compatibility.1.21.1 (2018-08-01)Fixed failing travis build.1.21 (2018-08-01)Updated Django dependency and dropped support for Python 3.3.x (https://github.com/dirkmoors/drf-tus/pull/9).1.20 (2018-02-12)Implemented per-view max file size setting (https://github.com/dirkmoors/drf-tus/pull/8).1.19 (2018-02-08)Fixed bug that occurred when pausing uploads (https://github.com/dirkmoors/drf-tus/pull/7).1.18 (2018-02-08)Make the metadata ‘filename’ key a setting. (https://github.com/dirkmoors/drf-tus/pull/2).Switch from (Positive)IntegerField to BigIntegerField for the upload_length and upload_offset fields (https://github.com/dirkmoors/drf-tus/pull/3).Increase Django version support up to 1.11 (https://github.com/dirkmoors/drf-tus/pull/4).Fix unicode errors (https://github.com/dirkmoors/drf-tus/pull/5).Updated travis configuration.1.17 (2017-05-10)Exchanged use ofbase64.encodebytestobase64.b64encode.1.16 (2017-05-04)Implementedvalidate_filenamehandler inTusCreateMixin.1.15 (2017-04-06)Added missing migration and changed max_length to 255 for modelUpload’s attributeuploaded_file.1.14 (2017-03-30)Updated default behaviour of theget_headerhandler inTusMiddleware.1.13 (2017-03-30)Implemented handler for retrieving request headers inTusMiddleware.1.12 (2017-03-10)Updatedvalidate_chunksignature.1.11 (2017-03-10)Implementedvalidate_chunkhandler method in TusPatchMixin.Implementedvalidate_success_headershandler method in TusCreateMixin.1.10 (2017-03-09)Disabled chunk writing to disk.1.9 (2017-03-09)Introduced TusUploadStreamParser.1.8 (2017-03-09)Introduced setting to include serializer data in response body.1.7 (2017-03-09)Bugfixes.1.6 (2017-03-09)Bugfixes.1.5 (2017-03-09)Updated middleware, removed required header (bug!).1.4 (2017-03-09)Initial migration.1.3 (2017-03-09)Renamed some parameters / classes.1.2 (2017-03-09)Cleanup repository.1.1 (2017-03-09)First release on PyPI.
Package: drf-typed
Django REST - TypedThis project extendsDjango REST Frameworkto allow use of Python's type hints for automatically validating view parameters, as well as supporting typed attributes and annotation-generated fields on serializers.Deriving automatic behavior from type annotations has become increasingly popular with theFastAPIandDjango Ninjaframeworks. The goal of this project is to provide these benefits to the DRF ecosystem.Main benefits:View inputs can be individually declared, not buried inside all-encompassingrequestobjects.Type annotations can replace repetitive view validation/sanitization code.Simple serializers can have their fields auto-generated from annotationsValidated serializer data can be accessed from attributes, with their types known to the IDEPydanticmodels are compatible types for view parameters. Annotate your POST/PUT functions with them to automatically validate incoming request bodies.Documentation:https://rsinger86.github.io/drf-typedSource Code:https://github.com/rsinger86/drf-typedViews Examplefromrest_typed.viewsimporttyped_api_view"""GET /users/registered/?registered_on=2019-03-03&staff=yes"""@typed_api_view(["GET"])defget_users(registered_on:date=None,staff:bool=None):print(registered_on,is_staff)# date(2019, 3, 3) Truedata=query_orm(registered_on,is_staff)returnResponse(data)Serializers Examplefromdatetimeimportdatefromrest_typed.serializersimportTSerializerclassMovieSerializer(TSerializer):title:str# same as: CharField(required=True, allow_null=False)release_date:date# same as: DateField(required=True, allow_null=False)description=None# same as: DateField(default=None)movie=MovieSerializer(data={"title":"The Last Duel","release_date":"2021-10-15",})movie.is_valid(raise_exception=True)print(movie.validated_data)"""{"title": "The Last Duel","release_date": date(2021, 10, 15),"description": None}"""# Or access attributes directly:print(movie.title)# The Last Duelprint(movie.release_date)# date(2021, 10, 15)The IDE can help you understand types and auto-complete attributes:InstallInstall using:pip install drf-typedPython 3.8 or higher is required.Changelog0.3.0 (March 2023)Adds support for nested serializers from type annotations.0.2.0 (January 2022)Fixes setup.py for finding packages0.1.3 (October 2021)Fixes setup.py for finding packages0.1.1 (October 2021)Docs improvementsUpdates setup.py to include stubs package0.1.0 (October 2021)First releaseTestingTests are found in a simplified Django project in the/testsfolder. Install the project requirements and do./manage.py testto run them.LicenseSeeLicense.
Package: drftypegen
DRFTypeGenDRFTypeGenis a app to enable user to generate type information for various languages.Why?Nowadays we use statically-typed languages in many consumer apps for our APIs. Of course there are 'schemas' to describe your API but generating types are better. This will enable projects to generate relevant type file(s) for using in other projects.InstallationInstall from pip:pipinstalldrftypgenAdddrftypegenin yourINSTALLED_APP.UsageTypeScriptfromdrftypgen.compilersimportTypeScriptCompilertscompiler=TypeScriptCompiler()types_data=tscompiler.generate()Now you can save thetypes_datain file or serve in a view.Or, you can generate TypeScript File with this management command with optional filename with--fileoption:./manage.pygenTSTypesTODOSupport for WagtailSupport for Dart
Package: drf-typescript-generator
DRF Typescript generatorThis package allows you to generate typescript types / interfaces for Django REST framework
serializers, which can be then simply used in frontend applications.SetupInstall the package with your preferred dependency management tool:$poetryadddrf-typescript-generatorAdddrf_typescript_generatortoINSTALLED_APPSin your django settings.py file:INSTALLED_APPS=[...'drf_typescript_generator',...]UsageTo generate types run django management commandgenerate_typeswith the names of django apps
you want the script to look for serializers in:$pythonmanage.pygenerate_typesmy_appExample serializer found inmy_app:classMySerializer(serializers.Serializer):some_string=serializers.CharField(max_length=100)some_number=serializers.IntegerField()some_boolean=serializers.BooleanField()choice=serializers.ChoiceField(choices=[1,2,3],allow_null=True)multichoice=serializers.MultipleChoiceField(choices=[2,3,5])Generated typescript type:exporttypeMySerializer={choice:1|2|3|nullmultichoice:(2|3|5)[]someBoolean:booleansomeNumber:numbersomeString:string}The script looks for DRF routers in project urls.py file as well as urls.py files in given
apps and extracts serializers based on viewsets defined in those routers.ArgumentsThegenerate_typescommand supports following arguments:ArgumentValue typeDescriptionDefault value--format"type" | "interface"Whether to output typescript types or interfaces"type"--semicolonsbooleanIf the argument is present semicolons will be added in outputFalse--spacesintOutput indentation will use given number of spaces (mutually exclusive with--tabs). Spaces are used if neither--spacesnor--tabsargument is present.2--tabsintOutput indentation will use given number of tabs (mutually exclusive with--spaces)NoneFeaturesThe package currently supports following features that are correctly transformed to typescript syntax:Basic serializersModel serializersNested serializersMethod fields (typed with correct type if python type hints are used)Required / optional fieldsList fieldsChoice and multiple choice fields (results in composite typescript type)allow_blank, allow_null (results in composite typescript type)More features are planned to add later on:One to many and many to many fields correct typingDifferentiate between read / write only fields while generating type / interfaceIntegration with tools likedrf_yasgto allow downloading the
generated type from the documentation of the APIAccept custom mappings
Package: drf-ujson2
Django Rest Framework UJSON RendererDjango Rest Framework renderer usingujsonInstallationpip install drf_ujson2You can then set theUJSONRendererclass as your default renderer in yoursettings.pyREST_FRAMEWORK={'DEFAULT_RENDERER_CLASSES':('drf_ujson.renderers.UJSONRenderer',),...}BenchmarksThis is on average 2.3x faster than the default JSON Serializer.importtimeitsetup='''from proposals.models import Proposalfrom proposals.serializers import ProposalSerializerfrom rest_framework.renderers import JSONRendererfrom drf_ujson.renderers import UJSONRendererproposals = Proposal.objects.all()serialized = ProposalSerializer(proposals, many=True).data'''stdlib_test='''JSONRenderer().render(serialized)'''ujson_test='''UJSONRenderer().render(serialized)'''stdlib_result=timeit.repeat(stdlib_test,setup=setup,number=1,repeat=10)ujson_result=timeit.repeat(ujson_test,setup=setup,number=1,repeat=10)printstdlib_resultprintsum(stdlib_result)/10printujson_resultprintsum(ujson_result)/10# stdlib results[0.004502058029174805,0.004289865493774414,0.006896018981933594,0.0048198699951171875,0.004084110260009766,0.007154941558837891,0.003937959671020508,0.004029035568237305,0.004770040512084961,0.004539966583251953]# avg0.00490238666534# ujson results[0.0016620159149169922,0.001817941665649414,0.0015261173248291016,0.0040950775146484375,0.0021469593048095703,0.001798868179321289,0.001569986343383789,0.0019931793212890625,0.0017120838165283203,0.001814126968383789]# avg0.00201363563538
Package: drf-url-content-type-override
DRF URL Content Type OverrideDRF URL Content Type Override allows the content type of the request to be overriden with a url parameter.Why would I need this?Sometimes it makes sense to override the content type specified in the header. For example, some browser’s XHR, such as IE9, are unable to support CORS. Pollyfills like,jQuery-ajaxTransport-XDomainRequestor httpplease’soldiexdomain.jsplug-in get around this by using XDomainRequest, which supports CORS. The problem is XDomainRequest only sends a content type of text/plain in the header. This is problematic when POSTing form data. DRF URL Content Type Override let’s you specify a content type which will override the header value.Installpipinstalldrf-url-content-type-overrideAdd ‘DEFAULT_CONTENT_NEGOTIATION_CLASS’REST_FRAMEWORK={'DEFAULT_CONTENT_NEGOTIATION_CLASS':'drf_url_content_type_override.URLOverrideContentNegotiation',}UsageExample: Javascript on a different domain from the API.jquery.ajax({'url':'http://apidomain.com/api/1/contact?_content_type=application/x-www-form-urlencoded','type':'POST','data':{'name':'Chris'}})For more background seehttps://github.com/tomchristie/django-rest-framework/pull/1731
Package: drf-url-token-auth
drf-url-token-authSimple token based authentication using rest_framework.
Clients should authenticate by passing the token key in the "?token="
HTTP parameter. The token parametter can be configured.Quick startAdd "gitlab_webhook" to INSTALLED_APPS:INSTALLED_APPS = {
    ...
    "drf_url_token_auth"
}Modify rest framework settings:REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'drf_url_token_auth.authentication.UrlTokenAuthentication',
    )
}Optionally, configure url parameter name (default: token)DRF_URL_TOKEN_AUTH = {
    'PARAM_NAME': 'token'
}Dev notes:
build package: python setup.py sdist
install: pip install --user drf-url-token-auth/dist/drf-url-token-auth-01.tar.gz
Package: drf-user
Django REST Framework - UserUser APP for Django REST Framework with API Views.DRF Useris a Django app that overrides default user app to provide additional attributes and functionalities. The
current stable version includes:JWT Support (UsingSimple JWT)Mobile NumberSingle field for full nameREST API to registerREST API to loginMultiModelBackend: User can login using either of mobile, email or usernameREST API to login with OTP (Same API endpoint as for OTP Verification; Setis_login: truewhile sending JSON request)OTP Verification for mobile and emailAPI to register / login with OTP (no pre-registration required)API to set user's profile imageMail sending feature upon successful registrationSMS sending feature upon successful registrationChange PasswordUpdate ProfileGeneric Configuration based on settings.pySignal based mailsMail based activation (optional alternative for OTP based activation)Social Auth Endpoints(Login using fb/google) (WIP)DocumentationFor more information on installation and configuration see the documentation at:https://drf-user.readthedocs.io/ExampleTo get the example project running do:Clone this repo$gitclonehttps://github.com/101Loop/drf-user.gitGo toexamplefolder in newly created directorydrf-user$cddrf-user/exampleCreate and activate virtual environment.Install requirements(.venv)$pipinstall-rrequirements.txtRun testing server:(.venv)$pythonmanage.pyrunserverTake a look athttp://localhost:8000/swagger. Swagger will list all the APIs of drf-user.ContributingPlease file bugs and send pull requests to theGitHub RepositoryandIssue Tracker. SeeCONTRIBUTING.mdfor details.For help and support please reach out to us onSlack.
Package: drf-utils
# DRF UtilsUtilities for Django Rest Framework we use at :ployst, including:FieldsSerializer mixinsDecoratorsDRF Utils only supports Python 3. It has been tested with Python 3.4.## DevelopmentRun tests with:DJANGO_SETTINGS_MODULE=drfutils.tests.settings django-admin test## ReleasingCircle takes care of releasing to PyPI. Simply create a tag in the form
3.2.1 and circle will build and release as 3.2.1.To release locally, run./release.sh <version>
Package: drf-vue
使用方法1.安装pip install drf-vue2 . 在setting.py引入 vueINSTALLED_APPS=[....'vue']3.在viewset中使用fromvue.mixinsimportVueMixinclassxxViewSet(VueMixin):4.访问url获取示例代码
只需要在路由后面加上/vue即可查看示例代码
eg:http://127.0.0.1:8000/api/xx/xxservice/vue/