Saravanan666/pypi-org huggingface dataset:
Package: django-query-analyzer
Django Query AnalyzerDjango Query Analyzer is a Django app that allows you to monitor and analyze the database queries executed by your Django application.InstallationInstall thedjango-query-analyzerpackage using pip:pipinstalldjango-query-analyzerAdd "django_query_analyzer" to yourINSTALLED_APPSsetting in your Django project'ssettings.py:INSTALLED_APPS=[...'django_query_analyzer',]Add "django_query_analyzer.middleware.QueryAnalyzerMiddleware" to your project'sMIDDLEWARElist insettings.py:MIDDLEWARE=[..."django_query_analyzer.middleware.QueryAnalyzerMiddleware",]Register the query analyzer URL patterns in your project'surls.py:fromdjango.urlsimportpath,includeurlpatterns=[...path("query-analyzer/",include("django_query_analyzer.urls")),]Run the following command to create the necessary database tables for the "django_query_analyzer" package:pythonmanage.pymigrateUsageStart your Django development server:pythonmanage.pyrunserverVisit the query analyzer dashboard athttp://127.0.0.1:8000/query-analyzer/in your web browser.ConfigurationBy default, the query analyzer stores the last 50 executed queries. If you want to control this number, you can add theMAX_QUERY_ANALYZER_RECORDSsetting to your project'ssettings.py. For example, to store the last 100 queries, add the following line to your settings.py:MAX_QUERY_ANALYZER_RECORDS=100Logging to TerminalYou can control logging to the terminal by adding theENABLE_LOGGING_TO_TERMINALsetting to your project'ssettings.py. If set toTrue, query analysis details will be printed to the terminal. To disable terminal logging, set it to `False.Example configuration in settings.py:ENABLE_LOGGING_TO_TERMINAL=TrueExcluded PathsYou can configure excluded path by configuring thePATHS_TO_EXCLUDEon thesettings.py.
by adding the list of path prefixes, you can ignore the execution of query analyzer on the paths. By default query analyzer execute on every paths.Example configuration in settings.py:PATHS_TO_EXCLUDE=['/admin/','/swagger/']
Package: django-query-blocker
django-query-blockerPrevents django to perform any query within the context or decorated methodTable of ContentsWhy Should I Use This?How To InstallHow To UseContextDecoratorWhy Should I Use This?Django ORM is great and easy to use but can easily hide some very back behaviours. Just by calling a property here and there you can cascade a chain of hundreds of queries hidden behind the easy-to-use model abstractions. This lib prevents it to happen by locking the ORM not allowing it to perform the queries by raising an exception.How To InstallInstall withpip install django-query-blockerHow To UseIt can be used as a context or decoratorContextfromquery_blockerimportblock_extra_queriesmy_object=MyModel.objects.first()print(my_object)# works finewithblock_extra_queries:print(obj.foreign_key_obj)# will raise a NoExtraQueryExceptionDecoratorfromquery_blockerimportblock_extra_queries@block_extra_queriesdefmy_method(obj):print(obj.foreign_key_obj)my_object=MyModel.objects.first()print(my_object)# works finemy_method(my_object)# will raise a NoExtraQueryException
Package: django-query-builder
django-query-builderquerybuilder is a django library for assisting with the construction and
execution of sql. This is not meant to replace django querysets; it is meant
for managing complex queries and helping perform database operations that
django doesn’t handle.Why use querybuilder?The django querybuilder allows you to control all parts of the query
construction. This is happens more clearly because the function calls more
closely represent the actual sql keywords.Why not just use django’s .raw() function?While the raw function lets you execute custom sql, it doesn’t provide any way
for the developer to build the query dynamically. Users lacking experience
writing “raw” sql should avoid using querybuilder and stick with django’s
querysets. The querybuilder’s query construction closely mirrors writing sql,
where django querysets simplify the sql generation process for simple queries.RequirementsPython 3.7 - 3.9Django 2.2 - 4.1Postgres 9.3+InstallationTo install the latest release, type:pip install django-query-builderTo install the latest code directly from source, type:pip install git+git://github.com/ambitioninc/django-query-builder.gitDocumentationFull documentation is available athttp://django-query-builder.readthedocs.orgLicenseMIT License (see LICENSE)
Package: django-query-builder-pebble
django-query-builderquerybuilder is a django library for assisting with the construction and
execution of sql. This is not meant to replace django querysets; it is meant
for managing complex queries and helping perform database operations that
django doesn’t handle.Why use querybuilder?The django querybuilder allows you to control all parts of the query
construction. This is happens more clearly because the function calls more
closely represent the actual sql keywords.Why not just use django’s .raw() function?While the raw function lets you execute custom sql, it doesn’t provide any way
for the developer to build the query dynamically. Users lacking experience
writing “raw” sql should avoid using querybuilder and stick with django’s
querysets. The querybuilder’s query construction closely mirrors writing sql,
where django querysets simplify the sql generation process for simple queries.RequirementsPython 2.7Python 3.3, 3.4Django 1.6+Postgres 9.3+InstallationTo install the latest release, type:pip install django-query-builderTo install the latest code directly from source, type:pip install git+git://github.com/ambitioninc/django-query-builder.gitDocumentationFull documentation is available athttp://django-query-builder.readthedocs.orgLicenseMIT License (see LICENSE)
Package: django-querycache
django-querycacheCache manager for Django querysets / serializationThis combines Django's cache mechanism, a queryset / model and a serialization format, in order that you don't need to query or serialize data which is (according to either timestamp or MD5 sum of the rows in your query) unchangedFingerprintingThis module takes a Django model, queryset or (app_name, model_name) tuple and generates an 8 character md5 hash of the contents. It caches that hash along with the time the hash was generated using a unique key for each query.TimeStampedFingerprintWhere a model uses a field withauto_nowthis field can be used as an alternative to generating the md5 hash, saving a bit of processor thrashing and i/o. You might want to check that you're using aDateTimeFieldrather than aDateFieldhowever or your cache might be unexpectedly stale.CachedQuerySetTakes a Django model, queryset or (app_name, model_name) tuple and optional params. If aFingerprintinginstance is provided it's used to generate hashes and detect changes; otherwise a Fingerprint instance is generated on init. This allows different cache backends and even different queries to be used for the fingerprint and cache, which is beneficial when there are costly database calls (one example being geographic processing... mvt tiles perhaps?)GeoJsonCachedQuerySetThis is a special form of CachedQuerySet which should generate valid GeoJSON features from a model or queryset. Note that the geometry field is expected to be a GeoJSON field not a geometry field.DevelopmentThis project uses poetry for deplomentOptional (but recommended): Installpre-commitwithpipinstallpre-commit
pre-commitinstallPublishingBump thepyproject.yamlversion numberRunpoetry buildRunpoetry publishAuthYou may need your API token from pypi, or generate onefrom pypi. The api token will start with 'pypi'.poetry publish --build --username __token__  --password pypi-AgE.........QYou may need to be added as a contributor on pypi - if so please ask @joshbrooks to add youTestingFrom the root directory run tests withpoetryrunruntests.pyThis uses the test setting intests. You may wish to set an env variable for a different settings if you want to use a different setup (note tests use the postgis container specified in the github actions)To run the container as specified in the actions, run a postgres container on 49158 with passwordpost1233dockerrun\--rm\-p49158:5432\-ePOSTGRES_PASSWORD="post1233"\postgis/postgis:14-3.2\-cfsync=offGithub ActionsGithub actions run a test suite for code clarity (black, isort, flake8, mypy) as well as the django tests above
Package: django-query-capture
django-query-captureOverviewDjango Query Capture can check the query situation at a glance, notice slow queries, and notice where N+1 occurs.Some reasons you might want to use django-query-capture:It can be used to simply check queries in a specific block.It supports Django Middleware, Context Manager, and Decorator.When you use Context Manager, you can get real-time query data.You can see where the query occurs.Inefficient queries can be found in the test code.It is easy to customize by simply changing the table shape, changing the color, and selecting and setting the desired output.It supports customization that allows you to decorate the output freely from the beginning.Fully DocumentedIt supports Type hint everywhere.Simple UsageJust add it to Middleware without any other settings, and it will be output whenever a query occurs.MIDDLEWARE=[...,"django_query_capture.middleware.QueryCaptureMiddleware",]Use in function-based views. or just functionfromdjango_query_captureimportquery_capture@query_capture()defmy_view(request):passUse in class-based views.fromdjango.utils.decoratorsimportmethod_decoratorfromdjango.views.genericimportTemplateViewfromdjango_query_captureimportquery_capture@method_decorator(query_capture,name='dispatch')classAboutView(TemplateView):passUse it as a context.When used as Context, you can check the query in real time.fromdjango_query_captureimportquery_capturefromtests.news.modelsimportReporter@query_capture()defrun_something():withquery_capture()ascapture:Reporter.objects.create(full_name=f"target-1")print(len(capture.captured_queries))# console: 1Reporter.objects.create(full_name=f"target-2")print(len(capture.captured_queries))# console: 2Use in testTest code can capture inefficient queries through theAssertInefficientQueryUtil.fromdjango.testimportTestCasefromdjango_query_capture.test_utilsimportAssertInefficientQueryclassAssertInefficientQueryTests(TestCase):deftest_assert_inefficient_query(self):withAssertInefficientQuery(num=19):self.client.get('/api/reporter')# desire threshold count 19 but, /api/reporter duplicate query: 20, so raise errorInstallationpipinstall-Udjango-query-captureor install withPoetrypoetryadddjango-query-captureFull DocumentationExtension documentation is found here:https://ashekr.github.io/django-query-capture/.🛡 LicenseThis project is licensed under the terms of theMITlicense. SeeLICENSEfor more details.CreditsThis project was generated withpython-package-template
Package: django-query-chunk
Django Query ChunkDjango Query Chunk is used to split big queries into multiple chunks for prevent (too high) memory usage. The chunk function will split the query set into several isolated queries.RequirementsPython: >=3.6Django: >=2.0Installationpip install django-query-chunkUsagefromquery_chunkimportchunkchunk_size=300forbookinchunk(Book.objects.all(),chunk_size):# process book
Package: django-query-counter
Django Queries CountThe difference between this project and all the others like it is that I needed
to debug management command in Django, but all the others only provided middleware,
which did not solve my problem.Example outputThe basic idea is to count duplicate queries, like django-debug-toolbar does,
and output them. The number of duplicated queries and the color of the theme
can be specified in the settings. It is also possible to output all requests
at once (counted if they are duplicated).ContentInstallationUsageAvailable settingsAdditional screenshotsContributeInstallationIt is enough to install the package and apply the decorator to the desired
management command or view.pipinstalldjango-query-counterUsageThe project can be used in two ways:Import the decorator and apply it where you need to know the number of queries
to the database.management command:fromdjango.core.management.baseimportBaseCommandfromquery_counter.decoratorsimportqueries_counterclassCommand(BaseCommand):@queries_counterdefhandle(self,*args,**options):passfunction-based viewsfromquery_counter.decoratorsimportqueries_counter@queries_counterdefindex(request):passclass-based views:fromdjango.utils.decoratorsimportmethod_decoratorfromquery_counter.decoratorsimportqueries_counter@method_decorator(queries_counter,name='dispatch')classIndexView(View):passspecifying middleware in settings for all views at once.MIDDLEWARE=['query_counter.middleware.DjangoQueryCounterMiddleware',]Available settingsIt is possible to override the default settings. To do this, you need to
include the app to the INSTALLED_APPS:INSTALLED_APPS=[...,'query_counter',...]Default settings:{'DQC_SLOWEST_COUNT':5,'DQC_TABULATE_FMT':'pretty','DQC_SLOW_THRESHOLD':1,# seconds'DQC_INDENT_SQL':True,'DQC_PYGMENTS_STYLE':'tango','DQC_PRINT_ALL_QUERIES':False,'DQC_COUNT_QTY_MAP':{5:'green',10:'white',20:'yellow',30:'red',},}Feel free to override any of them.Tabulate tables formats you can findhere.
Pygments styles availablehere.Additional screenshotsContributeFeel free to open an issue to report of any bugs. Bug fixes and features are
welcome! Be sure to add yourself to the AUTHORS.md if you provide PR.Releasepythonsetup.pysdistbdist_wheel
twinecheckdist/*
twineuploaddist/*
Package: django-query-execfile
# django-query-execfile**Django module for execute sql query in a file**Full documentation for the project is available at []---**Note**:---# Overviewdjango-query-execfile is a simple library for execute .sql query file.Especially# Requirements* Python (2.7.x )* Django (1.5+ )# InstallationInstall using `pip`...```shellpip install django-query-execfile```# Usage & ExampleThis is content of a .sql file```sql#sum_customerPayment_amount_rate_exchanged_group_by_daySELECTDATE(customerPayment.created)                       AS created,SUM(transaction.amount * transaction.exchange_rate) AS amount_exchangedFROM shop_module_customerpayment customerPaymentLEFT JOIN shop_module_transaction transaction ON transaction.id = customerPayment.transaction_idWHERE (customerPayment.created BETWEEN %(from_date)s AND %(to_date)s)GROUP BY DATE(customerPayment.created);```Usage example```pythonfrom models import Orderfrom query_execfile import sql_execfile, raw_queryfileresult = sql_execfile('../datagrip/payment_transaction_stats.sql'),params={'from_date': .., 'to_date': ..},mapResultToDict=True,includeDescription=True)print resultrawQuerySet = raw_queryfile(Order, '../datagrip/order_rawquery.sql')for order in rawQuerySet:doSomeThingWith(order)```**mapResultToDict=True** will map results to a dict with key = first comment above the query.So you can write multiple query in a single file and execute these query at once.**includeDescription=True** will add a extra row at first as column header using description from the query.In this case is _AS created_ and _AS amount_exchanged_**Result return of that example:**```json{"sum_customerPayment_amount_rate_exchanged_group_by_day": [["created","amount_exchanged"],["2016-03-01",4933000.0],["2016-03-02",7144000.0],.........["2016-03-10",2110000.0]],}```# Documentation & Support
Package: django-query-limiter
Ever wanted to limit how many db queries a certain function or view can make?
You're in luck!Get it fromPyPi:pipinstalldjango-query-limiter[formatting]Basic usagefromyour_django_modelsimportModelfromquery_limiterimportlimit_querieswithlimit_queries(1):print(Model.objects.first())# Prints your model's first objectwithlimit_queries(1):print(Model.objects.first())# Prints your model's first objectprint(Model.objects.first())# Raises QueryLimitErrorIt can also be used as a function decorator, and can limit queries on a per-database level:fromyour_django_modelsimportModelfromquery_limiterimportlimit_queries@limit_queries(10,db_connections=['default'])defmy_view(request):returnModel.objects.first()Multiple limits can be specified, and the first one to be reached will raise aQueryLimitExceededexception:fromyour_django_modelsimportModelfromquery_limiterimportlimit_queriesfromdatetimeimporttimedelta@limit_queries(amount=2,individual_max_time=timedelta(milliseconds=100),total_max_time=timedelta(seconds=1),)defmy_view(request):Model.objects.first()# if this query takes more than 100ms -> QueryLimitExceededModel.objects.first()# if the total time of all queries takes more than 1s -> QueryLimitExceededModel.objects.first()# if this query is reached -> QueryLimitExceededYou can globally disable the query limiter:fromyour_django_modelsimportModelfromquery_limiterimportlimit_queries,disable_query_limiterifsettings.ENVIROMENT=='production':disable_query_limiter()withlimit_queries(1):print(Model.objects.first())# Prints your model's first objectprint(Model.objects.first())# Prints your model's first objectThe default behaviour is to limit the connections to all databases. This can be globally overwriten like so:fromquery_limiterimportset_default_databasesset_default_databases(['your_database_name','another_database_name'])Unless the db connections are specified in thelimit_queriesdecorator, these databases will be used.FormattingTheformattingextra:humanizes all timedelta outputsusessqlparseto format the queries to be more human readable
Package: django-query-parameters
django-query-parametersAdds two template tags that simplify the manipulation of GET parameters on a querystring. Allows easy addition, manipulation, and deletion of parameters onto an existing querystring.The module is comprised of two template tags:set_query_parametersanddel_query_parameters.set_query_parametersTakes a 1+ list ofkey=valuepairs and generates an updated querystring that includes those pairs. If a key does not already exist in the querystring, it will be added. If a key exists, it will be updated with the new value. For example:# current page is http://localhost/?page=1&limit=20
{% load query_parameters %}
<a href="?{% set_query_parameters page=2 order=desc %}">...</a>
# => <a href="?page=2&limit=20&order=desc">...</a>del_query_parametersTakes a 1+ list of keys and generates an updated querystring that removes those keys. If a key does not exist in the query string, it will be ignored. For example:# current page is http://localhost/?page=1&limit=20
{% load query_parameters %}
<a href="?{% del_query_parameters page order %}">...</a>
# => <a href="?limit=20">...</a>InstallingInstalling is a simple as running aneasy_installorpip installcommand:pip install django-query-parametersInclude the project in theINSTALLED_APPSlist in your project’ssettings.pyfile:INSTALLED_APPS = (..., 'query_parameters', ...)Storing the output in the template contextBy default, both template tags output the result directly. If an optionalaskey is specified, the results will be stored in a context variable instead. For example:{% set_query_parameters page=2 as=next_page %}
<a href="?{{ next_page }}">Next Page</a>

{% del_query_parameters color size as=reset_filters %}
<a href="?{{ reset_filters }}">Reset Filters</a>Theaskey may be modified in Django’ssettings.pyfile:QUERY_PARAMETERS_VARIABLE_OUTPUT_KEY = 'output'

...

{% set_query_parameters color=red output=next_page %}Using a user defined query stringBy default, both template tags pull the query string from the request context. If an optionalwithkey is specified, the query string will be loaded from the context variable instead. For example:{% set_query_parameters color=red as=filter %}
{% set_query_parameters size=large with=filter as=modified_filter %}
<a href="?{{ modified_filter }}">Apply Filter</a>Thewithkey may be modified in Django’ssettings.pyfile:QUERY_PARAMETERS_VARIABLE_INPUT_KEY = 'input'

...

{% set_query_parameters color=red input=custom_querystring %}
Package: django-query-params
django-query-paramsDjango app providing template tags and JavaScript functions for query string management.Template Tag LibraryTo install the app, type:(venv)$pipinstalldjango-query-paramsThen add"query_params"to theINSTALLED_APPSin the settings.To use the template tags in templates:{% load query_params_tags %}

{% modify_query ["only_query_string"] "param_to_remove" "another_param_to_remove" param_to_change="new-value" another_param_to_change="new-value" %}

{% add_to_query ["only_query_string"] "param_to_remove" "another_param_to_remove" param_to_add="new-value" another_param_to_add="new-value" %}

{% remove_from_query ["only_query_string"] "param_to_remove" another_param_to_remove="value" %}JavaScript Library{% load static %}
<script src="{% static 'query_params/js/query_params.js' %}"></script>

<script>
var url1 = modify_query(
    location, 
    ['param_to_remove', 'another_param_to_remove'], 
    {
        param_to_change: 'new-value',
        another_param_to_change: 'new-value'
    },
    only_query_string=false
);

var url2 = add_to_query(
    location,
    ['param_to_remove', 'another_param_to_remove'],
    {
        param_to_add: 'new-value',
        another_param_to_add: 'new-value'
    },
    only_query_string=false
);

var url3 = remove_from_query(
    location,
    ['param_to_remove'],
    {
        another_param_to_remove: 'value'
    },
    only_query_string=false
);
</script>ExampleLet's say the current URL is:https://example.com/posts/?page=2&sort=by-date&tag=environment&tag=sustainabilitymodify_query{% modify_query "page" tag="ecological" %}will render:/posts/?sort=by-date&amp;tag=ecologicaland{% modify_query "only_query_string" "page" tag="ecological" %}will render:?sort=by-date&amp;tag=ecologicaladd_to_query{% add_to_query "page" tag="ecological" %}will render:/posts/?sort=by-date&amp;tag=ecological&amp;tag=environment&amp;tag=sustainabilityand{% add_to_query "only_query_string" "page" tag="ecological" %}will render:?sort=by-date&amp;tag=ecological&amp;tag=environment&amp;tag=sustainabilityremove_from_query{% remove_from_query "page" tag="environment" %}will render:/posts/?sort=by-date&amp;tag=sustainabilityand{% remove_from_query "only_query_string" "page" tag="environment" %}will render:?sort=by-date&amp;tag=sustainability
Package: django-query-parser
django-query-parserA django app to parse queries written outside the django app.IdeaSome queries are controls the business case, so it will be benefical if they are can saved outside the application like in a config file or a database so the logic can be changed without changing the code.Samplesto write an 'or'{"or":{"status_id":3,"name__icontains":"Ahmed"}}to write negation{"or":{"status_id":3,"~name__icontains":"Ahmed"}}to write an 'and'{"and":{"status_id":3,"name__icontains":"Ahmed"}}or{"status_id":3,"name__icontains":"Ahmed"}Installationpip install django-query-parserExamplefrom test_appfromquery_parser.ParserimportParsed={"or":{"status":"Completed","ordered_by_id":2}}res=Parse(d)print(Order.objects.filter(res).count())Operation SupportedANDORNOT: with a '~' in field name
exampled={"status":"Completed","~ordered_by_id":1}