Saravanan666/pypi-org huggingface dataset:
Package: django-query-prefixer
django-query-prefixerThe Django Query Prefixer allows you to prepend annotations to every query
executed within your Django project. This can be useful for monitoring. By
adding custom prefixes to queries, you can gain insights into their origin,
and can track their performance in a more organized manner.InstallationYou can installdjango-query-prefixerusing pip:pipinstalldjango-query-prefixerUsageChange database engine in yoursettings.pytodjango_query_prefixer.backends.<database backend>.DATABASES={"default":{"ENGINE":"django_query_prefixer.backends.postgresql","HOST":"127.0.0.1","NAME":"postgres","PASSWORD":"postgres","USER":"postgres",}}(Optional) Adddjango_query_prefixer.middlewares.request_routeto theMIDDLEWARElist. This middleware addsrouteandview_nameprefixes to
SQL queries.MIDDLEWARE=["django_query_prefixer.middlewares.request_route",# ...]Now, whenever queries are executed in your Django project, the configured prefixes
will be automatically added to those queries. For example, a query like this:User.objects.filter(username='bob')will be executed as:/* view_name=example route=/example */SELECT...FROM"auth_user"WHERE("auth_user"."username"='bob')You can add additional context to queries using thesql_prefixescontextmanager:fromdjango_query_prefixerimportsql_prefixeswithsql_prefixes(user_id=request.user.id,foo="bar"):User.objects.filter(username='bob')/* user_id=X foo=bar view_name=example route=/example */SELECT...FROM"auth_user"WHERE("auth_user"."username"='bob')ContributingContributions todjango-query-prefixerare welcome! If you find a bug, want to
add a new feature, or improve the documentation, please open an issue or submit
a pull request in the GitHub repository.
Package: django-query-profiler-Georgia
Django Query ProfilerDjango Query Profiler is a utility that profiles SQL queries made by Django ORM, providing insights into their performance and suggesting optimizations. This package is particularly useful for developers who want to improve the efficiency of their database interactions, focusing on the Django admin interface.FeaturesAutomatically profiles SQL queries made in the Django admin sectionSaves query profiles to a database table with execution time and timestampProvides an admin interface for viewing, searching, and analyzing query profilesInstallationTo install Django Query Profiler, simply run:pip install django-query-profilerUsageUpdate your Django project's settings.py file to include the QueryProfilerMiddleware and register the django_query_profiler app.Add the middleware to the MIDDLEWARE setting:MIDDLEWARE = [
...
'django_query_profiler.middleware.QueryProfilerMiddleware',
...
]Include 'django_query_profiler' in the INSTALLED_APPS setting:INSTALLED_APPS = [
...
'django_query_profiler',
...
]Run the following commands in your project's root directory to create the necessary QueryProfile table in the database:python manage.py makemigrations django_query_profiler
python manage.py migrateOnce the package is installed and configured, the Django Query Profiler will automatically start profiling SQL queries made in the admin section. Each query will be stored as a QueryProfile record in the database, including the SQL query, execution time, and timestamp.Access the query profiles in the Django admin interface by navigating to /admin/django_query_profiler/queryprofile/. From there, you can view, search, and analyze the query profiles to identify performance bottlenecks and potential optimizations.LicenseThis project is licensed under the MIT License. See the LICENSE file for details.
ContributingContributions are welcome! Please feel free to submit issues or pull requests.
Package: django-queryset-constraint
Django Queryset ConstraintThis library enables one to write reliable data invariants, by compiling Django
Querysets to database insert/update triggers, via. the migration system.MotivationDjango has a built-in signal system, which emits signals on various events, for
instance model creations, updates and deletions. However these signals are not
emmited for queryset operations, and as such cannot be used to maintain data
invariants.An attempt to ratify this was made with theDjango Queryset Signalslibrary.
While this library comes closer to a reliable solution, it does not succeed,
as it is stil possible to break the data invariants by accessing the database
directly.Database Constraint Triggers will effectively protect against all scenarios.Installationpip install django_queryset_constraintUsageAdd thedjango_queryset_constraintapp toINSTALLED_APPS:# settings.py
INSTALLED_APPS = {
    'django_queryset_constraint',
    ...
}Note: This should be donebeforeany apps that will be checkedAddQuerysetConstrainttoconstraintsto the Meta class of the models to checked:# models.py
from django.db import models
from django.db.models import Count
from django_queryset_constraint import M, QuerysetConstraint


class Topping(models.Model):
    name = models.CharField(max_length=30)


class PizzaTopping(models.Model):
    class Meta:
        unique_together = ("pizza", "topping")
        constraints = [
            # A pizza with more than 5 toppings gets soggy
            QuerysetConstraint(
                name='At most 5 toppings',
                queryset=M().objects.values(
                    'pizza'
                ).annotate(
                    num_toppings=Count('topping')
                ).filter(
                    num_toppings__gt=5
                ),
            ),
            # This constraint should be self-explanatory for civilized people
            QuerysetConstraint(
                name='No pineapple',
                queryset=M().objects.filter(
                    topping__name="Pineapple"
                )
            ),
        ]

    pizza = models.ForeignKey('Pizza', on_delete=models.CASCADE)
    topping = models.ForeignKey(Topping, on_delete=models.CASCADE)

class Pizza(models.Model):
    name = models.CharField(max_length=30)
    toppings = models.ManyToManyField(Topping, through=PizzaTopping)Make migrations:python manage.py makemigrationsRun migrations:python manage.py migrateNote: Complex triggers introduce performance overhead.Support MatrixThis app supports the following combinations of Django and Python:DjangoPython2.23.6, 3.7
Package: django-queryset-iterator
Queryset Iterator ReadMe========================General-------Queryset Iterator is a tool that is useful for iterating over large data-setsin Django.Queryset Iterator iterates over large data-sets in batches, which can bemanually set to any batch size of your choosing, to improve performance.The iterator maintains an open database cursor to a median table containingonly the primary keys of the results that would normally be obtained. Due tothis, primary keys must be unique within the collection and this tool willnot work should primary keys be non-unique within the database query results.
Package: django-querysetsequence
django-querysetsequence adds helpers for treating multiple disparateQuerySetobejcts as a singleQuerySet. This is useful for passing into APIs that only
accepted a singleQuerySet.TheQuerySetSequencewrapper is used to combine multipleQuerySetinstances.OverviewQuerySetSequenceaims to provide the same behavior as Django’sQuerySets,
but applied across multipleQuerySetinstances.Supported features:Methods that take a list of fields (e.g.filter(),exclude(),get(),order_by()) must use fields that are common across all
sub-QuerySets.Relationships across related models work (e.g.'foo__bar','foo', or'foo_id'). syntax).The sub-QuerySetsare evaluated as late as possible (e.g. during
iteration, slicing, pickling,repr()/len()/list()/bool()calls).PublicQuerySetAPI methods that are untested/unimplemented raiseNotImplementedError.Getting StartedInstall the package using pip.pipinstall--upgradedjango-querysetsequenceBasic Usage# Import QuerySetSequencefromqueryset_sequenceimportQuerySetSequence# Create QuerySets you want to chain.from.modelsimportSomeModel,OtherModel# Chain them together.query=QuerySetSequence(SomeModel.objects.all(),OtherModel.objects.all())# Use query as if it were a QuerySet! E.g. in a ListView.Project Informationdjango-querysetsequence is released under the ISC license, its documentation lives
onRead the Docs, the code onGitHub, and the latest release onPyPI. It
supports Python 3.7+, Django 3.2/4.0/4.1/4.2, and is optionally compatible withDjango REST Framework3.11+.Some ways that you can contribute:Check for open issues or open a fresh issue to start a discussion around a
feature idea or a bug.Fork the repository on GitHub to start making your changes.Write a test which shows that the bug was fixed or that the feature works as
expected.Send a pull request and bug the maintainer until it gets merged and published.
Package: django-query-signals
Django Query SignalsWhat is it?A library that will send signals on queryset data manipulation methods.What problem does it solve?Django sends many signals, including when a model instance is created, deleted
and updated. However when using bulk methods like bulk_create or delete. There
is no signal send, with this library signals are send on the following methods:bulk_createdeleteget_or_createupdate_or_createupdateA signal will be send before and after the method is executed.How do I install it?pipinstalldjango-query-signalsAdding to Django (using integrator)>>>importdjango_integrator>>>django_integrator.add_application('django_query_signals')If you don’t want to use the above, you can just add ‘django_query_signals’ to
your installed apps.How do I use it?From the namespace django_query_signals you can import the below signals which
you can connect to via the usual way.pre_bulk_createpost_bulk_create,pre_deletepost_deletepre_get_or_createpost_get_or_createpre_update_or_createpost_update_or_createpre_updatepost_updateFor example:>>>@receiver(post_bulk_create)>>>defcallback(signal,sender,args):>>>passThe argument ‘signal’ is the signal that is connected, ‘sender’ is the
underlying model class and ‘args’ is a dictionary which the method in queryset
is called with, this is supplemented with ‘self’ which contains the queryset
instance and if the connecting signal is a ‘post’ type the key ‘return’ is also
added which contains the value the method has returned.If you connect to the ‘pre’ type signal, changing the ‘args’ and ‘self’ will
also change the actual execution of the method.CaveatThis library relies on monkey patching django.db.models.query.QuerySet, thus if
your instance also monkey patches the same thing or you use a custom QuerySet in
your Manager, then there is a good chance that this library will not work at all
for you, however most likely you can work around this issue by examining the
signals.py file in this library.What license is this?Two-clause BSDHow can I get support?Please use the repo’s bug tracker to leave behind any questions, feedback,
suggestions and comments. I will handle them depending on my time and what looks
interesting. If you require guaranteed support please contact me via
e-mail so we can discuss appropriate compensation.Signing OffIs my work helpful or valuable to you? You can repay me by donating via:https://paypal.me/MartinHellwig-or-https://www.patreon.com/hellwigThank you!
Package: django-query-tools
django-query-toolsTools for building queries in Django.Setup$ pip install django-query-toolsTo use theservermodule, Django must also be installed:$ pip install djangoUsage# script.pyfromdjango_query_tools.clientimportFfromdjango_query_tools.serverimportmake_atoms,make_queryfromdjango.db.modelsimportQ# --- CLIENT ---# Define x and y fieldsx=F(x="hello")print("F object for x:",x)print("Data:",x.query)y=F(y="goodbye")print("F object for y:",y)print("Data:",y.query)# Form a query from x and yquery=x&~yprint("Query F object:",query)print("Client sends data:",query.query)# --- SERVER ---# Server receives querydata=query.queryprint("Server receives data:",data)# Modifies data in-place, creating QueryAtom keyvalue pairs# Returns these QueryAtom objects for validationatoms=make_atoms(data)print("QueryAtom structure:",data)print("QueryAtom objects:",atoms)# Builds Django Q object from the QueryAtom objectsformed=make_query(data)expected=Q(x="hello")&~Q(y="goodbye")print("Formed Q object:",formed)print("Expected Q object:",expected)print("These objects represent the same query:",formed==expected)$ python script.py
F object for x: <django_query_tools.client.F object at 0x1012f1910>
Data: {'x': 'hello'}
F object for y: <django_query_tools.client.F object at 0x1012f1990>
Data: {'y': 'goodbye'}
Query F object: <django_query_tools.client.F object at 0x1012f3510>
Client sends data: {'&': [{'x': 'hello'}, {'~': {'y': 'goodbye'}}]}
Server receives data: {'&': [{'x': 'hello'}, {'~': {'y': 'goodbye'}}]}
QueryAtom structure: {'&': [{'x': <django_query_tools.server.QueryAtom object at 0x1012f1a10>}, {'~': {'y': <django_query_tools.server.QueryAtom object at 0x1023b1890>}}]}
QueryAtom objects: [<django_query_tools.server.QueryAtom object at 0x1012f1a10>, <django_query_tools.server.QueryAtom object at 0x1023b1890>]
Formed Q object: (AND: ('x', 'hello'), (NOT (AND: ('y', 'goodbye'))))
Expected Q object: (AND: ('x', 'hello'), (NOT (AND: ('y', 'goodbye'))))
These objects represent the same query: True
Package: django-query-to-table
django-query-to-table is an easy to use django package to generate html table from sql query.You can read more about this package here :django query to tableThe package contains one function named "generateFromSql" accepting 12 arguments :cursor : DB cursortitle : The title of the report that will be shown on top of tablesqltext : The sql select query to retrieve datafooterCols : A list of columns name that you want to have Sum of values on footer . Example : ['amount','price']htmlClass : Html CSS classes for the tabledirection (default = "ltr") : Indicates direction of the report page.  "ltr"- Left to Right , "rtl" -  Right to Leftfont (default = "Tahoma") : Font of title and table contentstotalText (default = "Total") : Title of footer row that will be the put below the first column.rowIndex (default = False) : Indicates whether the table should have index column or not.headerRowColor (default = '#eeeeee') :  The header (title) row background color.evenRowColor (default = '#ffffff') :  The even rows background color.oddRowColor (default = '#ffffff') :  The odd rows background color.InstallationTo install django-query-to-table using pip :pipinstalldjango-query-to-tableUsage :fromdjango.dbimportconnectionfromdjango_query_to_tableimportDjangoQttfromdjango.httpimportHttpResponse# view function in Django projectdeflistOfPersons(request):cursor=connection.cursor()reportTitle="Employee List"sqlQuery="SELECT FirstName as 'First Name', LastName as 'Last Name', phone as 'Phone Number', salary as 'Salary' FROM persons"columnsToBeSummarized=['Salary']fontName="Arial"cssClasses="reportTable container"headerRowBackgroundColor='#ffeeee'evenRowsBackgroundColor='#ffeeff'oddRowsBackgroundColor='#ffffff'table=DjangoQtt.generateFromSql(cursor,reportTitle,sqlQuery,columnsToBeSummarized,cssClasses,"ltr",fontName,"Total Salary",True,headerRowBackgroundColor,evenRowsBackgroundColor,oddRowsBackgroundColor)# table is a string variable contianing the html table showing the query resultreturnHttpResponse(table)
Package: django-query-utils
PostgreSQL locksDjango already exposes row-level locks withQuerySet.select_for_update()method.
What's missing is table-level and advisory locks:fromdjango_query_utils.postgres.locksimporttable_lock,LockModewithtable_lock("auth_user","auth_group",mode=LockMode.Exclusive,timeout=10):""" Perform some esclusive operations on locked tables """# Set a lock for Django model tablesfromdjango.contrib.authimportmodelswithtable_lock.for_model(models.User,models.Group,**kwargs):...Advisory locks supportfromdjango_query_utils.postgres.locksimportadvisory_locklock_id=42withadvisory_lock(lock_id,using="default",nowait=True):""" Perform some actions with locked resources """# Create a more meaningful lock.# Postgres spports either a single `bigint` or (`int`, `int`) pair as a lock_id.# `advisory_lock` tries to convert any strings (or bigger ints) to postgres format# either with hashing and bit shifts.fromdjango.dbimporttransactionfromdjango.contrib.auth.modelsimportUseruser=User.objects.get(id=42)withtransaction.atomic(),advisory_lock("user:act",user.id,timeout=10):""" Perform some actions with locked resources.Timeout is only awailable within a transaction block. """PostgreSQL full-text search support fordjango-filterfromdjango_query_utils.postgres.filtersimportFullTextSearchFilterclassMyFilterSet(django_filters.FilterSet):search=FullTextSearchFilter(vector=("field_1","field__subfield"),# or `SearchVector` instancesearch_type="phrase",config="french",)Withsearch_type="custom"you may pass custom query expressionsclassMyFilterSet(django_filters.FilterSet):search=FullTextSearchFilter(vector=("first_name","last_name","email"),# or `SearchVector` instancesearch_type="custom",)qs=User.objects.all()filters=MyFilterSet({"search":"(John | Mike | Dan) Doe"},qs)Raw Query wrappers:fromdjango_query_utilsimportQuery,query_contextquery=Query("select first_name, last_name from auth_user where email =%(email)s",{"email":"jdoe@example.com"})withquery_context(using="default")asc:results=list(c.execute(query))assertresults==[{"first_name":"John","last_name":"Doe"}]Different result materializers:fromdjango_query_utilsimportPlainMaterializer,Query,query_contextquery=Query("select first_name, last_name from auth_user where email =%(email)s",{"email":"jdoe@example.com"},materializer=PlainMaterializer(),)withquery_context(using="default")asc:results=list(c.execute(query))assertresults==[("John","Doe")]More sophisticated transformers to kwarg classes:fromdataclassesimportdataclass@dataclassclassMyUser:first_name:strlast_name:strwithquery_context()asc:results=c.execute(query.as_type(MyUser))assertlist(results)==[MyUser(first_name="John",last_name="Doe")](PostgreSQL only)psycopg2.sqlquery formatting support:frompsycopg2importsqlraw_q=sql.SQL("select first_name, last_name from auth_user where email ={}")query=Query(raw_q.format(sql.Literal("jdoe@example.com")))...
Package: django-query-view
Django view for querying dataInstallationTo get the latest stable release from PyPipipinstalldjango-query-viewUsageSet up modelsfromdjango.dbimportmodelsfromtaggit.managersimportTaggableManagerfromtaggit.modelsimportTaggedItemBasefromquery_view.modelsimportTypedTagfromquery_view.modelsimportmake_typed_tag_tagged_modelclassTaggedThing(TaggedItemBase):content_object=models.ForeignKey('Thing',on_delete=models.CASCADE)classThing(models.Model):name=models.CharField(max_length=200)is_good=models.BooleanField()tags=TaggableManager(through=TaggedThing,blank=True)def__str__(self):returnself.name# Subclass TypedTagclassActorTypedTag(TypedTag):pass# Create your tagged model like thisActorTaggedThing=make_typed_tag_tagged_model('ActorTaggedThing',ActorTypedTag,Thing,app_label='testproject')# Or like thisclassActorTaggedThing(TaggedItemBase):typed_tag=models.ForeignKey(ActorTypedTag,related_name="%(app_label)s_%(class)s_items",on_delete=models.CASCADE,)content_object=models.ForeignKey(Thing,on_delete=models.CASCADE)classMeta:unique_together=['typed_tag','content_object']Create a typed tagged itemt=Tag.objects.get(name='clint eastwood')ActorTaggedThing.objects.create(content_object=thing,typed_tag=t.actortypedtag)Run the test projectpythonmanage.pymigratepythonmanage.pyloaddatatestproject/fixtures/tag_thing.jsonpythonmanage.pyrunserverDump fixturepythonmanage.pydumpdata--indent4testproject.Thingtestproject.TaggedThingtaggit.Tagtestproject.LanguageTypedTagtestproject.LanguageTaggedThingtestproject.DirectorTypedTagtestproject.DirectorTaggedThingtestproject.ActorTypedTagtestproject.ActorTaggedThing--outputtestproject/fixtures/tag_thing.json
Package: django-question
=====Question=====Polls is a simple Django app to conduct Web-based polls. For eachquestion, visitors can choose between a fixed number of answers.Detailed documentation is in the "docs" directory.Quick start-----------1. Add "polls" to your INSTALLED_APPS setting like this::INSTALLED_APPS = [...'question',]2. Include the polls URLconf in your project urls.py like this::url(r'^api/v1/', include('question.api.urls')),3. Run `python manage.py migrate` to create the polls models.4. Start the development server and visit http://127.0.0.1:8000/admin/to create a poll (you'll need the Admin app enabled).
Package: django-questionnaire-core
django-questionnaire-coreA django application which can be used as a base / starting point for questionnaire functionality in your project.
It heavily relies on django form fields & widgets and uses JSON fields to store the results.RequirementsPython version 3.8+Djangoversion 3.2+django-ordered-modelAPostgreSQLDatabase (optional since Django 3.2)Quick startAdd "questionnaire_core" and its dependency to your INSTALLED_APPS setting like this:INSTALLED_APPS = [
    ...
    'ordered_model',
    'questionnaire_core',
]Create a view based onquestionnaire_core.views.generic.QuestionnaireFormView; a simple version might look like this:fromdjango.httpimportHttpResponseRedirectfromdjango.urlsimportreversefromdjango.utils.httpimporturlencodefromquestionnaire_core.modelsimportQuestionnaire,QuestionnaireResultfromquestionnaire_core.views.genericimportQuestionnaireFormViewclassBasicQuestionnaireView(QuestionnaireFormView):template_name='basic_questionnaire.html'defget_questionnaire(self):returnQuestionnaire.objects.get(pk=self.kwargs.get('pk'))defget_questionnaire_result_set(self):ifself.request.GET.get('result_set'):returnQuestionnaireResult.objects.get(pk=self.request.GET.get('result_set'))returnQuestionnaireResult(questionnaire=self.get_questionnaire())defget_success_url(self):returnreverse('basic_questionnaire',args=(self.kwargs.get('pk'),))defform_valid(self,form):# Add current result set to the url (allows editing of the result)redirect=super().form_valid(form)url_params=urlencode({'result_set':form.current_result_set.pk})returnHttpResponseRedirect('{url}?{params}'.format(url=redirect.url,params=url_params))Add the new view to your URLconf:path('questionnaire/<int:pk>/', BasicQuestionnaireView.as_view(), name='basic_questionnaire'),Runpython manage.py migrateto create the questionnaire_core models.Start the development server and visithttp://127.0.0.1:8000/admin/to create a questionnaire (you'll need the Admin app enabled).Visithttp://127.0.0.1:8000/questionnaire/1/to test your first questionnaire.Development setupUpgrade packaging tools:python-mpipinstall--upgradepip
python-mpipinstall--upgradesetuptoolswheelInstall Django (theexample_appexpects django 3.2):python-mpipinstallDjango~=3.2.0django-ordered-modelpsycopg2Install tox, isort & flake8python-mpipinstalltoxisortflake8
Package: django-queued-storage
This storage backend enables having a local and a remote storage
backend. It will save any file locally and queue a task to transfer it
somewhere else usingCelery.If the file is accessed before it’s transferred, the local copy is
returned.Installationpip install django-queued-storageConfigurationFollow the configuration instructions fordjango-celerySet up acaching backendAdd'queued_storage'to yourINSTALLED_APPSsetting
Package: django-queue-health
Django Queue HealthSimple django app for checking queue health. Targeted to be used for Kubernetes deployments to periodically scheduleupdate_queue_timestampand set timestamp and verified bytest_queue_healthas a probe to verify if worker works and is not stucked.For an up to date and maintained version of this library, please checkoutgitlab.comInstallationUsing pip:pipinstalldjango-queue-healthFrom git:pipinstallgit+https://gitlab.com/adaptiware/django-queue-health.gitUsageAdd "queuehealth" to your INSTALLED_APPS setting like this:INSTALLED_APPS=[...,'queuechecker',]Add variable "DQH_TRESHOLD" to your settings like this:# Minutes treshold to check if there is queue log and if queue is runningDQH_TRESHOLD=10Configure defaultdjango cache.Queue Health usedjango rqorcelery.Use commands:# Push job to queue that updates the timestamppythonmanage.pyupdate_queue_timestamp# Check if timestamp in cache less than trasholdpythonmanage.pytest_queue_health