Saravanan666/pypi-org huggingface dataset:
Package: django-jux
Introductiondjango-jux/JUXD is an attempt to get JUnit-style XML output from the Django test runner.
It does a few notable things:Uses the test runner from thedjango.utils.unittestabstraction layer (Django >= 1.3 required)Does not redefine the behavior of the test suite’srunmethodDoes not redefine the behavior of the test runner’srun_suitemethodIncludes test suite run time as well as individual test run timesSupports all available unittest2 outcomes (success, failure, error, etc…)Works with builtin ElementTree to generate the XML outputThis job can be done using nose’s xunit plugin, but with the unittest
improvements in Python 2.7, my only reason for using nose was for the xunit
plugin itself. nose is a bit of a heavy hitter, but it’s a (really good)
generic test runner, not django specific. I wanted something a little more
targeted, and this is the result.The main motivator behind this was getting test output into Jenkins CI,
which works perfectly.InstallationInstall Django >=1.3 and set up a project.
Then, in your django project settings:# Tell Django to use the JUXD Test Suite Runner
TEST_RUNNER = 'juxd.JUXDTestSuiteRunner'
# Where to write the output
JUXD_FILENAME = '/path/to/junit.xml'ThanksThis module pulls inspiration from a lot of sources, and credit is due to all of them:junitxml plugin from the experimental plugin branch of unittest2xunit plugin for noseJenkins CIJUnit itselfMetaMetrics, Inc.
Package: django-jwt
# django-jwt
[![PyPI](https://img.shields.io/pypi/pyversions/django-jwt.svg)](https://pypi.python.org/pypi/django-jwt)
[![pypi Badge](https://img.shields.io/pypi/v/djang-jwt.svg)](https://pypi.python.org/pypi/django-jwt)
[![Travis](https://img.shields.io/travis/ah450/django-jwt.svg)](https://travis-ci.org/ah450/django-jwt)
[![Code Climate](https://codeclimate.com/github/ah450/django-jwt/badges/gpa.svg)](https://codeclimate.com/github/ah450/django-jwt)
[![Test Coverage](https://codeclimate.com/github/ah450/django-jwt/badges/coverage.svg)](https://codeclimate.com/github/ah450/django-jwt/coverage)
[![Issue Count](https://codeclimate.com/github/ah450/django-jwt/badges/issue_count.svg)](https://codeclimate.com/github/ah450/django-jwt)
[![license](https://img.shields.io/github/license/ah450/django-jwt.svg)](https://en.wikipedia.org/wiki/MIT_License)
[![GitHub issues](https://img.shields.io/github/issues/ah450/django-jwt.svg)](https://github.com/ah450/django-jwt/issues)
[![Gemnasium](https://img.shields.io/gemnasium/ah450/django-jwt.svg)]()A package that provides JWT authentication and related functionality for django and [DRF](https://django-rest-framework.org).# Installationpip install djang-jwtIf you require DRF support install the drf extras viapip install django-jwt[drf]# Settings
profile_klass should be set to your profile modeluser_reverse_profile_key should be the related name of profile on user modeljwt_realm should be set to your app name, user friendly versionemail_subject should be set to your a user friendly string that will appear in email subjectsFROM_EMAIL_ADDRESS should also be set.email_templates_dir should be set to a directory that contains activate_account.txt andreset_pass.txt
Package: django-jwt-expiringlinks
Django app that uses JWT to manage one-time and expiring links to protected URLs.Use CaseThe primary use case for this app is authenticating users on a per-
request basis, without having to log in to the site first.The canonical example of this would be unsubscribing from mailing lists -
you want to be able to identify the user, and process the request,
but requiring the user to log in first presents a barrier.Using JWT we can ‘pre-authenticate’ access to the URL.AssumptionsThis is not a general purpose link-generating app - it has some implicit
assumptions built-in:The link is being sent to a single userThe recipient is a known Django UserThe token generated will only authenticate the initial requestThe token willnotlog the user inThe link is not sensitive, and contains no sensitive dataImplementationThe underlying technology used is JWT - seejwt.iofor more
details on the specifics. The summary is that it can be used to generate a Base64 encoded and signed token based on an arbitrary JSON payload. The signature is used to ensure that the payload has not been tampered with. The payload itself is not encrypted, and can be decoded by anyone - hence ensuring that no sensitive data is included. (NB You can encrypt the token, but the base assumption is that you’re not sending sensitive data, you just want to ensure that the data you receive is the same data you sent.)The implementation within Django consists of two parts: adding the token to a URL as it leaves the app (e.g. in an email), and then validating the token when someone clicks on the link and returns to the site.In order to add the token, you need to create a new RequestToken object, and
then call theencodemethod on it. This will return the 3-part signed JWT
(header.payload.signature). You will need to initialise the token with the
recipientUser, and the target URL - to ensure that the token is only used
to access the intended endpoint...code ::python>>> from django_jwt.models import RequestToken
>>> # create a new RequestToken, and encode the contents
>>> token = RequestToken.objects.create_token(
...     user=User.objects.filter(...),
...     target_url=reverse('foobar')
... ).encode()
>>> token
1234567.qwertyuiop.zxcvbnm
>>>You now have a token that is bound to a taget URL, and an intended recipient.
If a user (any user - remmember, we arenotauthenticating the end user) clicks on this URL, they will hit the endpoint as an unauthenticated user. If the URL requires authentication, the request will fail, as the user is not yet authenticated.In order to use the JWT instead of full authentication, we must add a decorator to the view function to expand out the token, verify it (against tampering, and in line with the “not before time” and “expiration time” attributes of the token payload) and then set the user.The decorator does one more important task, once the function has run - it records the use of the token - extracting the source IP and user-agent from the request (for auditing purposes), and updating the tokenuse_countproperty, along with the response status_code - this enables fine-grained reporting on the use of the tokens.
Package: django-jwt-middleware
django_jwt_middlewaredjango_jwt_middlewareis a package used for authorize django request with JSON Web Tokens1. Installationpip3installdjango-jwt-middlewareor clonegitclonehttps://github.com/rizki4106/django_jwt_middleware.git2. Examplewith http cookieIf you store jwt key on cookie you can use@middleware.with_cookiedecoratorfromdjango_jwt_middlewareimportmiddlewarefromrest_framework.decoratorsimportapi_viewfromrest_framework.responseimportResponse@middleware.with_cookie(cookie_name="example-token",jwt_key="supersecretkey",algorithm="HS256")defhello_world(request):returnResponse(data={"message":"hello world"})@middleware.with_cookietakes 3 argumentsnametypedescriptioncookie_namestringname of cookie that store your jwt tokenjwt_keystringjsonwebtoken secret keyalgoritmstringalgorithm to decoded your jwt key default is HS256With http headersIf you store jwt key http headers you can use@middleware.with_headerdecoratorfromdjango_jwt_middlewareimportmiddlewarefromrest_framework.decoratorsimportapi_viewfromrest_framework.responseimportResponse@middleware.with_header(header_name="example-token",jwt_key="supersecretkey",algorithm="HS256")defhello_world(request):returnResponse(data={"message":"hello world"})@middleware.with_headertakes 3 argumentsnametypedescriptionheader_namestringname of header that store your jwt tokenjwt_keystringjsonwebtoken secret keyalgoritmstringalgorithm to decoded your jwt key default is HS2563. ResponseTypeDescriptionsuccessWill continue to request destinationfailedReturn http status code 403 with the message in it4. Discovered Problemsif you get error and it saidjwt has no attribute decodetry this commandpip3uninstallpyjwt
pip3installpyjwt
Package: django-k8s
django-k8sIntegration between Django and Kubernetes.CachingService discovery for Memcached. Admittedly this will work with any service
discovery that uses multiple A records for memcached servers. This allows the
memcached client to properly distribute keys amongst memcached servers. AWS
ElasticCache as well as Kubernetes and others are compatible with this scheme.If an error is received when trying to access a memcached server, DNS
resolution is performed again (refreshing server list). This allows memcached
servers to be added or removed without restarting the application.More information on this approach is provided below.https://cloud.google.com/solutions/deploying-memcached-on-kubernetes-engineGiven Memcached deployed to Kubernetes with the following command:helminstallstable/memcached--namemycache--setreplicaCount=3You could configure your application like this:CACHES={'default':{'BACKEND':'django_k8s.cache.backends.Memcached','HOST':environ.get('DJANGO_CACHE_HOST',None),},}MigrationsOne convenient way to handle Django migrations in Kubernetes is using a Job.
However Django applications expect the database to be available and migrated on
startup. Therefore some coordination is necessary. The application containers
should wait for the migration job to complete before starting up.This package provides a management command that polls the database to check for
two conditions:That the database server is reachable.That all migrations have been applied.It can optionally wait for both of these conditions to be true. An exit code of0indicates success. This management command could be part of your
entrypoint, ensuring no Django application is started until these conditions
are met.This technique is compatible with systems other than Kubernetes, the author has
used it with Docker Compose as well.$pythonmanage.pycheckmigrationsMigrationscomplete.
Package: django-k8s-health-check
Django Health CheckIf you use or like the project, clickStarandWatchto generate metrics and i evaluate project continuity.Install:pip install django-k8s-health-checkUsage Health only:In your urls:from django_k8s_health_check.views import HealthView
...

urlpatterns = [
    path('', views.HealthView.as_view()),
]Usage in kubernetes:If use health check in kubernetes, you need to add kubernetes ip/host to django allowed_hosts,
but is a bad practice, especially if there are multiple ip/hosts...
For this, i created a middleware to pass dynamic ip/hosts, using multiples validatorsRequest WayAdd the middleware to django middleware`s:MIDDLEWARE = [
    'django_k8s_health_check.middleware.HealthCheckMiddleware',
    ...
]Try this request:import requests
requests.get('your-url', headers={'X-Health': 'health-check'})Put this in your ymllivenessProbe:
    httpGet:
    path: /your-path
    httpHeaders:
    - name: X-Health
        value: health-check
    timeoutSeconds: 5Check de configuration section, and change for security reasons...Command Way (test database and cache only, this not guarantee application is running):Add this app to your installed apps:INSTALLED_APPS = [
    'django_k8s_health_check',
]Try to run this command:python manage.py health_checkPut this in your ymllivenessProbe:
    exec:
        command: ["python", "manage.py", "health_check"]
    timeoutSeconds: 5Configuration:HEALTH_CHECK = {
    # View
    'SERVICE_NAME': None,  # Used only in API
    'CHECK_DATABASE': True,
    'CHECK_CACHE': True,

    # Middleware (All bellow is used only in API)
    'HEADER_FIELD': 'X-Health',
    'HEADER_VALUE': 'health-check',
    'ALLOWED_PATHS': None,  # all others urls, use original ALLOWED_HOSTS. Ex: ['api/v1/health', '/health'], None allow all
    'ALLOWED_HOSTS': None,  # check request host is in a list, Ex: ['127.0.0.1', 'www.domain.com'], None allow all
}
Package: django-kafka-consumer
Django Kafka ConsumerPurposeDjango Kafka Consumeris an utility for consume events fromKafkaQuick startAddkafka_consumerto yourINSTALLED_APPSsetting like this:INSTALLED_APPS = [
    # ...
    'kafka_consumer',
]Runpython manage.py migrateto create thekafka_consumermodels.Add custom subscribers as classes derived fromkafka_consumer.subscribers.base.BaseSubscriberPrepare settings:KAFKA_HOSTS = ['kafka-host.com:9092']

KAFKA_CONSUMER_TOPICS = {
    'topic_key': {
        'topic': 'topic name',  # no spaces allowed!
        'group': 'topic group',
        'client': 'client ID',
        'subscribers': (
            'path.to.subscriber.Class',
        ),
        'message_processor': 'processor key',  # lookup in KAFKA_CONSUMERS_MESSAGE_PROCESSORS
        'wait': 0,  # optional, indicates how many seconds Kafka will wait to fillup buffer, None or ommited means wait forever
        'max_number_of_messages_in_batch': 200,
        'consumer_options': {  # Overrides options used to create KafkaConsumer
            'auto_offset_reset': 'latest',
        }
    },
}
KAFKA_CONSUMERS_MESSAGE_PROCESSORS = {
  'processor key': {
    'class': 'path.to.messageprocessor.Class',
    # Processors init arguments, e.g.
    'rsa_private_key_path': 'path/to/private/key'
  },
}

KAFKA_CONSUMER_SSL_SETTINGS = {
    'security_protocol': 'SSL',
    'ssl_cafile': '/path/to/file/ca.crt',
    'ssl_certfile': '/path/to/file/signed.request.crt',
    'ssl_keyfile': '/path/to/some/keyfile.key',
}To continuously consume events from kafka run:python manage.py consume --supervised --topic topic_keyLicenseThe Django Kafka Consumer package is licensed under theFreeBSD
License.
Package: django-kafka-event-log
Create an event from Django ORM object model, store the event into the database and also publish it into Kafka cluster.Quick startInstall the package:pip install django-kafka-event-logIn your project’ssettings.py, include the app and add credentials for Kafka:INSTALLED_APPS = [
    ...
    'events',
]

KAFKA_GROUP = 'KAFKA_GROUP'
KAFKA_BOOTSTRAP_SERVERS = 'KAFKA_BOOTSTRAP_SERVERS'
KAFKA_SECURITY_PROTOCOL = 'KAFKA_SECURITY_PROTOCOL'
KAFKA_SASL_MECHANISMS = 'KAFKA_SASL_MECHANISMS'
KAFKA_SASL_USERNAME = 'KAFKA_SASL_USERNAME'
KAFKA_SASL_PASSWORD = 'KAFKA_SASL_PASSWORD'Note: the credential should be read from environment variables.This application has only 1 interface; it isPublishKafkaEventUtil. Givenmyappis where the model object locates,MyModelSerializeris the data presenter, we can call the Util like this:from events.utils import PublishKafkaEventUtil
from myapp.serializers.mymodel_serializer import MyModelSerializer

PublishKafkaEventUtil.call(
    event_name='Created',
    model_object=model_obj,
    serializer=ModelSerializer,
    metadata={'purpose': 'testing'},
)
Package: django-kafka-streamer
django-kafka-streamer is a Django application and library for streaming data to
Apache Kafka.Features:Setup signal handlers to ORM models to transparently send create/update/delete
events to KafkaHandle database object relationsCelery task to stream large amount of data in backgroundLinks:GitHub:https://github.com/lostclus/django-kafka-streamer/PyPI:https://pypi.org/project/django-kafka-streamer/
Package: django-kakebo
Django KakeboA simple site made with django and exploiting the kakebo method.[IT]
Il Kakebo (giapponese: 家計簿) è un metodo di risparmio e di gestione finanziaria della famiglia nato e sviluppato in Giappone
Una prima copia di un kakebo è stato pubblicato dalla giornalista Motoko Hani (nel 1904).Letteralmente traducibile come "registro di casa"; ve ne sono di diversi tipi, che modificano la struttura dello stesso, ma l'idea di base è la stessa.All'inizio del mese: il kakeibo annota le entrate e le spese necessarie per il mese iniziale e decide una sorta di obiettivo di risparmio, aggiungendo eventuli spunti o propositi.
Su base giornaliera: l'utente registra le proprie spese, che vengono sommate alla fine della settimana e alla fine del mese.Alla fine del mese: l'utente redige un bilancio di fine mese con eventuali appunti e/o verifica del motivo del non raggiungimento dell'obiettivo imposto all'inizio del mese.Oltre alle spese e alle entrate, nel Kakebo si scrivono anche: pensieri e osservazioni, con l'obiettivo di aumentare la consapevolezza dei propri consumi.In questo progetto viene elaborato un sito attraverso python3 (con l'uso del framework django) che riporta lo stesso spirito del Kakebo tradizionale, dando all'utente un'interfaccia pulita e utilizzabile da subito, con la semplice installazione del pacchetto/app.Nel pacchetto è presente:'Home Page' (disattivabile dai settings)app 'user': che permette la gestione dell'utenza (login e registrazione // con eventuale reCAPTCHA)Per i dettagli, consigliamo di leggere la documentazione[EN]
The Kakebo (Japanese: 家計簿) is a method of household savings and financial management method originated and developed in Japan.
An early copy of a kakebo was published by journalist Motoko Hani (in 1904).Literally translatable as "household ledger"; there are different types where the structure changes, but the basic idea is the same.At the beginning of the month: the user notes the income and expenses needed for the initial month and decides on some sort of savings goal, adding any cues or resolutions.
On a daily basis: the user records his or her expenses, which are added up at the end of the week and at the end of the month.At the end of the month: the user draws up an end-of-month balance sheet with any notes and/or verification of why the goal imposed at the beginning of the month was not met.In addition to expenses and income, also written in the Kakebo are: thoughts and observations, with the goal of increasing awareness of one's consumption.In this project, a site is developed through python3 (with the use of the django framework) that brings back the same spirit as the traditional Kakebo, giving the user a clean and usable interface right out of the box, with the simple installation of the package/app.Included in the package is:'Home Page' (can be deactivated from settings's project)'user' app: which allows user management (login and registration // with reCAPTCHA)For details, we recommend reading the documentation
Package: django-kamasutra
Backwards incompatible changes made in version 0.2.2COMBINE_STRINGis now used to build the template list when usingPositionContent.renderorrender_contenttemplate tag.Before:/positions/my_position/<app>__<model>.htmlNew:/positions/my_position/<app><combine_string><model>.htmlInstallationUsing PIP:pip install django-kamasutraor download the appherepython setup.py installAddpositionsto your settingsINSTALLED_APPS:INSTALLED_APPS = (
    ...
    'positions',
    ...
)Addpositionsto your URLS:import positions.urls

urlpatterns += patterns('',
    url(r'^positions/', include(positions.urls)),
)Run syncdb:>>> ./manage.py syncdbGetting StartedCreating your first positionThe minimum required arguments to create a positions is aname, which is aSlugField.from positions.models import Position

position = Position.objects.create(name="MyPosition")Add something to your PositionThe position manager has aadd_objectmethod that takes, at minimum, 2 arguments,positionandobjpositionshould be apositions.Positioninstanceobjcan be any model instancefrom myapp.models import MyApp

obj = MyApp.objects.get_latest()

Position.objects.add_object(position=position, obj=obj)NoteThePositionmodel can define which types of objects that can be added.
Therefore when adding objects to a position, make sure the content types
is allowed by thePositioninstance.Retrieve your position contentThe position manager has aget_contentmethod that takes at least 1 argument,position.positionshould be apositions.Positioninstanceposition = Position.objects.get(name="MyPosition")

content = Position.objects.get_content(position=position)Retrieve your position content via templatetag{% get_position_content position as content %}get_position_contentexpects [position] [as] [varname]positioncan be a positions.Position instance or a name of a positionPosition {{ position }} has the following content:<br/>
<ul>
{% for obj in content %}
    <li>{{ obj }}</li>
{% endfor %}
</ul>NoteBy default the object instance will be returned, although returning the positions.PositionContent instance, which holds the generic relation between position and the object, is also possible{% get_position_content position as content as_content_type=False %}
Package: djangokantanlog
Kantan log is a simple Django helper app.
This app supports logging to Django Model’s created_by, updated_by. At http requests interception, too.Installationshell>pipinstalldjangokantanlogUsageInstalled apps:INSTALLED_APPS=[...'kantanlog.apps.KantanlogConfig',]Middleware:MIDDLEWARE=[...'kantanlog.middlewares.KantanlogMiddleware',]SettingsKLOG_TARGET_APP_LABELSDefault:()Target apps, settings as app-label:KLOG_TARGET_APP_LABELS=(...'myapp',)KLOG_BACKENDDefault:kantanlog.backends.KantanlogDefaultBackendAs interface, getting user.e.g.# at settings.pyKLOG_BACKEND='dotted.path.to.MyappBackend'...# -*- coding: utf8 -*-fromloggingimportgetLoggerfromkantanlog.backendsimportKantanlogDefaultBackendfromrest_framework_jwt.authenticationimportJSONWebTokenAuthenticationfromrest_framework_jwt.settingsimportapi_settingslogger=getLogger(__name__)payload_handler=api_settings.JWT_PAYLOAD_HANDLERencode_handler=api_settings.JWT_ENCODE_HANDLERclassMyappBackend(KantanlogDefaultBackend):def__init__(self):super().__init__()defget_user(self,request):user=super().get_user(request)ifuser.is_authenticated:returnuserja=JSONWebTokenAuthentication()ifja.get_jwt_value(request):user,jwt=ja.authenticate(request)returnuserreturnuser
Package: djangokantanoidc
KAOC behaves like OpenID Connect client as Django helper application.
KANTAN means “naive” or, “very simple”.Installationshell>pipinstalldjangokantanoidcUsageInstalled apps:INSTALLED_APPS=(...'kantanoidc.apps.KantanoidcConfig',...)URLconfs for Django project:urlpatterns=[...path('kantanoidc/',include('kantanoidc.urls')),]SettingsKAOC_SERVERDefault:''OpenID Connect Authorization Server URL.KAOC_CLIENT_IDDefault:''Client ID.KAOC_CLIENT_SECRETDefault:''Client secret.KAOC_EXTENDER (Optional)Default:NoneExtend a basic authentication flow.
Package: django-kazoo-locks
Django Kazoo LocksAboutDjango Kazoo
Locksprovides a
utils for using Zookeeper locks through kazoo inDjangoapplications.Installpipinstalldjango-kazoo-locksUsageRegister app inINSTALLED_APPSand define following settings:ZOOKEEPER_APP_NAMESPACE='some-unique-app-name'ZOOKEEPER_HOSTS=['10.32.96.201:2181']Usage example:lock=Lock('my-lock-{object_id}')withlock(object_id=123):print('so alone')try:withlock(object_id=123,timeout=9):print('so alone')exceptLockTimeout:print('unable to lock after waiting for 9s')try:withlock(object_id=123,blocking=False):print('so alone')exceptLocked:print('unable to lock immediately')ExtrasMigrationsThis package defines its version of the data migration command -migrate_with_kazoo. Thanks to this command it is possible to quickly
and correctly perform data migration process in applications running
simultaneously on many different hosts and using the same database. The
command can be used independently or as a base class for the migrate
command in your own application. The__init__method of the defined
class accepts the optionallockargument, which allows you to define
your ownkazoo_locks.locks.Lockobject to protect the critical section
of the migration.LicenseThe Django Kazoo Locks package is licensed under theFreeBSD
License.