Saravanan666/pypi-org huggingface dataset:
Package: django-db-cascade-2
django-db-cascade-2Installation for Django 3pip install django-db-cascade-2Installation for Django 2pip install django-db-cascade-2==0.2.3settings.py:DATABASES = {
    'default': {
        'ENGINE': 'django_db_cascade.backends.postgresql_psycopg2',
        # ... etc ...
    }
}Usagefrom django.db import models
from django_db_cascade.fields import ForeignKey, OneToOneField
from django_db_cascade.deletions import DB_CASCADE

class Thing(Common):
    account = ForeignKey('self', DB_CASCADE)CaveatsDB_CASCADE only supports PostgresDB_CASCADE does not support django on_delete signalsDB_CASCADE will not cascade delete multiple inherited tables as expectedDB_CASCADE will not trigger CASCADE on another model. E.g. Model A points to model B, via DB_CASCADE. Model B points to model C, via CASCADE. A will cascade delete B, B will django delete C, butdeleting A will not delete C!DB_CASCADE on a ManyToMany of A <---> B, only A_B set records will be cascade deleted (deleting A will not delete B)How it worksMinimal subclassing of the django postgresql backend and the django ForeignKey fieldAdded a new possible value for ForeignKey's on_delete kwarg, called DB_CASCADEWhen you use DB_CASCADE, the migration framework will recognize a change, and write new sqlexample SQL generated:ALTER TABLE mytable ADD CONSTRAINT myconstraint FOREIGN KEY (mycolumn)
REFERENCES myothertable myothercolumn ON DELETE CASCADE DEFERRABLE INITIALLY DEFERREDFuture proofIf, and when, DB_CASCADE ever gets into django, editing these generated migrations should be very easy.Generated migrations:migrations.AlterField(
    model_name='modelname',
    name='fieldname',
    field=django_db_cascade.fields.ForeignKey(on_delete=django_db_cascade.deletions.DB_CASCADE)
)Changing them over, if django ever handles DB_CASCADE natively, might look like:migrations.AlterField(
    model_name='modelname',
    name='fieldname',
    field=django.db.models.ForeignKey(on_delete=models.DB_CASCADE)
)TicketThe ticker where django has discussed bringing DB_CASCADE to django:https://code.djangoproject.com/ticket/21961
Package: django-dbcleanup
django-dbcleanupEasily monitor database usage - and clean it up (based on your django models)This pluggable app provides:visibility over database disk space usage for your modelscommand to remove unused tables and recover disk spaceremove historical data from models that haveanyDateTimeField(configurable in the project settings.py)Usagemodel and admin viewdbcleanup.Tableis an unmanaged model mapped to information tables in MySQL and PostgreSQL and added to django admincommanddbcleanupis the management command that can be used (or scheduled) to remove unused$ ./manage.py dbcleanup -h
usage: manage.py dbcleanup [-h] [-f] [-i] [-j {tables,history,analyze,migrations}] [--no-fk] [--version] [-v {0,1,2,3}] [--settings SETTINGS] [--pythonpath PYTHONPATH] [--traceback] [--no-color]
                           [--force-color] [--skip-checks]

Remove database tables that do not map to any models, such as when a django app is removed/disabled.

optional arguments:
  -h, --help            show this help message and exit
  -f, --force           Delete the items (instead of just listing them)
  -i, --interactive     Ask which items to delete, interactively
  -j {tables,history,analyze,migrations}, --just {tables,history,analyze,migrations}
                        Perform only a subset of actions
  --no-fk               Disable FOREIGNKEY_CHECK when DROPping tables - CAREFUL! use only if you are sure the constraints are not from a table in use (ie: circular dependencies between drop candidates)Need to use--forceor--interactiveto actually perform changes, otherwise it'll be a dry run.Covered actions are:tables: remove database tables that do not map to any model (ie: when a app is removed from the project, there is no migration to delete the tables) - usesettings.DBCLEANUP_REQUIRED_TABLESto whitelist tables that would otherwise be removedhistory: remove old records for the models defined insettings.DBCLEANUP_HISTORY_MODELS(more below)analyze: only for MySQL - force analyze on all the tables to update the row count and size estimatesmigrations: remove migrations (fromdjango_migrationstable) that not in the project migration path (ie: after migration squashing and reset)historical datasettings.DBCLEANUP_HISTORY_MODELSis a list of tuples where each tuple is(MODEL_NAME, DAYS_TO_KEEP, DATE_TIME_FIELD_NAME).# someproject/settings.py
DBCLEANUP_HISTORY_MODELS = [
    ('notifications.notification', 365, 'time'),
    ...
]With this setup, when./manage.py dbcleanup -j historyis executed, allnotifications.Notificationentries withtimeolder than 365 days would be deleted.History cleanup is skipped if it would cascade into other models (unless it's a multi-table model and it would cascade to the parent model).
Package: django-db-comments
Move your model’s verbose name and help_text to database comments:DocumentationThe full documentation is athttps://django-db-comments.readthedocs.io.QuickstartInstall Django Db Comments:pip install django-db-commentsAdd it to yourINSTALLED_APPS:INSTALLED_APPS=(...'django_db_comments',...)FeaturesCopy verbose_name and help_text to columns in DB, currently:Postgres.Running TestsDoes the code actually work?source <YOURVIRTUALENV>/bin/activate
(myenv) $ pip install tox
(myenv) $ toxCreditsTools used in rendering this package:Cookiecuttercookiecutter-djangopackageHistory0.4.1 (2022-04-03)Bugfix for models detection and more unit tests. (PR #13)0.4.0 (2022-04-02)Skip proxy, abstract and not managed model. (Issue #11 by @xjlin0)0.3.1 (2021-08-02)Update meta information in setup.py.0.3.0 (2021-08-02)Add comments to tables based on verbose_name of model. (PR #5 by @ssatoh17)0.2.2 (2019-05-19)Add psqlextra.backend to ALLOWED_ENGINES. (PR #4 by @shuribuzz)0.2.1 (2019-05-19)Fix case, when help_text or verbose_name use ugettext_lazy from django. (PR #1 by @ErhoSen)0.2.0 (2019-05-07)First release on PyPI.
Package: django-db-connection-pool-plus
django-db-connection-poolMySQL & Oracle & PostgreSQL connection pool backends of Django, Be based on SQLAlchemy.中文版QuickstartInstall withpipwith all engines:$pipinstalldjango-db-connection-pool[all]or select specific engines:$pipinstalldjango-db-connection-pool[mysql,oracle,postgresql]ConfigurationMySQLchangedjango.db.backends.mysqltodj_db_conn_pool.backends.mysql:DATABASES = {
    'default': {
        ...
        'ENGINE': 'dj_db_conn_pool.backends.mysql'
        ...
    }
}Oraclechangedjango.db.backends.oracletodj_db_conn_pool.backends.oracle:DATABASES = {
    'default': {
        ...
        'ENGINE': 'dj_db_conn_pool.backends.oracle'
        ...
    }
}PostgreSQLchangedjango.db.backends.postgresqltodj_db_conn_pool.backends.postgresql:DATABASES = {
    'default': {
        ...
        'ENGINE': 'dj_db_conn_pool.backends.postgresql'
        ...
    }
}pool options(optional)you can provide additional options to pass to SQLAlchemy's pool creation, key's name isPOOL_OPTIONS:DATABASES = {
    'default': {
        ...
        'POOL_OPTIONS' : {
            'POOL_SIZE': 10,
            'MAX_OVERFLOW': 10
        }
        ...
     }
 }Here's explanation of these options(from SQLAlchemy's Doc):pool_size: The size of the pool to be maintained,
defaults to 5. This is the largest number of connections that
will be kept persistently in the pool. Note that the pool
begins with no connections; once this number of connections
is requested, that number of connections will remain.pool_sizecan be set to 0 to indicate no size limit; to
disable pooling, use a :class:~sqlalchemy.pool.NullPoolinstead.max_overflow: The maximum overflow size of the
pool. When the number of checked-out connections reaches the
size set in pool_size, additional connections will be
returned up to this limit. When those additional connections
are returned to the pool, they are disconnected and
discarded. It follows then that the total number of
simultaneous connections the pool will allow is pool_size +max_overflow, and the total number of "sleeping"
connections the pool will allow is pool_size.max_overflowcan be set to -1 to indicate no overflow limit; no limit
will be placed on the total number of concurrent
connections. Defaults to 10.or you can use dj_db_conn_pool.setup to change default arguments(for each pool's creation), before using database pool:importdj_db_conn_pooldj_db_conn_pool.setup(pool_size=100,max_overflow=50)
Package: django-db-connection-retrier
Django Database Connection RetrierAutomatically try to re-establish Django database connections when they fail due to DNS errors.When the Django app (dbconnectionretrier) loads, a hook is installed in Django'sBaseDatabaseWrapper.ensure_connectionthat catchesdjango.db.OperationalError. If the error raised is a DNS error, the connction attempt is retried synchronouslythree times.Tested on Django 2.0-2.3 and Python 3.7 and 3.8. Might work with other versions of Django and Python.InstallationInstall the package from PyPi:$ pip install django-db-connection-retrierAdddbconnectionretrierto yourINSTALLED_APPS:INSTALLED_APPS = [
     'dbconnectionretrier',
     ...
 ]Manual usageAddingdbconnectionretriertoINSTALLED_APPSenables automatic connection retrying. Want more granular control over patching?Globallyfrom dbconnectionretrier.patch import patch_ensure_connection

# after this line executes, connection retrying is enabled
patch = patch_ensure_connection()

# after this line, the connection retrying is disabled
patch.rollback()Context managerfrom dbconnectionretrier.patch import patch_ensure_connection_contextual

with patch_ensure_connection_contextual():
    # all code inside this block benefits from connection retrying
Package: django-db-constraints
# django-db-constraints## What is this?Add database table-level constraints to your Django model's Meta class and have `makemigrations` add the appropriate migration.```pythonclass Foo(models.Model):bar = models.IntegerField()baz = models.IntegerField()class Meta:db_constraints = {'bar_equal_baz': 'check (bar = baz)',}```This should generate a migration like so:```pythonclass Migration(migrations.Migration):initial = Truedependencies = []operations = [migrations.CreateModel(name='Foo',fields=[('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),('bar', models.IntegerField()),('baz', models.IntegerField()),],),django_db_constraints.operations.AlterConstraints(name='Foo',db_constraints={'bar_equal_baz': 'check (bar = baz)'},),]```The resulting SQL applied:```sqlCREATE TABLE "sample_foo" ("id" serial NOT NULL PRIMARY KEY, "bar" integer NOT NULL, "baz" integer NOT NULL)ALTER TABLE "sample_foo" ADD CONSTRAINT "bar_equal_baz" check (bar = baz)```## Composite foreign keysIt's possible to support composite foreign keys if you have a unique key on your reference model:([Why are composite foreign keys useful?](https://github.com/rapilabs/blog/blob/master/articles/same-parent-db-pattern.md))```pythonclass Bar(models.Model):baz = models.IntegerField()class Meta:unique_together = ('id', 'baz')class Foo(models.Model):bar = models.ForeignKey(Bar)baz = models.IntegerField()class Meta:db_constraints = {'composite_fk': 'foreign key (bar_id, baz) references sample_bar (id, baz)',}```Results in:```sqlALTER TABLE "sample_foo" ADD CONSTRAINT "composite_fk" foreign key (bar_id, baz) references sample_bar (id, baz)```## Migration operation orderingGiven that nothing will depend on a constraint operation, they're simply added to the end of the list of operationsfor a migration.  This includes operations that drop fields used in a constraint as the database drop will any relatedconstraints as well (at least with PostgreSQL).## CaveatsIt's possible to end up in a situation where the constraints are declared on the Meta class but do not exist in the databasedue to a database dropping a constraint implicitly when a field in the constraint is dropped.## Installation```pip install django-db-constraints```in your settings.py:```pythonINSTALLED_APPS = ['django_db_constraints',…]```
Package: django-db-counter
django-db-counterObtain continuous count.Installpip install django-db-counterUse a shared table to countfrom django_db_counter.models import DjangoDBCounter


some_id = DjangoDBCounter.get_next("some_keyword")Use a dedicated table to countapp/models.pyfrom django_db_counter.models import DjangoDBCounterBase

class MyCounter(DjangoDBCounterBase):
    default_key = "my_counter_keyword" # default to "default"app/views.pyfrom app.models import MyCounter

some_id = MyCounter.get_next()Releasesv0.1.0First release.
Package: django-dbcron
django-dbcron=============Manage crontab directly from your Django databaseWhy---They are plenty of implementation of crontabs in Python and Django, but ourissue was their elasticity. Generally a set of classes will allow you tocreate a crontab, here in django-dbcron, things are stored in databaseinstead of Python classes.Installation------------Classic pip install: ::pip install django-dbcronAdd it to you ``INSTALLED_APPS``: ::INSTALLED_APPS = (...'dbcron',...)Launch migrations: ::./manage.py migrate dbcronUsage-----This app owns its own cron daemon, launch it with: ::./manage.py crondThe daemon will act as a classic cron and will run each task in a new thread,leaving the main one continuing.From admin~~~~~~~~~The cron table is set in database and the Django admin site is a quicksolution to manage you jobs.From Python~~~~~~~~~~Just play with the model: ::from dbcron.models import Job# Run now() each minutejob = Job.object.create(name='My job',func='django.utils.timezone.now',is_active=True,sec="0",min="*/1,hou="*",dom="*",mon="*",dow="*",yea="*")# Test itjob.run()Warning-------The cron daemon launches jobs as they are requested with:- function's path- arguments and keyword argumentsThere's no security about who/when/how, just functions launched abritairly,Be careful who can set crontab, and do not hesitate to limit possible values.
Package: django-dbdump
This tiny Django application provides a “dbdump” management command that wraps
mysqldump or pg_dump and allows you to create SQL dumps of your configured
databases.To use, add ‘dbdump’ to your INSTALLED_APPS.Usage:$ manage.py dbdump$ manage.py dbdump –db-name=mydb –debug –compress=gzipYou can dump only table schema without data or exclude tables completely
using DB_DUMP_EMPTY_TABLES and DB_DUMP_EXCLUDED_TABLES settings inside
your settings.DATABASES definition. For example:DATABASES = {
    'default': {
        'ENGINE': 'mysql',
        ...
        'DB_DUMP_EMPTY_TABLES': ['table1', 'table2'],
    }
}will not include contents of table1 and table2 in your output.Seehttp://github.com/vitaliyf/django-dbdumpfor more information.
Package: django-db-email
django-db-emailDatabase email backend for Django.RationaleCapture emails in database during development.SupportSupports: Python 3.10.Supports Django Versions: 4.2.7Installation$pipinstalldjango-db-emailUsageAdddb_emailtoINSTALLED_APPS.SetEMAIL_BACKENDto: "db_email.backend.EmailBackend"Run migrations:pythonmanage.pymigrateView captured emails in Django Admin.
Package: django-db-email-backend
Django DB Email Backend=======================[![Build Status](https://travis-ci.org/jsatt/django-db-email-backend.svg?branch=master)](https://travis-ci.org/jsatt/django-db-email-backend)Django email backend for storing messages to a database. This is intended to be used in developement in cases where you want to test sending emails, but don't want to send real emails and don't have access to the console output (such as on a remote server).This is NOT intended for production use in any capacity.To install:```shpip install django-db-email-backend```In settings.py:```pythonINSTALLED_APPS = [...'db_email_backend',]EMAIL_BACKEND = 'db_email_backend.backend.DBEmailBackend'```
Package: django-dbfiles
django-dbfilesA fork ofdjango-db-storage, updated for modern versions of Django (and renamed for inclusion in PyPI).OverviewWarning: In many cases, storing files in the database is a BAD idea. Your database will easily become bloated and theperformance can degrade rapidly. See thisStackExchange postfor more information.This is a custom storage backend for storing files in the database instead of the file system and is a drop-in replacement for Django's FileSystemStorage. Some benefits of this application:no changes needed to existing models, it just works (and if it doesn't, open a ticket!)django-admin is implemented and can be used to search, upload, download and manage files100% code coverage with unit testsRequirementsPython 3.8 or aboveDjango 3.2 or aboveInstallationInstallation using pip:pip install django-dbfilesUpdatesettings.py:# Add 'dbfiles' to INSTALLED_APPSINSTALLED_APPS=['dbfiles',]# Optionally set DEFAULT_FILE_STORAGEDEFAULT_FILE_STORAGE='dbfiles.storage.DBStorage'# Choose a root url for uploaded filesMEDIA_URL='/media/'Updateurls.py:urlpatterns=[...dbfiles_url(),]Run database migrations:python manage.py migrateHow to UseNo modification are needed for models to work properly.defuser_directory_path(instance,filename):return'user_{0}/{1}'.format(instance.user.id,filename)classMyModel(models.Model):file_field1=models.FileField()file_field2=models.FileField(upload_to='uploads/%Y/%m/%d/')file_field3=models.FileField(upload_to=user_directory_path)Moving from django-db-storage?If you are switching to this package fromdjango-db-storageand want to keep your existingdb_filetable, let Django know about the app name change by running the following SQL:UPDATEdjango_migrationsSETapp='dbfiles'WHEREapp='dbstorage';Bugs?Create an issue athttps://github.com/imsweb/django-dbfiles/issues
Package: django-db-file-storage
Django DB File Storage is a customfile storage systemfor Django. Use it to save files in your database instead of your file system.Supports Python versions2.7,3.5,3.6+, and Django versions1.11,2.2&3.0+.Dependencies scanned by PyUp.ioDocumentationThe project docs can be foundhere (RTD).DemoIn order to run the demo project, justdownload the project andcdinto it,cdinto thedemo_and_testsdirectory,pip-installall the libraries specified in therequirements filein your environment (you might want to create and use avirtual environment),runpython manage.py migrateandpython manage.py runserverfrom your shell andvisithttp://localhost:8000in your browser.Tests & ContributingIn order to run the tests and contribute to db_file_storage, check the instructions in theCONTRIBUTING file.
Package: django-db-geventpool
django-db-geventpoolAnother DB pool using gevent for PostgreSQL DB.Ifgeventis not installed, the pool will useeventletas fallback.psycopg2django-db-geventpool requires psycopg2:psycopg2>=2.5.1for CPython 2 and 3 (orpsycopg2-binary---seenotes in the psycopg2 2.7.4
release)psycopg2cffi>=2.7for PyPyPatch psycopg2Before using the pool, psycopg2 must be patched with psycogreen, if you
are usinggunicorn webserver, a good place
is thepost_fork()function at the config file:from psycogreen.gevent import patch_psycopg     # use this if you use gevent workers
from psycogreen.eventlet import patch_psycopg   # use this if you use eventlet workers

def post_fork(server, worker):
    patch_psycopg()
    worker.log.info("Made Psycopg2 Green")SettingsSet *ENGINE* in your database settings to:

:   -   *\'django\_db\_geventpool.backends.postgresql\_psycopg2\'*
    -   For postgis: *\'django\_db\_geventpool.backends.postgis\'*AddMAX_CONNStoOPTIONSto set the maximun number of
connections allowed to database (default=4)AddREUSE_CONNStoOPTIONSto indicate how many of the
MAX_CONNS should be reused by new requests. Will fallback to the
same value as MAX_CONNS if not definedAdd'CONN_MAX_AGE': 0to settings to disable default django
persistent connection feature. And read below note if you are
manually spawning greenletsDATABASES = {
    'default': {
        'ENGINE': 'django_db_geventpool.backends.postgresql_psycopg2',
        'NAME': 'db',
        'USER': 'postgres',
        'PASSWORD': 'postgres',
        'HOST': '',
        'PORT': '',
        'ATOMIC_REQUESTS': False,
        'CONN_MAX_AGE': 0,
        'OPTIONS': {
            'MAX_CONNS': 20,
            'REUSE_CONNS': 10
        }
    }
}Using ORM when not serving requestsIf you are using django with celery (or other), or have code that
manually spawn greenlets it will not be sufficient to set CONN_MAX_AGE
to 0. Django only checks for long-live connections when finishing a
request - So if you manually spawn a greenlet (or task spawning one) its
connections will not get cleaned up and will live until timeout. In
production this can cause quite some open connections and while
developing it can hamper your tests cases.To solve it make sure that each greenlet function (or task) either sends
the django.core.signals.request_finished signal or calls
django.db.close_old_connections() right before it endsThe decorator method with your function is preferred, but the other
alternatives are also validfrom django_db_geventpool.utils import close_connection

@close_connection
def foo_func()
     ...orfrom django.core.signals import request_finished

def foo_func():
   ...
   request_finished.send(sender="greenlet")orfrom django.db import close_old_connections

def foo_func():
   ...
   close_old_connections()Other poolsdjango-db-pooldjango-postgresql
Package: django-db-helper
Django-DB-HelperPackage contain necessary tools to complement your Django ORM usage.Install$  pip install django-db-helperUsageGet Object or NoneModel.objects.get() is widely use in getting a single record from the database. A DoesNotExist exception is thrown when the record is not found. get_object_or_none returns None when no matching record is found. This method is very helpful because most developers do not handle DoesNotExist exception from Model.objects.get() since it is used in anticipation that a single matching record is available.fromdjango_db_helper.get_object_or_noneimportget_object_or_none#### Formatget_object_or_none(Model,key1=value1,key2=value2,..)#### Getting User Object from User Model with an available usernameuser=get_object_or_none(User,username="andrewsxx")//=>userobject#### Getting User Object from User Model with an available usernameuser=get_object_or_none(User,username="andrewsxx1234")//=>NoneLicenseMIT © [Andrews Agyemang Opoku]
Package: django-dbindexer
Withdjango-dbindexeryou can emulate SQL features on NoSQL databases. For example, if your database doesn’t support case-insensitive queries (iexact, istartswith, etc.) you can just tell the indexer which models and fields should support these queries and it’ll take care of maintaining the required indexes for you. Magically, the previously unsupported queries will just work. Currently, this project is in a very early development stage. The long-term plan is to support JOINs and at least some simple aggregates, possibly even much more.Visit theproject sitefor more information.