Saravanan666/pypi-org huggingface dataset:
Package: djp-py-helpers
djp_py_helpersThis package exposes some basic helper functions for
configuring the built-in python logging package.GithubTable of ContentsDependenciesBuildingPublishingInstallationUsageProject StructureTestingContributingLicenseDependenciesPoetry- Great tool for managing dependenciesBuildingPublishingInstallationPoetryRefer to installation docs forPoetry.Navigate to your project you want to use this library in:cd <path/to/project>Create a Python virtual environment to work in with this command:python -m venv ./venvOn Mac & Linux:
Runsource ./venv/bin/activateOn Windows
Run./venv/scripts/activate.ps1Download the library from Github with this command:pip install git+https://github.com/Djpleasant/djp-py-logger.git#egg=djp_py_helpersIn your requirements.txt file, adding this line will install the djp_py_helpers package after runningpip install -r requirements.txt:djp_py_helpers @ git+https://github.com/Djpleasant/djp-py-logger.gitUsageBasic setup""" example script to use the most basic helper function """

import logging
from djp_py_helpers.helpers import configure_logger

# This will not do anything
logging.info('hello world')

# The logging library has been configured now
configure_logger()

# This will output `hello world` in our default logging format
logging.info('hello world')Project StructureTDBTestingFor unit testing:poetry run pytestFor coverage testing:poetry run pytest --cov-report term-missing --cov=./ testsFor coverage testing with report in html:poetry run pytest --cov-report term-missing --cov-report html --cov=./ testsContributingTBDLicenseHelper functions for the built-in python logging package.Copyright (C) 2023  Dawson Pleasantdawsonpleasant@outlook.com(https://https://github.com/Djpleasant)This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.You should have received a copy of the GNU General Public License
along with this program.  If not, seehttp://www.gnu.org/licenses/.
Package: dj-pq
pqwrapper for django.Installationpipinstalldj-pqConfigurationAdddj_pqto yourINSTALLED_APPS:INSTALLED_APPS+=['dj_pq',]Apply migrations:./manage.py migrateUsagedj-pqexposes thepq tasks API.fromdj_pqimportget_queuequeue=get_queue('notifications')@queue.task()defnotify(user_id):User.objects.get(id=user_id).notify()notify(42)Optionally aQueuecan be bound to a specific database connection:queue=get_queue('notifications','another_connection')Aworkercommand allows to start a worker for a given queue:./manage.py worker notifications
Package: djpubsubhubbub
READMEThis is a mirror of the original app (see ORIGINAL README below.)The small changes I made were just to integrate custom header
support into the app. This is needed to interface with the
SuperFeedr.com hub.Updated to work cleanly with Django 1.5.INSTRUCTIONSPlease see:https://bitbucket.org/petersanchez/djpubsubhubbub/wiki/InstallationFor SuperFeedr tutorial, please see:https://bitbucket.org/petersanchez/djpubsubhubbub/wiki/SuperFeedr_TutorialDEPENDENCIESRequires the django-easyconfig and feedparser packages.$ pip install django-easyconfig
$ pip install feedparser# Note, if you install djpubsubhubbub from pip yourself,
# it should handle the dependencies for you.REQUIREMENTSThis app assumes you are running at least Python 2.4
and Django 1.2AUTHORSThe good people at Participatory Culture
Peter Sanchez -peter@netlandish.comMartin Bachwerk -martin@webscio.netORIGINAL READMEThis is a Django PubSubHubBub module.Code is at:https://git.participatoryculture.org/djpubsubhubbubLicense information is in the LICENSE file.
Package: djpush
========Djpush========Manage programatic *Push Notifications* from Django admin.Features========- Define notifications via the admin- Categorize notifications- Schedule notifications by category- Choose your provider(APNS/apns2, GCM/gcm, OneSignal/yaosac). Actually you must install one.- Same notification in time range are canceled- (optional) Multiple language support via django-modelstranslationImportant Dependencies======================- django-timezone-field- pytzUsage=====In your `settings.py` define:DJPUSH_NOTIFICATIONS_CHOICESA list of `slugs <https://docs.djangoproject.com/en/1.11/glossary/#term-slug>`_ representing the notifications you want to send.DJPUSH_DEFAULT_PROVIDERThe provider you want to use to send notifications(values can be found in `pypn <https://github.com/alej0varas/pypn>`_).optional settingsDJPUSH_NOTIFICATION_EXPIRESThe number of seconds after task will be considered expired.. code-block:: python# Get a notification, you define them in the adminnotification = models.Notification.objects.get(slug='a-slug', enabled=True)# Create a notification instancenotification_instance = models.NotificationInstance.objects.create(notification=notification, tokens=tokens, data=data)# Send the notificationnotification_instance.send()Development===========Update migrations-----------------::DJANGO_SETTINGS_MODULE=migration_settings django-admin makemigrationsRun tests---------::./runtests.pyBuild/Publish-------------::rm -rf distpython setup.py sdist bdist_wheeltwine upload dist/*Translations------------To enable translations you have to install `django-modeltranslation`and add `MIGRATION_MODULES = {'djpush': 'djangoproject.migrations'}`to your settings.Notifications will be sent including the available tranlations.
Package: dj-py
Django PayPal REST API Integration:Building a Secure and Reliable Payment Gateway## DescriptionIn this project, we leverage the power of Django to create a robust REST API for integrating PayPal as a secure payment gateway into your web application. With PayPal’s wide adoption and reliability, integrating it into your platform will provide seamless and convenient payment options for your users.## Key FeaturesUser Authentication and Authorization:Implement a secure authentication system using Django’s built-in authentication module to ensure that only authorized users can access and make payments through the PayPal API.PayPal API Integration:Utilize PayPal’s REST API to handle payment transactions securely. Implement endpoints for initiating payments, processing transactions, handling refunds, and managing payment status updates.Error Handling and Validation:Implement robust error handling and data validation mechanisms to ensure smooth and error-free communication with the PayPal API. Handle various scenarios such as validation errors, network failures, and transaction discrepancies gracefully.Webhooks and Notifications:Set up webhooks to receive real-time notifications from PayPal regarding payment status changes, refunds, and other relevant events. Use Django’s webhook handling capabilities to update your application’s database and notify users accordingly.Comprehensive Documentation:Provide clear and concise documentation on how to use the API endpoints, authenticate requests, handle responses, and troubleshoot common issues. Include code samples, usage examples, and best practices to assist developers in integrating the PayPal REST API into their Django applications.Testing and Deployment:Develop comprehensive test suites to ensure the functionality and reliability of your API. Implement secure deployment practices, including environment configuration and integration with your chosen hosting provider.By the end of this project, you will have a powerful REST API integrated with PayPal, providing your users with a seamless and secure payment experience. With Django’s robustness and PayPal’s reliability, you can confidently handle payment transactions within your application.Note:It is important to familiarize yourself with PayPal’s developer documentation and guidelines to ensure compliance with their API usage policies and security practices.
Package: djpykafka
djpykafka🚧 This project is WIP and is subject to change at any timeThis project is currently in the alpha state, even though it can be used in production with some caution. Make sure to fix the version in your requirements.txt and review changes frequently.Installationpip install djpykafkaExamplesAdd theKafkaPublishMixinto your model class.fromdjango.dbimportmodelsfromdjpykafka.modelsimportKafkaPublishMixinclassMyModel(KafkaPublishMixin,models.Model):...Create a publisher class, e.g. atevents/publish/{modelname_plural}.pyfromdjpykafka.events.publishimportEventPublisher,DataChangePublisherfrom...importmodelsfrom...schemasimportresponsefrom.importconnectionclassMyModelPublisher(DataChangePublisher,EventPublisher,orm_model=models.MyModel,event_schema=response.MyModel,connection=connection,topic='bizberry.access.users',data_type='access.user',):passAsyncAPI DocsThis feature is WIP.Install djpykafka with the extradocs(pip install djpykafka[docs]) and add the following snippets to yourasgi.py:fromstarlette.responsesimportHTMLResponse,JSONResponsefromstarlette.routingimportRoutefromfastapi.encodersimportjsonable_encoderfromasyncapi_docgen.docsimportget_asyncapi_ui_html# ! Import after django's get_asgi_application()fromdjpykafka.docs.asyncapiimportget_asyncapidefasyncapi_html(request):returnHTMLResponse(get_asyncapi_ui_html(asyncapi_url='/asyncapi.json'))defasyncapi_json(request):returnJSONResponse(jsonable_encoder(get_asyncapi(),by_alias=True,exclude_none=True))app=FastAPI(...,routes=[Route('/asyncapi',asyncapi_html),Route('/asyncapi.json',asyncapi_json),],)
Package: djqdqtranslations
Django QDQMedia Translations====================Installs Django commands to manages translations.Installation------------pip install --extra-index-url http://pypi.qdqmedia.com:8888/simple djqdqtranslationsConfigure---------- Add ``djqdqtranslations`` to the INSTALLED_APPS.- Define the variable THEMES_REPOS in your project settings.Development---------------Install `requirements-dev.txt` into a virtualenv.Using _virtualenvwrapper_:mkvirtualenv djqdqtranslationsworkon djqdqtranslationspip install -r requirements-dev.txtRun tests:python -m djqdqtranslations.tests
Package: djqgrid
djqgridis a Django wrapper for jqGrid.djqgridlets you define grids in a Django-familiar way, while taking care of most of the mundane Python-JavaScript bridge for you.You can find the documents atReadTheDocs.Quick ExampleAdddjqgridto your projectInstall withpip install djqgridAdddjqgridto yourINSTALLED_APPS.Reference thejqGridandjQueryUIJavaScript and CSS filesReference the script at{% static "js/djqgrid_utils.js" %}Add thedjqgridURLs tourls.py:urlpatterns += patterns('', url(r^'grid_json/', include (djqgrid.urls))Define your modelclass MyModel(models.Model):
    name = models.CharField(max_length=40)
    desc = models.CharField(max_length=100)
    url = models.URLField()
    height = models.IntField()Define your gridclass MyGrid(Grid):
    model = MyModel

    name = TextColumn(title='Name', model_path='name')
    height = TextColumn(title='Height', model_path='height', align='right')
    desc = LinkColumn(title='Description', model_path='desc', url_builder=lambda m: m.url)What we have here is a grid associated withMyModelobjects - each grid row represents one object. The grid has three columns:Name - a basic column containingmodel.nameHeight - containingmodel.height, but right alignedDescription - containing a link - its text will bemodel.descand the URL will bemodel.urlOne thing to note isalign='right'- this property is passed directly to jqGrid in the column’scolModel. Any property can be passed to jqGrid this way. For exampleTextColumn(title=...,model_path=...,editable=true)creates an editable column.Add the grid to your view and templateThe view:define myview(request):
    grid = MyGrid()
    return render(request, 'my_template.html', { grid: grid })The template:{% load djqgrid %}

<div id="grid-div">
    {% jqgrid grid %}
</div>Now run the view. You should see a very nice grid that supports paging and sorting.
Package: dj-queryset-manager
A Django utility that makes it simple to write DRY queryset methods.Warningdj-queryset-manager only works with Django versions 1.2 through 1.6.In Django 1.7 it has been superseded byQuerySet.as_manager(). Seethe docs.UsageCreate a manager class that inherit theQuerySetManagerDecorate your filter methods withqueryset_method.These methods receive a queryset instead of a manager as the first argument.fromdj_queryset_managerimportQuerySetManager,queryset_methodclassMyManager(QuerySetManager):@queryset_methoddefby_slug(queryset,slug):returnqueryset.filter(slug=slug)@queryset_methoddeffilter(queryset,*args,**kwargs):returnsuper(type(queryset),queryset).filter(*args,**kwargs)For reference, here is a standard implementation:fromdjango.db.modelsimportManagerfromdjango.db.models.queryimportQuerySetclassMyQuerySet(QuerySet):defby_slug(self,slug):returnself.filter(slug=slug)deffilter(self,*args,**kwargs):returnsuper(MyQuerySet,self).filter(*args,**kwargs)classMyManager(Manager):defget_query_set(self):# Better remember the arguments to QuerySetQuerySet(self.model,using=self._db)defget_queryset(self):# And don't forget about Django 1.6returnself.get_query_set()defby_slug(self,*args,**kwargs):# Enjoy this duplicate signaturereturnself.get_queryset().filter(*args,**kwargs)Mix-inSome third-party apps ship managers as part of their API. If you need to extend any existing manager, use theQuerySetManagerMixin. This example uses theInheritanceManagerfromdjango-model-utils.frommodel_utils.managersimportInheritanceManagerfromdj_queryset_managerimportQuerySetManagerMixin,queryset_methodclassMyInheritanceManager(QuerySetManagerMixin,InheritanceManager):@queryset_methoddefby_slug(queryset,slug):returnqueryset.filter(slug=slug)Installation$ pip install dj-queryset-manager
Package: dj-querytools
dj-querytoolsA collection of functions to make it a little easier to build aggregation SQL queries for Django projectsInstallationpip install dj-querytoolsUsageSimple aggregation:Assuming the following model:class Todo(models.Model):
    owner = models.CharField(max_length=30)
    title = models.CharField(max_length=30)
    status = models.CharField(max_length=30, choices=TODO_STATUSES)
    size = models.PositiveIntegerField(default=1)
    due = models.DateField()
    due_time = models.DateTimeField()group_by_and_aggregateExamplegroup_by_and_aggregate(qs,'size','Sum')>>20group_by_and_annotatePerforms the aggregation and groups by the provided field:Exampleresult=group_by_and_annotate(qs,'status','Count')>>{'D':5,'N':1,'P':8}as_timeseriesqs = Todo.objects.filter(owner="Jack")
as_timeseries(
    qs,
    'due_time',
    'id',
    'Count',
    '2018-11-01',
    '2018-11-10'
)
>> [{'x': '2018-11-01', 'y': 3.0}, {'x': '2018-11-02', 'y': 3.0}, {'x': '2018-11-03', 'y': 0}, {'x': '2018-11-04', 'y': 2.0}, {'x': '2018-11-05', 'y': 2.0}, {'x': '2018-11-06', 'y': 0}, {'x': '2018-11-07', 'y': 0}, {'x': '2018-11-08', 'y': 0}, {'x': '2018-11-09', 'y': 0}, {'x': '2018-11-10', 'y': 0}]pivot_tableGiven a flat queryset, group it by one or more fields.fields are comma seperatedoptionally provide a serializer function to serialize items (otherwise it will just append the queryset row)result=pivot_table(qs,'owner,status',serialize_todo)>>{'Jack':{'N':[{'title':'Day year outside whatever int'}],'P':[{'title':'Answer society close example '},{'title':'Raise real individual general'}],'D':[{'title':'Number organization particula'},{'title':'Least activity herself than c'},{'title':'Country local pretty yourself'}]},'Jane':{'P':[{'title':'Prevent do still teacher grou'},{'title':'Include they management first'},{'title':'Number court few loss sort mu'},{'title':'That federal end local dream '},{'title':'Able ask listen. Cost ball me'},{'title':'Bad know meeting compare room'}],'D':[{'title':'Through town stay able car di'},{'title':'Tree design candidate because'}]}}periodic_breakdownfrom querytools.tools import periodic_breakdownProvide an aggregation broken down by a period (Trun(kind=)).See:https://docs.djangoproject.com/en/2.1/ref/models/database-functions/#django.db.models.functions.TruncMonthDefaults:kind='month'aggregate_field='ok'aggregation = 'Count'# simple case:result=periodic_breakdown(qs,'due')# slighly more fancy:result=periodic_breakdown(qs,'due',aggregate_field='size',aggregation='Sum')Other stuffFor full functionality list, seespec.txtFor examples, checkexample_app/tests.pyContributingUpdate the spec:python manage.py test --testrunner=testreporter.runner.BDDTestRunner
Package: dj_queue_health
dj-queue-health  -Simple django app for checking queue health. Targeted to be used for Kubernetes deployments to periodically scheduleupdate_queue_timestampand set timestamp and verified bytest_queue_healthas a probe to verify if worker works and is not stacked.InstallationUsing pip:pipinstalldj-queue-healthUsageAdddj_queue_healthto your INSTALLED_APPS setting like this:INSTALLED_APPS=[...,"dj_queue_health",]Add variabledjango_queue_healthto your settings like this:# Minutes django_queue_health to check if there is queue log and if queue is runningdjango_queue_health=10Configure defaultdjango cache.Queue Health usedjango rqorcelery.Use commands:# Push job to queue that updates the timestamppythonmanage.pyupdate_queue_timestamp# Check if timestamp in cache less than django_queue_healthpythonmanage.pytest_queue_health
Package: djraphql
DjraphQLCheck out thedocumentation!WhatDjraphQL ("GiraffeQL") is a library that examines your Django models and builds a flexible, performant GraphQL schema usingGraphene. No resolvers necessary.You can of course extend this schema, reference the defined types and build custom business logic into your own resolvers. The goal is to remove the monotonous 90% of boilerplate generalized C.R.U.D. and allow you to focus on stuff that can't be auto-generated.HowYou provide a list of Django models and some associated metadata. For example, you can define the QuerySet that will be used for each fetch of a certain model type (you have access to the Django request object in the definition lambda for the QuerySet). By providing a QuerySet that is already filtered by e.g., user account, the library will use that QuerySet in the resolvers it generates. The requirement that you mustrememberto filter by account is all but eliminated.It builds each relationship into the schema, so you can traverse fromLabeltoArtisttoAlbumtoSongin a single query (both in the result-set and via filtering), still retrieving only the data you need.You can specify arbitrarily complex SQL statements: the schema allows specifying filtering viawhere,orderBy,offset,limit, ordistinct.It allows smooth (nested, if you're bold enough!) updates & inserts.Perhaps best of all, it automatically generatesselect_relatedandprefetch_relatedcalls to your QuerySet. This avoids the classic GraphQL N+1 problem usually solved by things likedataloader. Additionally, it fetchesonlythe columns necessary to satisfy the query. No over fetching!A hand-rolled schema providing all of this for a single model would be hundreds of lines of code. Multiply that by a realistic, mature application with a hundred or more models, and you have an unmaintainable mess. This library auto-generates it for you, leaving the fun stuff for you.ContributingSeeCONTRIBUTING.md.
Package: dj-raw-sql
dj-raw-sqldj-raw-sql is just a wrapper over thestandard Django queryThis demo shows how to get the record(s) from the databaseExample:defget_music_by_id(id:int):return"SELECT * FROM dj_app_music WHERE id =%s",(id,)fromdjango.dbimportmodels# Our demo modelclassMusic(models.Model):name=models.CharField(max_length=150)create_at=models.DateTimeField(auto_now_add=True)update_at=models.DateTimeField(auto_now=True)is_delete=models.BooleanField(default=False)fromdjango.httpimportJsonResponsefromdjango.viewsimportViewfrommy_app.queriesimportget_music_by_idfromdj_raw_sqlimportQueryExecutorclassMyView(View):defget(self,request,*args,**kwargs):music:tuple[tuple]=QueryExecutor.fetchone(get_music_by_id,id=1)returnJsonResponse({"name":music[0][1]})BenchmarksQ: How were performance tests conducted?A: tests/test_collection/ performance tests are located here. A dataset of 5000 elements was generated and loaded into the database. Then the query "SELECT * FROM dj_app_music LIMIT %s" was called, where the value of LIMIT changed from 10 to 5000 in each test.Test resultsNumber of itemsfetchallto_ordereddict=True100.000060.000111000.000170.0002510000.001380.0020750000.006580.01052Improve projectIf you want to improve the project then create "Issues" . If you want to help with writing tests or typing, create a "pull request".
Package: dj-redis-url
This simple Django utility allows you to utilize the12factorinspiredREDIS_URLenvironment variable to configure your Django application.UsageConfigure your Redis database insettings.pyfromREDIS_URL:REDIS = {"default": dj_redis_url.config()}Parse an arbitrary Database URL:REDIS = {"default": dj_redis_url.parse("redis://..."")}InstallationInstallation is simple too:$ pip install dj-redis-url
Package: dj-registry
DJ-RegistryThis is a simple, easy access key-value registry for Django. Sometimes you would like to have some flexibility in your settings.
Putting your settings insettings.pyor as environment variables also mean an engineer familiar with code or command line is required to alter them.This Django app leverage the built-in Django admin so changing settings is easier as you can use the web interface.RequirementsPython = "^3.6"Django = "^3"Run the following command inside project's root folder to install it's dependencies with Poetry:$ poetry installYou can specify to the command that you do not want the development dependencies installed by passing the--no-devoption.If you have not yet installed Poetry, please refer to theirofficial documentation.InstallationInstall DJ-Registry with your favorite Python package manager:(venv)$ pip install dj_registryAddregistryto yourINSTALLED_APPSsettings:INSTALLED_APPS=[# other apps...'registry',]Migrate the database(venv)$ ./manage.py migrateThen, we're all set!UsageLog in to the admin, and create some keys under theDjango Registry>Entriessection. Let's say, we createmailgun.keyandmailgun.domainwith the correspondingstringtype and values.
We then create another entry withgame.max_scoreas the key,10000as the value andintegeras the type.The following example shows you how to access them in code:fromregistry.helperimportregkey=reg['mailgun.key']# the key that you setdomain=reg['mailgun.domain']# the domain that you setmax_score=reg['game.max_score']# 10000, it is returned as an intYou can also usegetif you want to have a default and avoid exceptions if the key is not available (not enabled or does not exist)reg.get('game.levels',10)# return 10 if key not found or disabledreg['game.levels']# KeyError if key not found or disabledYou can set or delete entry if you wantreg['game.levels']=12# Set game.levels to 12 (integer) and savedelreg['game.levels']# Delete game.levelsEnabled and comment fieldIf you want to disable a key, just toggle theenabledboolean in the admin interface. It would be treated as if the key didn't exist. This is something meant to be used in the admin interface.
If you want to manipulate this in the code, you will have to access the raw model like the following:fromregistry.modelsimportEntrye=Entry.objects.get('game.levels')e.enabled=Falsee.save()The comment field is also meant to be used in the admin interface. It is a convenient cell for user to put comments regarding to the settings, something like the following:50: average use case.
9999: maximum special caseTypesinteger,float,string, andbooleanare the supported types for now.