Saravanan666/pypi-org huggingface dataset:
Package: django-apikey
Key authentication for django. Can be used with django-piston easily.Based onhttps://github.com/scoursen/django-apikey.Installationpip install django-apikeyConfigurationAdd ‘apikey’ to your settings.py:INSTALLED_APPS = (
...
'apikey',
....
)A QuestionWhat is a Token and a Key? and which are the differences between them?TokenA Token is generated with:Token.objects.create(user)and it can be used to authenticate requests with Django-Piston as long as it remain active, which is configured in settings.py:TOKEN_VALID_SECONDS = 3600The header used to send the token is configured in settings.py with:TOKEN_AUTH_HEADER = 'X-Auth-Token'To ask for a token in a resource handler use it like this:from apikey.auth import TokenAuthentication
from piston.handler import BaseHandler
from piston.resource import Resource
from app.models import Item

class ItemHandler(BaseHandler):
    allowed_methods = ('GET', )
    fields = ('name', 'id')
    model = Item

    def read(self, request):
        return Item.objects.all()

handler = Resource(
    handler=ItemHandler, authentication=TokenAuthentication())The token remains active TOKEN_VALID_SECONDS after each request, and it should be created in a request authenticated with the username/email and password/key, or Basic, Digest.ApiKeyApiKey is basically a key used to authenticate the requests that replace an email/username and password in all the API request.You can change the authorization header by setting the APIKEY_AUTHORIZATION_HEADER in settings.py:APIKEY_AUTHORIZATION_HEADER = 'App-Authorization'To add api authentication with piston write this in your handlers:from apikey.auth import ApiKeyAuthentication
from piston.handler import BaseHandler
from piston.resource import Resource
from app.models import Item

class ItemHandler(BaseHandler):
    allowed_methods = ('GET', )
    fields = ('name', 'id')
    model = Item

    def read(self, request):
        return Item.objects.all()

handler = Resource(
    handler=ItemHandler, authentication=ApiKeyAuthentication())ThanksThis project is base on the one of Steve Coursenhttps://github.com/scoursen/django-apikeybut with several simplifications, and adds.LicenseThis software is licensed  under the New BSD License.
Package: django-api-key
Per URL api-key control for DjangoInstallationTo get the latest stable release from PyPipipinstalldjango-api-keyTo get the latest commit from GitHubpipinstall-egit+git://github.com/dryice/django-api-key.git#egg=django_api_keyAdddjango_api_keyto yourINSTALLED_APPSINSTALLED_APPS=(...,'django_api_key',)Migrate your database./manage.pymigratedjango_api_keyAdd thedjango_api_keyURLs to yourMIDDLEWAREMIDDLEWARE=[...,'django_api_key.middleware.APIKeyMiddleware',](Optional) adjust the URLs that you don’t want api_key check. Default is:IGNORE_API_KEY_CHECK_FOR=["/admin/.*","/docs/.*"]Visit /admin/django_api_key/ipaccess/ and add rules accordinglyUsageTODO:ContributeIf you want to contribute to this project, please perform the following steps# Fork this repository
# Clone your forkmkvirtualenv-ppython3.7django-api-keymakedevelopgitco-bfeature_branchmaster# Implement your feature and testsgitadd.&&gitcommitgitpush-uoriginfeature_branch# Send us a pull request for your feature branchIn order to run the tests, simply executetox. This will install two new
environments (for Django 2.0 and Django 2.1) and run the tests against both
environments.
Package: django-api-key-server
Secure API Signature MechanismInternal used for creating signed url for server installed api-key-serverInstallpipinstallapi-key-clientExample:sign_request_1(url, api_key, api_secret)recommand>>>fromapi_key_client.utilsimportsign_request_1>>>url='https://api.example.co/sample/something-important/'>>>sign_request_1(url,'SOME-TEST','some-key-xxxxxx')'https://api.example.co/sample/something-important/?api_key=SOME-TEST&timestamp=20220209144716&sign=7f210048e1e972d968186f8a35a86f9a'sign_request_1(url, api_secret)place api_key in url# sign.py>>>fromapi_key.utilsimportsign_request,sign_request_1>>>url='https://example.site.com/sample/secret-info/?api_key=xxx&xxxxx=true&id=163'>>>url=sign_request(url,'your_secret')>Note:pleasechecksystemdatetothecorrecttimezone,OtherwisethetimeoutcheckingcouldbeinvalidFordockercontainer(alpine)```dockerfileRUNapkadd--updattzdataENVTZ=Pacific/Auckland
Package: django-api-middleware
La aplicacion utiliza la libreriaPYJWTpara agregar un token a cada request y a cada response mediante un middleware personalizado.InstalacionAgregar a la lista de aplicaciones.INSTALLED_APPS = [
    ...
    'authorized'
]Agregar el middlewareal iniciode la lista.MIDDLEWARE = [
    'authorized.middleware.APIAuthRequestMiddleware',
    ...
]Agregar las variables*RequeridoEn el archivosettings.pyagregar las variables.APP_NAME = 'Awesome App'
IGNORED_PATHS = []En el archivodocker-compose.ymlservice:
...
environment:
    - APP_KEY=secretAplicar las migraciones del middleware.$ python manage.py migrate authorizedUsoRequestsPara que el middleware funcione se necesita agregar el header'Application-Token':tokenPara evitar hacerlo se creo una “mascara” de la libreriapython requestsque agrega el token automaticamente, sin alterar su funcionalidad.
Importar el modulo.from authorized import api_requesthacer los request de forma normal, ie.api_request.get('url', params)Todos los metodos de python requests estan disponibles en el modulo api_request:getpostputpatchdeleteoptionsheadPara peticiones a aplicaciones externas se debe especificar en cada metodo el parametrois_external=True, por defecto el valor esFalse, esto previene que el middleware evalue que la respuesta provenga de una fuente confiable.api_request.get('https://jsonplaceholder.typicode.com/posts/1', is_external=True)Informacion adicional sobre python requests consultarAquiCorrer TestsPara ejecutar los tests de la aplicacionauthorized, ejecutar el comando.python manage.py test authorized
Package: django-api-permission
Django-API-Permission1. IntroA Django api permission manager that helps you custom api url in regular expression and control access.2. Quick Start2.1 Installpip install django-api-permission2.2 add to INSTALLED_APPS and MIDDLEWAREINSTALLED_APPS=[...'api_permission',...]MIDDLEWARE=['django.contrib.sessions.middleware.SessionMiddleware','django.contrib.auth.middleware.AuthenticationMiddleware',...'api_permission.middleware.APIPermCheckMiddleware',]2.3 migrate./manage.py migrate api_permission2.4 settingssetAPI_PERMISSION_CONFin your settings.py as a dict.API_PERMISSION_CONF={'API_PREFIX':['api/topic/'],# default is /'PERMISSION_DENIED_CODE':1,# default is 1'AUTHORIZATION_HEADER':'HTTP_AUTHORIZATION',# default is HTTP_AUTHORIZATION'ADMIN_SITE_PATH':'/admin/',# default is /admin/'TOKEN_EXPIRE':15,# unit is days, default is None, which won't check token expire.}You can customAPI_PREFIXas a str like'/'or list like['api/account', 'api/topic'].** When you setTOKEN_EXPIRE, you need add below in yourREST_FRAMEWORKsettings. **REST_FRAMEWORK={'DEFAULT_AUTHENTICATION_CLASSES':(...'api_permission.authentication.ExpireTokenAuthentication',),}3. Demo3.1 list3.2 edit3.3 result
Package: django-api-playground
A django app that creates api explorer for RESTful APIs.Works with any RESTful API. For example, you can create api explorer for your tastypie based API with this app.Demo:http://api-playground-demo.hipo.bizInstructionsTo get this application up and running, please follow the steps below:Install from pip:pip install django-api-playgroundOr from source:pip install git+git://github.com/Hipo/Django-API-Playground.gitAdd to installed apps:INSTALLED_APPS =(
    # ...

    'apiplayground',
)Installation is completed. You can define the API schema now.Firs step, Create an url:# urls.py

from api.playgrounds import ExampleAPIPlayground

urlpatterns = patterns('',
    (r'api-explorer/', include(ExampleAPIPlayground().urls)),
)Second step, Define a subclass for your API:# api/playgrounds.py

from apiplayground import APIPlayground

class ExampleAPIPlayground(APIPlayground):

    schema = {
        "title": "API Playground",
        "base_url": "http://localhost/api/",
        "resources": [
            {
                "name": "/feedbacks",
                "description": "This resource allows you to manage feedbacks.",
                "endpoints": [
                    {
                        "method": "GET",
                        "url": "/api/feedbacks/{feedback-id}",
                        "description": "Returns a specific feedback item"
                    },
                    {
                        "method": "POST",
                        "url": "/api/feedbacks/",
                        "description": "Creates new feedback item",
                        "parameters": [{
                            "name": "title",
                            "type": "string"
                        },
                        {
                            "name": "resource",
                            "type": "string"
                        },
                        {
                           "name": "description",
                           "type": "string"
                        }]
                    }
                ]
            },
        ]
    }That’s all. More detailed documentation will be coming soon.
Package: django-apirouter
Django APIRouter (in progress)Django API router component.Inspired byFastAPIandDjango Rest Framework.Documentation:https://django-apirouter.readthedocs.io/InstallingInstall usingpip:pipinstalldjango-apirouterQuick Exampleproject/urls.pyfromapirouterimportAPIRouter,Response,Requestrouter=APIRouter()@router.route("/")defindex(request:Request):returnResponse("Hello, Django APIRouter!")urlpatterns=router.urlsTODO:DocumentationOpenAPI support (Swagger, ReDoc)Pydantic supportAsync views support (with Django 3.1)etc.
Package: django-api-sbif
API SBIF .v3VERSION 3Información obtenida de la API de la Superintendencia de Bancos e Instituciones Financieras de Chilehttps://api.sbif.cl/Pypihttps://pypi.python.org/pypi/django-api-sbifInstallationinstalldjango-api-sbifusingpippip install django-api-sbifaddapisbiftoINSTALLED_APPSsettings.py# …INSTALLED_APPS =[
…
‘apisbif’,
]# …
Package: django-apistat
Прочти меняО проектеApiStat - модуль генерирует json ответ на основе запроса из БД.
Хорошо пододйет для выдачи каких либо справочников или отчетов на основе sql зфпроса с параметрамиВозможностиполучить результат sql запроса к указанной БД в JSON форматезадать параметры запроса через urlТребуетсяDJANGO
DJANGO_REST_FRAMEWORKУстановкаpip install django-apistatв setting.py добавляем наш модуль а так же необходимый rest_framework:INSTALLED_APPS = […‘rest_framework’,‘apistat’…]Добавляем в urls.py (путь ‘stat/’ может быть любой, на Ваше усмотрение)from django.urls import path, includeurlpatterns = […path(‘stat/’, include(‘apistat.urls’, namespace=’apistat’)),…]Запускаем миграции py -3 manage.py nigrateЗаходим в админку и в таблицу Api stat sprs добавляем необходимые запросыПример сhttp://127.0.0.1/http://127.0.0.1:8000/spr/list/- получаем список отчетовhttp://127.0.0.1:8000/spr/report/1- получаем данные отчета с идентификатором 1http://127.0.0.1:8000/spr/report/1?start=5- получаем данные отчета с идентификатором 1 с параметром start=5Планыпостраничное получение данныхвыдача структуры полей, для заголовки отчеты (json в отдельном поле)выдача параметров отчета (json в отдельном поле, имя параметра и тип)История измененийMVP22.08.2021 Первая версия пакетаЛицензияBSDBSD 3-Clause License
Package: django-apitokens
django-apitokensGenerate tokens compatible with Django Restframework (drf) from your Django Admin view:Create new tokens at will (after being generated, they no longer can be reversed, since only a digest is stored in the database).Add expirity dates (supports time and date)Remove tokens when you no longer need them.My Token viewAdd token viewInstallInstall the python package:pip install django-apitokensAddapitokensto your Django installed apps:# In your settings.pyINSTALLED_APPS=[...'apitokens',]Ensure you are usingknoxTokenAuthenticationclass:# In your settings.pyREST_FRAMEWORK={...,'DEFAULT_AUTHENTICATION_CLASSES':('knox.auth.TokenAuthentication',...,),...,}You are set to use tokens generated through this app as a way to login with the DRF framework.ContributingTo contribute code to this app, ensure you're following thecommunity guidelines
Package: django-api-toolkit
ContentsInstalationGet startedUsageStructureSettingsModelsAdvancedRestModel overwritesRestModel.RestRestModel._rest_serializerRestModel._rest_querysetRestModel._rest_endpointFEATURESCHANGELOGInstalationpipinstalldjango-api-toolkitGet startedIn the first you need initialize your projectproject_init<pathtoproject>For existing projects you should to generateenvfileenv_generator<pathtoproject>This script generate base variables that needed to run project. You can also add youself variables in env file
You should also change yourmanage.py. AddAPIManagerto your file. e.q.#!/usr/bin/env pythonimportsysfromapi_tools.utilsimportAPIManagerif__name__=="__main__":er=APIManager(__file__,'cfg.settings')# path to user project settingser.set_app_dir('apps')# directory for user project applicationser.apply()# apply settingsfromdjango.core.managementimportexecute_from_command_lineexecute_from_command_line(sys.argv)UsageStructure├──apps# dir for your apps├──cfg# dir for diferent project configurations│├──settings.py# user project settings│└──wsgi.py└──manage.pySettingsCOMMON_APPS- django common applicationsTHIRD_PARTY_APPS- third party applicationsEXTRA_APPS- applications should be insted before common appsPROJECT_APPS- your project applicationsYou also can overwrite other standard django settings keys and add yourself variablesModelsAll project models should be inherited of RestModel(this standart django abstract model and you can use all capabilities
of this)fromapi_tools.modelsimportRestModelclassMyModel(RestModel):...AdvancedRestModelhave subclassRest. This subclass have properties for control your rest models. RestModel also have
classmethods for these controls.RestModel overwritesRestModel.Restqueryset:defines queryset aslambdaofmodel.objectsfields:list of allowed fields of modelname:name of viewsetroute:route of endpointRestModel._rest_serializerDefines serializer for viewset of modelRestModel._rest_querysetDefines queryset for viewsetRestModel._rest_endpointSet endpoint for your modelFEATURESCHANGELOG
Package: django-api-view
Django basic api view and api response.DocumentationThe full documentation is athttps://django_api_view.readthedocs.io.QuickstartInstall Django api view. In the command line:pip install django_api_viewConfigurationAdd‘django_api_view’it to yourINSTALLED_APPS:INSTALLED_APPS = (
    ...
    'django_api_view',
    ...
)Simple usageRead full documentation for full featureshttps://django_api_view.readthedocs.io.Api ViewApiView will automatically parse post data.It accepts'application/json','application/x-www-form-urlencoded', or'multipart/form-data'For example:from django_api_view.api_view import ApiView

class BasicApiView(ApiView):

    def get(self, request):
        # For get method use 'GET' to get parameters
        email = request.GET.get('email')

    def post(self, request):
        # For post method use 'data' to get parameters
        email = request.data.get('email')Api ResponseApi response retuns json response.Basic example:from django_api_view.api_response import ApiResponse

def get(request):
    # 'data' parameter is optional
    return ApiResponse().success(data={})Version 0.1 (2017-07-25)Initial release.
Package: djangoapiviewdoc
djangoapiviewdoc根据装饰器生成api文档版本<=1.1.0# settings.pyfromapiview_doc.decoratorimportApiDocAPIDOC_DECORATOR=ApiDoc()# views.pyfromproject_name.settingsimportAPIDOC_DECORATORfromrest_framework.genericsimportGenericAPIViewclassPersonLoginAPIView(GenericAPIView):"""@author:    JiChao_Song@desc:      用户名、密码登录@date:      2021/11/29 17:09"""@APIDOC_DECORATOR.start@APIDOC_DECORATOR.ApiTag(value='user',desc='用户管理')@APIDOC_DECORATOR.ApiOperation(method='POST',path='/user/login',summary='用户登录')@APIDOC_DECORATOR.ApiParams(value='username',require=True,type='string',desc='用户名')@APIDOC_DECORATOR.ApiParams(value='password',require=True,type='string',desc='密码')defpost(self,request,*args,**kwargs):pass# url.pyfromapiview_doc.decoratorimportapi_docfromviewsimportPersonLoginAPIViewdefdocs(request):context=api_doc()returnrender(request,'apiview_doc/docs/index.html',context)urlpatterns=[path('login',PersonLoginAPIView.as_view()),path('docs',docs),]启动项目访问 “/docs”版本 >= 1.1.0# settings.pyfromapiview_doc.decoratorimportApiDocfromapiview_doc.openapiimportApiImplicitParam,ApiTag,ApiParameters,ApiOperation,ApiDataType,ApiParamType# views.pyfromrest_framework.genericsimportGenericAPIViewclassPersonLoginAPIView(GenericAPIView):"""@author:    JiChao_Song@desc:      用户名、密码登录@date:      2021/11/29 17:09"""@ApiTag(name='user',description='用户管理')@ApiOperation(method='POST',path='user/login',summary='用户登录')@ApiParameters(params=[ApiImplicitParam(description='用户名',name='username',required=True,paramType=ApiParamType.Body,dataType=ApiDataType.String),ApiImplicitParam(description='密码',name='password',required=True,paramType=ApiParamType.Body,dataType=ApiDataType.String),])defpost(self,request,*args,**kwargs):pass# url.pyfromviewsimportPersonLoginAPIViewfromapiview_doc.openapiimportOpenApi,api_info_listopenapi=OpenApi(paths=api_info_list())defget_openapi_docs_url(request):context=openapi.__dict__returnrender(request,'apiview_doc/openapi/index.html',context)urlpatterns=[path('login',PersonLoginAPIView.as_view()),path('redocs',get_openapi_docs_url),]启动项目访问 “/docs”
Package: django-apollo
AboutThe best way to prove an idea is to test it. Whether you want to test a new
feature in an existing application or prove an entirely new concept,
django-apollo helps you quickly add a landing page to your existing Django
site or create a new landing page based MVP site.UsageInstallationpip installdjango-apolloDependenciesIn addition to Django, the following python packages are required by this
package, and should be installed automatically bypip:django-ckeditor>= 4.4django-widget-tweaks>= 1.3Bootstrap 3 and jQuery are also required, but because there are so many ways to
add these to your project, they have not been made dependencies.SettingsAdd ‘apollo’ to yourINSTALLED_APPSCreate a list ofLANDING_PAGE_TEMPLATESthat will be used in your landing
pages. You must create at least one. Typically these will be in your site’s
root template directory.Admin ConfigurationConfigure yourSiteas appropriate.Create aPageincluding key and landing template.AddQuestionif needed.TemplatesThe templates include a flexible layout scheme that allows you to define named
blocks in your template file and type the content into thePageusing the
Django Admin.Here is an example landing page template that you can include in your Django Site:{% extends "base.html" %}

{% block content %}

    <div class="jumbotron">
        <div class="container">
            {{ content.main|safe }}
        </div>
    </div>

    {% include "apollo/buttons.html" %}
{% endblock %}This assumes that you have abase.htmltemplate that defines your overall
site layout and contains a content block.Save this to a filelanding1.htmlin your templates directory and then
configureLANDING_PAGE_TEMPLATES:LANDING_PAGE_TEMPLATES = (
    ('landing1.html', 'Landing Page One'),
)Variable Page ContentNote thecontent.maintemplate variable in the above example. Any Page
Content that you add in the Django Admin for thePagewill be added with
the key into this content dictionary. You can arrange these in your landing
page templates however you’d like, then easily update them in the admin site.In addition to regular variables, you can expose a list by ending your keys
with an index. For example use keys in the format ideas[0], ideas[1]… to
create a template that iterates over a variablecontent.ideas:{% for i in content.ideas %}
  ...
{% endfor %}
Package: django-app-base
django-app-base部门权限的作用，部门就是类似人员组，只需要将权限设置在人员组上，并不需要有具体的员工，只要有员工进来就可以获得相应的角色pip install /d/xunull-repository/xunull-github/public/django-user-role/dist/django_user_role-0.0.1.tar.gzpip install /d/xunull-repository/xunull-github/public/simple-common/dist/simple_common-0.0.1.tar.gzpython -m django test --settings=tests.settingspython setup.py sdist bdist_wheel
Package: django-app-bootstrap
# DJANGO APP BOOTSTRAPA simple django application that can speedup your development by generating code from models.Specify a different application structure to process by entering the full path to the folder in settings.py variable BOOTSTRAP_FOLDERQuick startpip install django-app-bootstrappAdd “django_app_bootstrap” to your INSTALLED_APPS setting like this:INSTALLED_APPS = [
    ...
    'django_app_bootstrap',
]Runpython manage.py bootstrap_appto start the wizard.
Package: django-appchance-sections
Appchance SectionsThis application will allow you to implement flexible sections. It is not an out of the box mechanism and its
implementation requires a bit of effort, but in return you get a solution that you can relatively easily adapt
to your needs.Including:the possibility of generic and dynamic content,convenient operation in the admin panel.This solution was designed for the Django Rest Framework.Not so quick startThe applicationappchance_sectionscontains only abstract models so you nead add new applicationpython manage.py startapp mysectionsadd created app to settings.INSTALLED_APPSINSTALLED_APPS = [
        ...
        'mysections',
    ]and define real models.1. Real Section ModelIn mysections.models.py file defineSectionmodel. If you need you can add additional fields, but the default fields
provide basic functionality.from appchance_sections.models import SectionAbstract
    from django.db import models
    
    class Section(SectionAbstract):
        passIn your Django project settings file defineSectionmodel.SECTION_MODEL = "mysections.Section"In mysections.admin.py useSectionAdminMixinwhich binds - most importantly - the modified form.from appchance_sections.admin import SectionAdminMixin
    from django.contrib import admin
    from mysections.models import Section

    @admin.register(Section)
    class SectionAdmin(SectionAdminMixin):
        passIn mysections.apps.pyit is very important that you do not forget to importappchance_sections.receiversin the configfrom django.apps import AppConfig
    
    class SectionsConfig(AppConfig):
        name = "mysections"
    
        def ready(self):
            from appchance_sections import receivers  # noqa F405The last thing you have to do is add urls to urls.pyfrom django.contrib import admin
    from django.urls import include, path
    
    urlpatterns = [
        path("admin/", admin.site.urls),
        path("", include("appchance_sections.urls", namespace="sections")),
    ]2. Bind contentThen we need some content that we could present in sections. We can add two types of content:genericdynamicTo see how to define dynamic content and how to make this content possible to attach to the section.Read more in/docs/DYNAMIC_CONTENT.mdand/docs/GENERIC_CONTENT.md.Sections were originally designed such that the section content is geted asynchronously by separate requests from the api. However, it is possible to get the content of the sections together with the list of sections.How to? Read in/docs/IMMEDIATE_CONTENT.md