Saravanan666/pypi-org huggingface dataset:
Package: django-dbreact
=======DbReact=======DbReact is simple but effective django app which makes any database defined within the project reactiveusing SSE ( Server Side Events - no need to install anything for sse | its a http concept ).The library provides any addition ,or deletion of objects in model ( row in rdms table ) ,in a json based protocol( sends json structure of objects deleted and added ) to the client (Android ,Ios ,Web).( On more Granular Level ) you can also make group of Model objects as reactive .Quick start-----------1. Add middleware string in middleware list of your project (in settings.py):MIDDLEWARE_CLASSES = [...'DbReactCreator.reactMiddle.reactiveMiddleware',]2. Import reactive decorator to views where you want to create the event pusher, and then create eventsource::from DbReactCreator.reactDecorators import dbreact...@dbreact("unique_id_for_eventsource_in_string")def pusher_function(request):request.META['objects_to_be_reactive'] = Model.objects.all() | Model.objects.filter() ( always a list of queryset objects)request.META['for_model'] = Modelreturn JsonResponse({},status=200)3. Define a url for the view , and pass it to the client (mobile | web) .4. As soon as client registers the url ,it starts getting json objects of the elements not present on its end.* Format of data received by client :{ add: [ json_serialized_queryset_object, ... ],delete: [ json_serialized_queryset_object, ... ]}
Package: django-db-retry
DescriptionDjango database retries. Main motivation for using this - to deal with network/db issues to avoid data-loss.Usually when you develop a project locally with a single user - everything works perfectly. Local networks are super-stable, and simultaneous users don't bother you.
When it comes to the real world - your application can (and definitely will) face network issues.
Second case - deadlocks, which I personally see too often across different projects.
And the only possible solution here to avoid the data-loss - to do a query retry.IMPORTANT:Right now this worksONLY WITH MYSQL. If someone requires postgres/other dbs support - please create an issueUsageInstall:pip install django-db-retryChoose your flow (or use both):Monkey-patch django internal methods (IMPORTANT:global patching won't handle retries for atomic transactions.with_query_retrydecorator should be used instead)Use explicit decoratorMonkey-patch:Add next code somewhere on the top level of your projectfromdjango_db_retryimportinstallasinstall_db_retriesinstall_db_retries()That's it =)
All the needed underlying django methods will be wrapped with the retry decorator and
will do execution retry if your app will face a network issue or deadlockDecoratorCan be used on top of any function/view and will do a retry if deadlock/network error will happen.
Default number of retries is 5. This value can be configured by using theQueryRetryclass (see example 2):fromdjango_db_retryimportwith_query_retryfromdjango.db.transactionimportatomic@with_query_retrydefsome_view():query_0,query_1=...withatomic():query_0()query_1()return...Configuring own value of retriesfromdjango_db_retryimportQueryRetryfromdjango.db.transactionimportatomicmy_retry_decorator=QueryRetry(max_tries=100)@my_retry_decoratordefsome_view():query_0,query_1=...withatomic():query_0()query_1()return...TodoDeal with atomic transactions during global patchingAdd possibility to install the package using djangoINSTALLED_APPSsettings
Package: django-dbrouter
[[TOC]]DescriptionSet of simple and usable database routers for django applitaionsdbrouter.DbByAppRouterdbrouter.DbByAppRouterallows you to specify django-applications or models, that will work with this database.dbrouter.RestrictMigrationsdbrouter.RestrictMigrationsallows you to specify a database to which you can not apply migrations.
For example, with read-only access.dbrouter.parse_database_urldbrouter.parse_database_urlallows you to specify a database connection as one stringExamplefromdbrouterimportparse_database_url# ...INSTALLED_APPS=[...'some_app','other_app',]...DATABASES={'default':{'ENGINE':'django.db.backends.sqlite3','NAME':'db.sqlite3',},# 'dbrouter.DbByAppRouter' usage example'external':{'NAME':'some_other',.....'applications':['some_app',#  all models on some_app'other_app.OnlyThisModel',#  OnlyThisModel on other_app],},# 'dbrouter.RestrictMigrations' usage example'some_read_only_external_database':{'NAME':'some_read_only_external_database',.....'allow_migrate':False,# False - disable migrations# True - do not disable migrations# None - default},'some_db_added_by_url':parse_database_url(# DB in remoge PostgreSQL-server on some schema'psql://user:pass@remote.db.host/dbname?options=-c search_path=some_schema',applications=['some_new_app'],allow_migrate=False)}...DATABASE_ROUTERS=['dbrouter.DbByAppRouter','dbrouter.RestrictMigrations',...]
Package: django_db_sampler
This python module was written to help create database fixtures from an existingdatabase that is too large to simply dump it in its entirety.Thanks to Jacob Rigby, Technical lead at Reya Group (http://www.reya.com)for his unhesitating agreement to release this to the open source community.The process copies the desired model instances to a separate databasealong with their dependencies, and optionally children (instances dependent onthem).  You can then dump the other database to get a minimal fixturefor your test case.Quick Reference:def db_sample(db_obj_iterable,	# Iterable containing Django model instanceschild_depth=1, 		# Set this to 2+ to also include children of childrendb_alias='fixture_maker' # If you really need to use a different alias you can.)First use:1. Add a database 'fixture_maker' to your settings file pointing to adatabase with a different name from your default database.  Add"'TEST_MIRROR': 'default'" to the fixture_maker database settingsto prevent the new database from being created during tests.2. Create the database pointed to by alias fixture_maker (This step can be skippedif you're using sqlite, as it will automatically create the database whensync'd)3. Run 'python manage.py syncdb --database=fixture_maker'.*note I've run into some trouble with South, syncdb, and the --databaseflag.  If you're using south, you can work around this:Move your default database, do a 'syncdb --migrate' then renamethe resulting new default database asthe fixture maker database then move your original default database back.4. Pass an iterable containing django model instances to db_sample().This Example will save all the Pizza instances with olive topping to thefixture_maker database with their dependencies and by default children to1 level deep:from db_sampler_script import db_samplep = Pizza.objects.filter(toppings__type='olive')db_sample(p)5. Run 'python manage.py dumpdata --database=fixture_maker > your_new_fixture'Enjoy.Subsequent use:Skip steps 1 & 2, and replace step 3 with:'python manage.py flush --database=fixture_maker'Be careful not to run this command without the --database flag, lestyou erase your entire default database.Assumptions:Primary key for models is obj.id, if you've changed this for some models,please let me know how it blows up.Foreign keys don't form loops (an object reference an object which eventuallyreferences the first).  This is very rarely needed, and many databasesmake it difficult, so if you're not sure don't worry about it.If you have some loops like these and genuinely need them, let me know &I'll update the code to deal with it.Foreign keys that aren't NULL are assumed to be required for databaseconsistency.  At worst this will add some model instances to the resultingfixture that aren't really needed.  Unless someone contacts me aboutthis causing a real problem, it will likely stay like this.
Package: django-db-schema-renderer
Django-db-schema-rendererOverviewThis is a django app to render db schema (ER diagram), of selected models or apps inside django admin panelRequirementsPython 3.7+Django 3.1+django-extensions 3+pygraphviz 1.7+For successful install of pygraphviz you need to have on your host graphviz installed. you can find official docshereOn apple silicon this can be achieved by running command:brewinstallgraphviz
pip3install\--global-option=build_ext\--global-option="-I$(brew--prefixgraphviz)/include/"\--global-option="-L$(brew--prefixgraphviz)/lib/"\pygraphvizInstallationInstall usingpip...pip install django-db-schema-rendererAdddjango_db_schema_rendererto yourINSTALLED_APPSsetting, beforedjango.contrib.admin(make sure you havedjango-extensionsalso added)INSTALLED_APPS=['django_db_schema_renderer','django.contrib.admin',...'django-extensions']Edit the{project_dir}/urls.pymodule in your project:fromdjango_db_schema_renderer.urlsimportschema_urlsurlpatterns=[...path("db-schema/",include((schema_urls,"db-schema"))),...]
Package: django-db-settings
django-db-settings is a Django app to save your configuration in cacheable DB objects that are easily defined like classes.Quick startInstalldjango-db-settingsusingpip:pip install django-db-settingsAdd “settings” to your INSTALLED_APPS setting like this:INSTALLED_APPS = [
    ...
    'settings',
]Include the settings URLconf in your project urls.py like this:path('settings/', include('settings.urls')),Runpython manage.py migrateto create the settings models.Start the development server and visithttp://127.0.0.1:8000/admin/to setup your app settings (you’ll need the Admin app enabled).Visithttp://127.0.0.1:8000/settings/?setting=YOUR_SETTINGto get the objects related to that specific setting (JSON).Find the REFRESH SETTINGS button with in Value model change list page. This project uses TTL based cache, which can be configured by adding the following setting:SETTINGS_CACHE_MAXSIZE: To set the maximum size of total items in the cache. By default set to 100.SETTINGS_CACHE_TTL: To set the Time To Live of the cache items. By default set to 3600 seconds (1 hour).Basic Usagedjango-db-settings saves your settings in a flexible model. To create a setting follow these steps:Create a setting in modelSetting, it will act like the class that will group a set of settings. e.g.,product typeDefine the attributes of thisSettingby adding them in modelField. You can set each as public or private. e.g.,title,description,code.AddSettinginstances in modelInstance. They will act as the objects of the setting class. e.g.,saving,credit card,loan.Finally, add values in modelValuefor every instance guided by the fields defined forSetting. e.g., forsavinginstance, values aretitle: Saving account,description: Saves you money,code: S001.After adding all values, you will be able to retrieve all those which fields are public by going tohttp://127.0.0.1:8000/settings/?setting=product%20type. It returns a JSON object:{“saving”: {“title”: “Saving account”, “description”: “Save your money with us!”}, “credit card”: {“title”: “Credit Card”, “description”: “Get the best from our Credit Card”}, “loan”: {“title”: “Loan”, “description”: “We loan you the money you need”}}TIP: You can use the same settings internally by calling methodget_settingin modulesettings.business:>>> get_setting('product type')
{'saving': {'title': 'Saving account', 'description': 'Save your money with us!'}, 'credit card': {'title': 'Credit Card', 'description': 'Get the best from our Credit Card'}, 'loan': {'title': 'Loan', 'description': 'We loan you the money you need'}}Internally, you can set parameterinclude_non_public=Trueto retrieve private fields also:>>> get_setting('product type', include_non_public=True)
{'saving': {'title': 'Saving account', 'description': 'Save your money with us!', 'code': 'S-001'}, 'credit card': {'title': 'Credit Card', 'code': 'C-001', 'description': 'Get the best from our Credit Card'}, 'loan': {'title': 'Loan', 'description': 'We loan you the money you need', 'code': 'L-001'}}Call methodclear_settings_cachefrom the same package to clear the cache and refresh the global settings.
Package: django-dbshell-plus
Django DB Shell PlusA dbshell_plus management command for Django that selectspgcliormycliwhen available.Free software: BSD licenseDocumentation:http://django-dbshell-plus.rtfd.org.ChangelogHere’s the recent changes to Django DB Shell Plus.version:1.0.1released:2015-08-12tags:generalInitial version, usepgcliormycliwhen available.
Package: django-db-signals
This app adds a set of signals to some of Django’s database operations:django.db.signals.pre_commitdjango.db.signals.post_commitdjango.db.signals.pre_rollbackdjango.db.signals.post_rollbackdjango.db.signals.pre_transaction_managementdjango.db.signals.post_transaction_managementRequirementsPython 2.6/2.7/3.2/3.3 (3.x requires Django >=1.5)Django 1.2/1.3/1.4/1.5InstallationInstall from PyPI:pip installdjango-db-signals.Add'django_db_signals'toINSTALLED_APPS.Enable the signals by adding to yourmodels.py:importdjango_db_signalsdjango_db_signals.enable()ExampleLet’s assume you’ve installed django-db-signals, and now you’d like to log a
message each time the database is rolled back:fromdjango.dbimportsignalsfromdjango.dispatchimportreceiverimportlogginglogger=logging.getLogger(__name__)@reciever(signals.post_rollback)deflog_rollbacks(sender,**kwargs):# sender is a DatabaseWrapper objectlogger.info("A rollback occurred on database%s"%sender.alias)DesignIn the same way that Django settings are available viadjango.conf.settingsattributes, signals are available viadjango.db.signalsattributes. As
such, attempting to import individual signals will fail:>>>importdjango_db_signals>>>django_db_signals.enable()>>>fromdjango.dbimportsignals# GOOD>>>signals.pre_commit<django.dispatch.dispatcher.Signalobjectat0x1089c8b90>>>>fromdjango.db.signalsimportpre_commit# BADTraceback(mostrecentcalllast):File"<stdin>",line1,in<module>ImportError:Nomodulenamedsignalspre_…vspost_…signalspre_…signals are sentbeforean operation occurs. The signals are sent
via.send(…). Exceptions raised in receivers are propagated to the
application. This can be exploited to cancel the operation (e.g. to block a
commit).post_…signals are sentafteran operation, and as such can’t offer the
samecancel the pending operationbehaviour. The signal is sent via.send_robust(…)to ensure all receivers are called. Any exceptions raised
are logged, but are not propagated to the application.LoggingA logger nameddjango.db.signalsis used to log all exceptions raised inpost_…receivers.Signal sendersFor all database signals, the sender of the signal is Django’s database
connection wrapper.Troubleshooting“I can importdjango.db.signals, but when I try to access a signal I get
anAttributeErrorexception.”You need to enable the signals viadjango_db_signals.enable()
Package: django-db-snapshot
Django-Db-Snapshot==================What's that-----------Reusable Django app for fully automatic database snapshots.We are using it for backup big databases (100GB+).App can be run on several instances and managing from one place.Installation------------1. Install backup server with LVM support. Install and configure ``mylvmbackup`` config file.. code-block:: bash$ apt-get install mylvmbackup$ cp /etc/mylvmbackup.conf{,.bak}$ cat > /etc/mylvmbackup.conf << END[mysql]user=rootpassword=123password123socket=/var/run/mysqld/mysqld.sock[lvm]vgname=vg0lvname=mysqllvsize=2GEND2. Install ``dbsnapshot`` using pip:.. code-block:: bash$ pip install django-db-snapshot3. Add the ``dbsnapshot`` application to ``INSTALLED_APPS``4. Configure django-celery on project settings.. code-block:: bash$ apt-get install redis-server$ pip install django-celery.. code-block:: pythonINSTALLED_APPS += ('djcelery',)BROKER_URL = 'redis://127.0.0.1:6379/1'CELERYBEAT_SCHEDULER = 'djcelery.schedulers.DatabaseScheduler'import djcelerydjcelery.setup_loader()5. Sync database (``./manage.py syncdb`` or ``./manage.py migrate``)6. Run internal dbsnapshot server (``./manage.py run_dbsnapshot_server``)7. Restart Redis instance.. code-block:: bash$ /etc/init.d/redis-server restart8. Add backup server and configure backup options on django admin interface (``/admin/dbsnapshot/server/``)9. That's all. Enjoy.Demo----.. code-block:: bash$ apt-get install virtualenvwrapper redis-server$ mkvirtualenv django-db-snapshot$ git clone https://github.com/LPgenerator/django-db-snapshot$ cd django-db-snapshot$ python setup.py develop$ cd demo$ pip install -r requirements.txt$ python manage.py syncdb$ python manage.py migrate$ redis-server >& /dev/null &$ python manage.py runserver >& /dev/null &$ xdg-open http://127.0.0.1:8000/admin/Backup server configuration---------------------------.. code-block:: bash$ sudo -i$ cd /srv/$ apt-get install python-mysqldb python-django python-pip supervisor$ pip install django-db-snapshot$ django-admin startproject dbback$ cd dbback/$ cat >> dbback/settings.py << ENDDATABASES = {'default': {'ENGINE': 'django.db.backends.mysql','NAME': 'mysql','USER': 'root','PASSWORD': '','HOST': 'localhost','PORT': 3306,'TEST_COLLATION': 'utf8_general_ci',}}INSTALLED_APPS += ('dbsnapshot',)DBS_SERVER_HOST = '0.0.0.0'DBS_SERVER_PORT = 61216END$ tail -12 dbback/settings.py$ iptables -A INPUT -p tcp --dport 61216 -j ACCEPT$ python manage.py run_dbsnapshot_server$ cat > /etc/supervisor/conf.d/dbsnapshot.conf << END[program:dbsnapshot_server]command=/usr/bin/python /srv/dbback/manage.py run_dbsnapshot_serveruser=rootnumprocs=1autostart=trueautorestart=truestdout_logfile=/var/log/dbsnapshot.logstderr_logfile=/var/log/dbsnapshot.err.logstartretries=25END$ /etc/init.d/supervisor restart$ supervisorctl statusScreenshots-----------.. image:: /screenshots/server_change_list.jpg.. image:: /screenshots/logs_chage_list.jpgCompatibility:-------------* Python: 2.6, 2.7* Django: 1.4.x, 1.5.x, 1.6.x
Package: django-dbstorage
A Django file storage backend for files in the database.InstallingThe easiest way to installdjango-dbstorageis to usepip:pip install django-dbstorageQuick StartIn your Djangosettingsfile:Add'django-dbstorage'toINSTALLED_APPSSetDEFAULT_FILE_STORAGEto'django_dbstorage.storage.DatabaseStorage'SetMEDIA_ROOTandMEDIA_URLtoNone.Serving filesIn yoururls.py, add the following tourlpatterns:url(r'^media/', include('django_dbstorage.urls'))Or, if you want to specify more options, use:url(r'^media/', include(django_dbstorage.urls.serve()))You should setsettings.MEDIA_URLto the root of this include, in
this case:/media/.If you do not wish to serve files from the database, don’t add
anything tourls.pyand setsettings.MEDIA_URLtoNone.CustomizingDatabaseStoragetakes several options. To customize, subclass
it and use that asDEFAULT_FILE_STORAGE. For instance:class MyDatabaseStorage(DatabaseStorage):
    def __init__(self):
        super(MyDatabaseStorage, self).__init__(location='/tmp',
                                                base_url='/files/',
                                                uniquify_names=True)As a convenience, there is aNonUniquifyingDatabaseStorageclass
which does not attempt to find a unique filename when saving. This
class throws anIOErrorwith theEEXISTSstatus code, when
attempting to_save().This functionality is used by other packages, such asdjango-randomfilenamestorage.
Package: django-db-storage
OverviewWarning: In many cases, storing files in the database is a BAD idea. Your database will easily become bloated and the performance 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 (2.7, 3.4, 3.5)Django (1.8, 1.9)InstallationInstallation using pip:$ pip install django-db-storageUpdatesettings.py# Add 'dbstorage' to INSTALLED_APPSINSTALLED_APPS=['dbstorage',]# Optionally set DEFAULT_FILE_STORAGEDEFAULT_FILE_STORAGE='dbstorage.storage.DBStorage'# Choose a root url for uploaded filesMEDIA_URL='/media/'Updateurls.pyurlpatterns=[...dbstorage_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)Bugs?Create an issue athttps://github.com/derekkwok/django-db-storage/issues
Package: django-db-storage2
django-db-storage2.. image::https://travis-ci.org/derekkwok/django-db-storage.svg?branch=master:target:https://travis-ci.org/derekkwok/django-db-storage.. image::https://coveralls.io/repos/github/derekkwok/django-db-storage/badge.svg?branch=master:target:https://coveralls.io/github/derekkwok/django-db-storage?branch=master.. image::https://badge.fury.io/py/django-db-storage.svg:target:https://badge.fury.io/py/django-db-storageOverviewWarning: In many cases, storing files in the database is a BAD idea. Your database will easily become bloated and the performance can degrade rapidly. See thisStackExchange post_ for more information... _StackExchange post:http://programmers.stackexchange.com/questions/150669/is-it-a-bad-practice-to-store-large-files-10-mb-in-a-databaseThis 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 tests.. image::http://i.imgur.com/4g9tmEZt.png:target:http://i.imgur.com/4g9tmEZ.png.. image::http://i.imgur.com/A2F8xlrt.png:target:http://i.imgur.com/A2F8xlr.pngRequirementsPython (3.5+)Django (1.11.17+)InstallationInstallation using pip::$ pip install django-db-storage2Updatesettings.py.. code-block:: python# Add 'dbstorage' to INSTALLED_APPS
INSTALLED_APPS = [
    'dbstorage',
]

# Optionally set DEFAULT_FILE_STORAGE
DEFAULT_FILE_STORAGE = 'dbstorage.storage.DBStorage'

# Choose a root url for uploaded files
MEDIA_URL = '/media/'Updateurls.py.. code-block:: pythonurlpatterns = [
    ...
    dbstorage_url(),
]Run database migrations::$ python manage.py migrateHow to UseNo modification are needed for models to work properly... code-block:: pythondef user_directory_path(instance, filename):
    return 'user_{0}/{1}'.format(instance.user.id, filename)

class MyModel(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)Bugs?Create an issue athttps://github.com/derekkwok/django-db-storage/issues
Package: django-dbtemplate
With django-dbtemplate your users may override templates from admin interface.
Main purpose of this project - allow admin users to override email templates.InstallationInstall packagepipinstalldjango-dbtemplateAdd “dbtempalte” and “django.contrib.admindocs” to INSTALLED_APPSINSTALLED_APPS=(...'dbtemplate','django.contrib.admindocs',...)Add loader “dbtemplate.loader.DatabaseLoader” to TEMPLATE_LOADERS.For production deployments, always usecached template loaderto awoid unnecessary database queries.
Package: django-dbtemplates
dbtemplatesis a Django app that consists of two parts:It allows you to store templates in your databaseIt providestemplate loaderthat enables Django to load the
templates from the databaseIt also features optional support for versioned storage and django-admin
command, integrates with Django’s caching system and the admin actions.Please seehttps://django-dbtemplates.readthedocs.io/for more details.The source code and issue tracker can be found on Github:https://github.com/jazzband/django-dbtemplates