Saravanan666/pypi-org huggingface dataset:
Package: django-sql-debug
django-sql-debugOutput in the console the executed SQL of queries made by Django's ORM.This is a development tool that should only be used in a local environment and never included in production code.FeaturesPrint executed SQL to the consoleAutomatically runsEXPLAIN ANALYSEAllows for debugging of single query, function, test or the entire applicationWhy not use django-debug-toolbar?Django Debug Toolbaris great if you are developing an html website
using Django. However, since it is focused on displaying the queries using HTML code inject in the webpage it is not
suitable if you are developing a REST API or need to view the queries being run in a unit test. This lib was inspired
by the weakenesses of Django Debug Toolbar on these use cases.Installationpip install django-sql-debugExamplesThere are many ways to use the library. You can set the scope of the debug using one of the examples below.Debugging a small segment of codefrom django_sql_debug import debug_sql


with @debug_sql():
    SomeModel.objects.get(id=5)  # will be captured
SomeModel.objects.get(id=5)  # will not be capturedDebugging a single function or testfrom django_sql_debug import debug_sql


class MyTest(TestCase):
    @debug_sql()
    def test_will_show_executed_sql(self):
        SomeModel.objects.get(id=5)

    def test_will_not_show_executed_sql(self):
        SomeModel.objects.create(name='test')Debugging an entire TestCasefrom django_sql_debug import DebugSQLTestCaseMixin


class MyTest(DebugSQLTestCaseMixin, TestCase):
    def test_will_show_executed_sql(self):
        SomeModel.objects.get(id=5)

    def test_will_also_show_executed_sql(self):
        SomeModel.objects.create(name='test')Debugging an entire applicationAdddjango_sql_debugto theINSTALLED_APPSandMIDDLEWARES.INSTALLED_APPS = [
    'django_sql_debug',

    ...
]

MIDDLEWARE = [
    'django_sql_debug.DebugSQLMiddleware',

    ...
]ConfigurationYou can change some configurations in Django'ssettings.pySQL_DEBUG_ENABLE_PARAMS: Include the SQL parameters section in the debug log (default: True)SQL_DEBUG_ENABLE_PERFORMANCE: Include the SQL performance section in the debug log (default: True)SQL_DEBUG_ENABLE_EXPLAIN: RunEXPLAINcommand on supported databases (default: True)SQL_DEBUG_OUTPUT_STREAM: The output stream to write sql queries and additional sections (default: sys.stdout)SQL_DEBUG_OUTPUT_SIZE: The size of the output headers (default: terminal width)
Package: django-sql-debugger
=====SQL Debugger=====django-sql-debugger is an app that helps controlling number of SQL during your HTTPRequests, including AJAX.Based on custom database backend, it currently supports only MySQL.*Warning: the app currently works under Django 1.6.5 and is not tested against other versions*Quick start-----------1. Add "sql_debugger" to your INSTALLED_APPS setting like this::INSTALLED_APPS = (...'sql_debugger',)2. To turn on SQL Debugger add the following to your settings.py file::SQL_DEBUGGER_SHOW_TRACEBACK = TrueAlso make sure DEBUG is set to True. Do not use this on production server!Usage-----1. To add visualization to your page include SQL Debugger template there::{% include 'sql_debugger/base.html' %}
Package: django-sql-explorer
SQL ExplorerDocumentationSQL Explorer aims to make the flow of data between people fast,
simple, and confusion-free. It is a Django-based application that you
can add to an existing Django site, or use as a standalone business
intelligence tool. It will happily connect to any SQL database thatDjango supports.Quickly write and share SQL queries in a simple, usable SQL editor,
view the results in the browser, and keep the information flowing!SQL Explorer values simplicity, intuitive use, unobtrusiveness,
stability, and the principle of least surprise. Sql Explorer is MIT
licensed, and pull requests are welcome.Some key features include:Support for multiple connectionsQuick access to schema information to make querying easierIn-browser pivot tables (which can also be shared via URLs)Ability to snapshot queries on a regular schedule, capturing changing
dataQuery history and logsQuick in-browser statistics, pivot tables, and scatter-plots (saving
a trip to Excel for simple analyses)Basic code-completion in the SQL editorParameterized queries that automatically generate a friendly UI for
users who don’t know SQLA playground area for quickly running ad-hoc queriesSend query results via emailSaved queries can be exposed as a quick-n-dirty JSON API if desired…and more!ScreenshotsWriting a query and viewing the schema helperViewing all queriesQuery results rendered in browserPivot in browserDevelopmentIncluded is a test_project that you can use to kick the tires. Just
create a new virtualenv, cd intotest_projectand runstart.sh(or
walk through the steps yourself) to get a test instance of the app up
and running.You can now navigate to 127.0.0.1:8000/ and begin exploring!
Package: django-sqlfixtables
Copyright (c) 2009-2012 Dennis Kaarsemaker <dennis@kaarsemaker.net>Inspect your models and database and print Print SQL statements for changes inmodels since the table was created/fixed. Supported changes are:- ALTER TABLE to add/drop columns- ALTER TABLE to change the length of VARCHAR fields- ALTER TABLE to change default values- CREATE INDEX for new ForeignKey and OneToOne fields- CREATE TABLE for new m2m relationsNot (yet) supported:- Databases other than MySQL (sqlite will never be supported, others canpossibly be supported, patches welcome)- Changes in unique_together- Field type changes (they will be detected and warned about though)- Index additions/removals- Deleting old m2m tables- Parent changes in multi-table inheritanceIf you need those, a complete migration framework like django-south is abetter option for you.Install: python setup.py installUsage:- Add 'sqlfixtables' to INSTALLED_APPS- Run: ./manage.py sqlfixtables <appname>Compatible with django 1.0-1.4. Tested only on MySQL, bugreports ortestreports for other databases are welcome.
Package: django-sqlfun
Django SQL FunDjango SQLFun allows you to define and manage custom SQL functions in code. When you change the function definitions and callmakemigrations, it will generate migrations for any functions that have been added, removed, or changed. These function classes can also be used in Django querysets since theSqlFunclass inherits fromdjango.db.models.expressions.Func.Note: I'm still developing this so there may be some rough edges. Breaking changes may happen.InstallationInstall using your favorite python package manager, eg.pip install django-sqlfun.AddsqlfuntoINSTALLED_APPSin your django settingsRunmanage.py migrate. This will set up any tables required bysqlfunto keep track of your custom funcitonsUseDefine a custom function in a module that gets imported on project load (eg.models.py). See below for example, or thetest_project.Runmanage.py makemigrationsRunmanage.py migrateExampleDefine a custom function in yourmodels.py:# models.pyfromsqlfunimportSqlFunfromdjango.db.modelsimportIntegerFieldclassBadSum(SqlFun):"""Almost returns the sum of two numbers."""app_label='test_project'# [optional] if omitted, sqlfun will atempt to auto-resolve itsql="""CREATE OR REPLACE FUNCTION bad_sum(first integer,second integer) RETURNS integer as $$SELECT first + second + 1;$$LANGUAGE sqlstable;"""output_field=IntegerField()Then runmanage.py makemigrationsandmanage.py migrateand you should be good to go. You can use it in SQL:SELECT bad_sum(2, 2), or in a Python queryset like so:MyModel.objects.annotate(foo=BadSum(Value(2), Value(2))).NotesSQL functions are normalized, so changes in white-space should not result in changes being detectedthe--dry-runand--nameoptions ofmakemigrationsare respectedDevelopmentThese instructions assume a recent Ubuntu/Debian environment.Clone the repositoryIf needed, installpython3-venvandpython3-pippackagesCreate a virtual environmentpython3 -m venv .venvInstalllibpq-devpackage sincepsycopg2depends on it.Installpdm:pip3 install --user pdmInstall dev dependencies withpdm install --devTesting also requires a recent install of docker which is used to spin up a test postgres instance.CreditsThis project is inspired by two great projects:django-pgtriggeranddjango-pgviews.
Package: django-sqlite-backup
Django Sqlite BackupA Django application to backup you SQLite database by calling and endpoint.InstallationFrom PYPi usingpip:pip install django-sqlite-backupUsageAdd the app to theINSTALLED_APPS:INSTALLED_APPS = [
    ...,
    "django_sqlite_backup",
    ...,
]Then, add the app's URLs to the root URL conf:path("", include("django_sqlite_backup.urls")),This will create a route in your application to backup your sqlite database:GET /backup/

204: Successful backupWrite your own viewIf you want to use a different method or want to add some sort of authentication or other kinds of logic with the backup call, you can write your own view importing thedo_backupfunction:# views.py
from django.http import HttpRequest
from django.http import JsonResponse

from django_sqlite_backup import backup


def my_view(request: HttpRequest) -> JsonResponse:
    do_backup()
    return JsonResponse({}, status=204)SettingsYou must define your settings in yoursettings.py:SQLITE_BACKUP = {
"BACKUP_CLASS": ...,
"RESTORE_CLASS": ...,
"BUCKET_NAME": ...,
"S3_ENDPOINT": ...,
}BACKUP_CLASSmust point to class which follows theSqliteBackupprotocol.RESTORE_CLASSmust point to class which follows theSqliteRestoreprotocol.BUCKET_NAMEis the name of the bucket in S3 which can be written to.S3_ENDPOINTS3 endpoint override. Leave this blank if you use AWS S3 directly.Management commandsThis app provides two commands for carrying out operations on the backups:backupandrestore../manage.py backupWill back up the current sqlite database into the configured bucket../manage.py restore [date_str]Will restore your sqlite database from your configured bucket on the date specified.
Thedate_stris optional and defaults to today.AWSBy default, the backup class usesboto3to backup the sqlite database into S3. Therefore, you will need to also pass theAWS Environment Variablesto the environment where your application is running.LicenceThis package is distributed underMIT Licence.
Package: django-sqlite-file-cache
django-sqlite-file-cacheA Django cache backend which has a similar API to FileBasedCache, but reduces the number of inodes used.Supports both Python>=v2.7and>=3.4.Installationpip install django-sqlite-file-cacheUsageAdd to your Django CACHESCACHES={'default':{'BACKEND':'django_sqlite_file_cache.SQLiteFileCache','LOCATION':'/var/tmp/django_cache/cache.db',}}EnsureLOCATIONpath is readable/writable by the web server's userSeehttps://docs.djangoproject.com/en/3.1/topics/cache/for more options
Package: django-sql-log-middleware
Django SQL Log MiddlewareA middleware to write Django SQL queries and stats to a jsonl file. Makes analysis easier when you have log files
that are hundreds of megabytes.Inspired by thedjango-sqlprint-middlewareprojectInstallationpip install django-sql-log-middlewareAdd it to the middleware section of settings.py:MIDDLEWARE=[...'django_sql_log_middleware.SqlLogMiddleware',]OutputOutput will be written to the path specified inSQLLOG_LOGin the below format. Each line is a JSON object
covering a single request. Time is the current unix time. Query time is measured in seconds.{"path":"/path/to/api?abc=1234","time":1649301150,"queries":[{"sql":"select * from users","time":1.1234},{"sql":"select * from things","time":4.1234},]}SettingsSpecify the following settings in your settings.py file:DEBUGThis middleware will only run when DEBUG is set.SQLLOG_MIDDLEWAREset this variable toFalsedisable the middleware without removal. Defaults toTrueSQLLOG_PATH_REa regex pattern to only log SQL queries in the matched path(s). Defaults to.*SQLLOG_LOGthe file to write out the logs to. Defaults todjango_queries.jsonlSQLLOG_LOG_POSTlogrequest.POSTdata. Defaults toFalseSQLLOG_LOG_METAlogrequest.METAdata. Defaults toFalseAny outputs that can't be JSON serialized will be rendered as<not serializable>
Package: django-sql-middleware
Django SQL MiddlewareA simple middleware aimed to capture all queries in a request and provide basic SQL profiling such
as execution time, execution plan, and query traceback.This package is only intended to run in development mode for non-sqlite database.Currently, this package only tested in projects that uses psycopg2 (postgres) as default database engine.How To InstallGet the package from pypi:pip install django-sql-middlewareInsettings.pyadd:INSTALLED_APPS = [
    # your other apps
    "sqlmiddleware"
]

MIDDLEWARE = [
    # your other middlewares
]

if DEBUG:
    MIDDLEWARE.append("sqlmiddleware.middlewares.LogSQLMiddleware")Register urls inyour_project/urls.py:from django.urls import include, path

urlpatterns = [
    # other urls,
    path("__sql/", include("sqlmiddleware.urls")),
]Runcollectstaticto serve included css and js assets:./manage.py collectstaticStart the development server:./manage.py runserveryou should be able to accesslocalhost:8000/__sqlin your browser.
Package: django-sqlprint-middleware
Middleware that pretty prints Django’s sql statements.InstallationInstall from PyPI:pip install django-sqlprint-middlewarethen add it to theMIDDLEWAREsettings in yoursettings.pyfile:MIDDLEWARE = (
    ...
    'django_sqlprint_middleware.SqlPrintMiddleware',
    ...
)(UseMIDDLEWARE_CLASSESin older Djangos.)This middleware is not order sensitive so you can put it at any position in
the list of classes.SettingsThe following settings control the behavior (all of these have defaults).DEBUG or TESTINGEither of these need to be True for the middleware to run.SQLPRINT_MIDDLEWARESet to False to skip middleware without removing it.X_DB_HITSSet to false to prevent db hits being sent in the response header ‘X-DB-hits’SQLPRINT_MAX_QUERIESRaise an exception if the number of queries for a view is greater than this.
Default is 1200 (zero means no check).SQLPRINT_MIN_QUERIESFor less output you can set this to the number of queries a view can make before
queries are printed (default is zero).
Package: django-sql-profiler
Django SQL ProfilerProject Description:Django SQL Profiler is a lightweight package inspired by the Sentry SDK. It allows you to effortlessly capture all SQL statements generated by your Django application and store them in MongoDB. To use this package, ensure that you have PyMongo installed.How to Use:Installation:pipinstalldjango-sql-profilerInitialization:Import thesql_profilermodule and call theinstall_sql_hookfunction with the desired configuration options. Example:importsql_profilersql_profiler.install_sql_hook({'slow_queries_threshold':0.2,'app_namespace':['apps.'],'mongodb':{'uri':MONGODB,'db':MONGODB_DB,'collection':'sql_slow_queries'}})Configuration Options:slow_queries_threshold(float): Set the threshold for slow queries in seconds.app_namespace(list): Specify the namespaces of your Django apps to filter SQL statements.mongodb(dict): Configure MongoDB connection details.uri(str): MongoDB connection URI.db(str): MongoDB database name.collection(str): MongoDB collection to store SQL slow queries.Note:Ensure that PyMongo is installed in your environment before using this package.
Package: django-sql-queries
Django SQL QueriesThis project provides a middleware which can be used in django projects to print all SQL queries, their count and execution time
for processed view before returning response for a request.How to use:Install python 3.7 or greater on your system usingpyenvActivate your project's virtual environment for installing this library$source<virtualenv-path>/bin/activateInstall the package by running following command$pipinstalldjango-sql-queriesAdd in the list of middlewares of django projectMIDDLEWARE.append("django_sql_queries.middleware.SQLPrinterMiddleware")
Package: django-sql-sniffer
Django SQL SnifferA simple command line tool for analyzing Django ORM SQL execution from a running process.
Minimally invasive and granular - no need to change the logging config or the source code
of the target process, and no need to restart the process.UsageInstall though pippip install django-sql-snifferRun the tool by passing it the target process iddjango-sql-sniffer -p 76441Ctrl + Cto stop and show the query stats summary. Take a look at a short demo:demoBy default, stats summary shows queries sorted by max duration; the possible options include:-tprint queries in tail mode, i.e. as they are executed-csort stats summary by query count-ssort stats summary by total combined query duration-nset the number of top queries to display in stats summary-vfor verbose logging mode on both the client and server sideif OS supportsSIGINFOsignal pressCtrl + Tto display snapshot stats summary without killing the processHow it worksThe tool is composed out of a client and a server. Runningdjango-sql-snifferstarts the server, which then
injects the client into the running process using GDB/LLDB and waits for it to connect.
The client monkey patches the Django DB cursor and starts streaming queries to the server as they are executed.
The queries are then collected and analyzed on the server side.Finally, when the server gets a shutdown signal, it stops the client which in turn rolls back the monkey patch leaving
the target process in the original state.
Package: django-sql-stacktrace
Pluggable application, which puts a python stack trace in the SQL query as a comment (useful for debugging).For more details seehttp://adw0rd.com/2012/django-sql-stacktrace/en/After installed you can see inprocesslista SQL-query and comment with python stack trace:watch -n1 mysqladmin processlist --verboseOr you can see in a log files, such aslog_slow_queriesorlog-bin(aka ‘binlog’).How to install this wonderful package?Install fromhttp://pypi.python.org/pypi/django-sql-stacktrace/:pip install django-sql-stacktraceOr install the dev-version from GitHub:pip install -e git://github.com/adw0rd/django-sql-stacktrace.git#egg=sqlstacktraceAdd to settings.py:INSTALLED_APPS = (
    'sqlstacktrace',
)

SQL_STACKTRACE = TrueStart runserver or any other server:./manage.py runserver 8000I wish you a successful debugging!
Package: django-sql-utils
Django SQL UtilsThis package provides utilities for working with Django querysets so that
you can generate the SQL that you want, with an API you enjoy.Subquery AggregatesTheCountaggregation in Django:Parent.objects.annotate(child_count=Count('child'))generates SQL like the following:SELECT parent.*, Count(child.id) as child_count
FROM parent
JOIN child on child.parent_id = parent.id
GROUP BY parent.idIn many cases, this is not as performant as doing the count in a SUBQUERY
instead of with a JOIN:SELECT parent.*,
       (SELECT Count(id)
        FROM child
        WHERE parent_id = parent.id) as child_count
FROM parentDjango allows us to generate this SQL using The Subquery and OuterRef classes:subquery = Subquery(Child.objects.filter(parent_id=OuterRef('id')).order_by()
                    .values('parent').annotate(count=Count('pk'))
                    .values('count'), output_field=IntegerField())
Parent.objects.annotate(child_count=Coalesce(subquery, 0))Holy cow! It’s not trivial to figure what everything is doing in the above
code and it’s not particularly good for maintenance. SubqueryAggregates allow
you to forget all that complexity and generate the subquery count like this:Parent.objects.annotate(child_count=SubqueryCount('child'))Phew! Much easier to read and understand. It’s the same API as the originalCountjust specifying the Subquery version.Easier API for ExistsIf you have a Parent/Child relationship (Child has a ForeignKey to Parent), you can annotate a queryset
of Parent objects with a boolean indicating whether or not the parent has children:from django.db.models import Exists

parents = Parent.objects.annotate(
    has_children=Exists(Child.objects.filter(parent=OuterRef('pk'))
)That’s a bit more boilerplate than should be necessary, so we provide a simpler API for Exists:from sql_util.utils import Exists

parents = Parent.objects.annotate(
    has_children=Exists('child')
)The child queryset can be filtered with the keyword argumentfilter. E.g.,:parents = Parent.objects.annotate(
    has_child_named_John = Exists('child', filter=Q(name='John'))
)Thesql_utilversion ofExistscan also take a queryset as the first parameter and behave just like
the DjangoExistsclass, so you are able to use it everywhere without worrying about name confusion.Installation and UsageInstall from PyPI:pip install django-sql-utilsThen you can:from sql_util.utils import SubqueryCountAnd use that as shown above.In addition toSubqueryCount, this package providesSubqueryMinSubqueryMaxSubquerySumSubqueryAvgIf you want to use other aggregates, you can use the
genericSubqueryAggregateclass. For example, if you want to use Postgres’ArrayAggto get an array ofChild.namefor eachParent:from django.contrib.postgres.aggregates import ArrayAgg

aggregate = SubqueryAggregate('child__name', aggregate=ArrayAgg)
Parent.objects.annotate(child_names=aggregate)Or subclass SubqueryAggregate:from django.contrib.postgres.aggregates import ArrayAgg

class SubqueryArrayAgg(SubqueryAggregate)
    aggregate = ArrayAgg
    unordered = True

Parent.objects.annotate(avg_child_age=SubqueryArrayAgg('child__age'))
Package: django-sqlviews
Copyright (c) 2009,2010 Dennis Kaarsemaker <dennis@kaarsemaker.net>
Management command for creating views of multi-table modelsWhen doing multi-table inheritance, it is somewhat annoying that you constantly
need to type INNER JOIN when accessing the data outside the django ORM, for
instance in a database shell or with external applications. This management
commands makes it easy to create views for these models that are simpler to
query.Install: python setup.py install
Usage:
- Add ‘sqlviews’ to INSTALLED_APPS
- Run: ./manage.py sqlviews <appname>Tested only on MySQL, bugreports or testreports for other databases are
welcome.
Package: django-sqs-mq
django-sqs-mq概括Supported Django and Python versionsDjango \ Python3.43.53.63.73.81.11*****2.0*****DocumentationInstallationTo install django-sqs-mq:$pipinstalldjango-sqs-mqUsageIntegrating django-sqs-mq support into your app is a three-step process:create your notice typescreate your notice templatessend notificationsCreating Notice TypesYou need to callNoticeTypeonce to
create the notice types for your application in the database.labelis the internal shortname that will be used for the typedisplayis what the user sees as the name of the notification typedescriptionis a short descriptionFor example:importjsonfromdjango_sqs.launcherimportSqsLauncherkwargs={}kwargs.update({'logs_type':'operate_logs'})SqsLauncher().send_message(json.dumps(**kwargs,ensure_ascii=False))ContributeCode of ConductLicenseCopyright (c) 2018-2020MIT license.
Package: django-squeezemail
Docs to be written soon.Special ThanksBryan Helmig & Zapier for django-drip (https://github.com/zapier/django-drip), which this project is based off of.
Marc Egli’s Pennyblack for inspiration to use feincms in a newsletter.
pmclanahan’s django-celery-email (https://github.com/pmclanahan/django-celery-email) for his clever chunked function with celery.