Saravanan666/pypi-org huggingface dataset:
Package: django-pgcrypto
django-pgcryptoA set of utility functions for dealing with ASCII Armor (http://www.ietf.org/rfc/rfc2440.txt) and padding, and a collection of Django field classes that utilize these functions in a way that is compatible with pgcrypto functions.Installationpip install django-pgcryptoQuickstartThere are several encrypted versions of Django fields that you can use (mostly) as you would use a normal Django field:fromdjango.dbimportmodelsimportpgcryptoclassEmployee(models.Model):name=models.CharField(max_length=100)ssn=pgcrypto.EncryptedTextField()pay_rate=pgcrypto.EncryptedDecimalField()date_hired=pgcrypto.EncryptedDateField(cipher="bf",key="datekey",auto_now_add=True)If not specified when creating the field (as inssnandpay_rateabove), fields are encrypted according to the following settings:PGCRYPTO_DEFAULT_CIPHER(aesorbf, default:aes) - The default algorithm to use when encrypting fields.PGCRYPTO_DEFAULT_KEY(default:settings.SECRET_KEY) - The default key to use for encryption.You must also make sure the pgcrypto extension is installed in your database. Django makes this easy with aCryptoExtensionmigration.QueryingIt is possible to filter on encrypted fields as you would normal fields viaexact,gt,gte,lt, andltelookups. For example, querying the model above is possible like so:Employee.objects.filter(date_hired__gt="1981-01-01",salary__lt=60000)CaveatsThis library encrypts and encodes data in a way that works with pgcrypto'sraw encryption functions. All the warnings there about using direct keys and the lack of integrity checking apply here.This library also predates Django'sBinaryField, which is why the fields are essentiallyTextFields that store armored encrypted data. This may or may not be ideal for your application, and a hypothetical future version might include a switch to store binary data.
Package: django-pgcryptoauth
Django hasher for PostgreSQL pgcrypto encoded passwords.django-pgcryptoauthis a custom Django password hasher which is intended to provide authentication continuity for legacy passwords that were encrypted with the Postgres pgcrypto extension.Since we don’t have access to the cleartext passwords, we instead just make Django understand and handle the legacy algorithm. When a user successfully logs in, Django will automatically upgrade the password to the preferred algorithm.Source codehttps://github.com/tomatohater/django-pgcryptoauthDependenciesOf course, you will need to be using a PostgreSQL database with thepgcryptoextension installed.InstallationInstall thedjango-pgcryptoauthpackage:pip install django-pgcryptoauthAddpgcryptoauthto yourINSTALLED_APPS:INSTALLED_APPS = (
    ...
    'pgcryptoauth',
    ...
)Addpgcryptoauth.hashers.PgCryptoPasswordHashertoPASSWORD_HASHERSin your Django settings:PASSWORD_HASHERS = (
    ...
    'pgcryptoauth.hashers.PgCryptoPasswordHasher',
)Note: This hasher should probably at the bottom of the list so that other hashers take priority. Seehttps://docs.djangoproject.com/en/dev/topics/auth/passwords/ConfigurationBy default,pgcryptoauthwill use yourdefaultdatabase connection. However, you may instruct it to use another connection by settingPGCRYPTOAUTH_DATABASEto something else in your Django settings.:PGCRYPTOAUTH_DATABASE = 'another_database'Of course, this other connection must be a valid Postgres database with the pgcrypto extension and listed in yourDATABASESsetting:DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'my_database',
        'USER': 'my_user',
        'PASSWORD': 'my_pass',
        'HOST': '127.0.0.1',
        'PORT': '',
    },
    'another_database': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'another_database',
        'USER': 'another_user',
        'PASSWORD': 'another_pass',
        'HOST': '127.0.0.1',
        'PORT': '',
    }
}This may be necessary if the pgcrypto extension is not (or can’t be) installed on your primary database. Especially if your primary database is not PostgreSQL!Running test casesExecute the unit test:python manage.py test pgcryptoauthLoading legacy dataNote: Legacy pgcrypto hashed passwords look like$1$BFw5nhna$XeiE8c4FInYGp3oND2l9n1. When migrating these passwords, we simply need to prefix the hash with thepgcrypto$algorithm:user.password = 'pgcrypto$$1$BFw5nhna$XeiE8c4FInYGp3oND2l9n1'
user.save()If you review that users password via the Djangoauth.useradmin, you should see:algorithm: pgcrypto
hash: $1$BFw******************************************Historyv0.3 - Adds Python 3 support, supports Django 1.8+.
Package: django-pgcrypto-expressions
Django model fields whose values are encrypted using thepgp_sym_encryptfunction frompgcrypto.django-pgcrypto-expressionssupportsDjango1.8.2 and later on Python
2.7, 3.2, 3.3, 3.4, pypy, and pypy3.Getting HelpDocumentation for django-pgcrypto-expressions is available athttps://django-pgcrypto-expressions.readthedocs.org/This app is available onPyPIand can be installed withpip installdjango-pgcrypto-expressions.ContributingSee thecontributing docs.CHANGES0.1 (2015.05.27)Initial working version.
Package: django-pg-ddl-extras
django-pg-ddl-extrasA tiny library that implements declarative postgres function definitions for Django.RequirementsPython >= 3.7Django >= 3.2UsageIn the below example, we create a function that is run as part of a constraint trigger.fromdjango_pg_ddl_extrasimport(PostgresTriggerFunctionDefinition,ConstraintTrigger,TriggerEvent,)fromdjango.dbimportmodelsfromdjango.db.models.constraintsimportDeferrable# Write a custom constraint in SQL# In order to get picked up by the migration engine, we include the function definition# as part of the class `Meta.constraints` list.# Unfortunately, Django does not seem to have a cleaner way to define this yet.custom_function=PostgresTriggerFunctionDefinition(name="my_function",body="""DECLAREBEGINIF (TG_OP = 'DELETE') THENRETURN OLD;END IF;IF NOT FOUND THENRAISE EXCEPTION'This is an example constraint error'USING ERRCODE = 23514;END IF;RETURN NEW;END;""",)classMyModel(models.Model):classMeta:constraints=[custom_function,ConstraintTrigger(name="my_trigger",events=[TriggerEvent.UPDATE,TriggerEvent.INSERT,TriggerEvent.DELETE],deferrable=Deferrable.DEFERRED,function=custom_function.as_func(),),]
Package: django-pghistory
django-pghistorydjango-pghistorytracks changes to your Django models usingPostgres triggers, providing:Reliable history tracking everywhere with no changes to your application code.Structured history models that mirror the fields of your models.Grouping of history with additional context attached, such as the logged-in user.django-pghistoryhas a number of ways in which you can configure history tracking for your application's needs and for performance and scale. An admin integration and middleware is included out of the box too.Quick StartDecorate your model withpghistory.track. For example:importpghistory@pghistory.track()classTrackedModel(models.Model):int_field=models.IntegerField()text_field=models.TextField()Above we've trackedTrackedModel. Copies of the model will be stored in a dynamically-created event model on every insert and update.Runpython manage.py makemigrationsfollowed bymigrateandvoila, every change toTrackedModelis now stored. This includes bulk methods and even changes that happen in raw SQL. For example:frommyapp.modelsimportTrackedModelm=TrackedModel.objects.create(int_field=1,text_field="hello")m.int_field=2m.save()print(m.events.values("pgh_obj","int_field"))>[{'pgh_obj':1,'int_field':1},{'pgh_obj':1,'int_field':2}]Above we printed the history ofint_field. We also printedpgh_obj, which references the tracked object. We'll cover how these fields and additional metadata fields are tracked later.django-pghistorycan track a subset of fields and conditionally store events based on specific field transitions. Users can also store free-form context from the application in event metadata, all with no additional database queries. See the next steps below on how to dive deeper and configure it for your use case.Compatibilitydjango-pghistoryis compatible with Python 3.8 - 3.12, Django 3.2 - 5.0, Psycopg 2 - 3, and Postgres 12 - 16.DocumentationView the django-pghistory docs hereto learn more about:The basics and terminology.Tracking historical events on models.Attaching dynamic application context to events.Configuring event models.Aggregating events across event models.The Django admin integration.Reverting models to previous versions.A guide on performance and scale.There's also additional help, FAQ, and troubleshooting guides.InstallationInstalldjango-pghistorywith:pip3 install django-pghistoryAfter this, addpghistoryandpgtriggerto theINSTALLED_APPSsetting of your Django project.Contributing GuideFor information on setting up django-pghistory for development and contributing changes, viewCONTRIBUTING.md.Primary AuthorsWes KendallOther Contributors@shivananda-sahu@asucrews@Azurency@dracos@adamchainz@eeriksp@pfouque
Package: django-pgindex
Search for Django and PostgreSQL.RequirementsDjango >= 1.1django-stringfield >= 0.1.5django-cerial >= 0.0.2InstallationFirst install the package from pypi using pip:pip install django-pgindexThen makepgindexan app in yourINSTALLED_APPS:INSTALLED_APPS = (
    ...
    'pgindex',
    ...
)Sync your database:python manage.py syncdbDone.UsageCreate and Index class and register it to your model, much like registering an
admin class to your model. Example:# models.py
from django.db import models
from .index import ItemIndex
from pgindex import register

class Item(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()

    def get_absolute_url(self):
        return '/item/'

register(Item, ItemIndex)


# index.py
from pgindex import IndexBase, Vector

class ItemIndex(IndexBase):
    def get_title(self):
        return self.obj.title

    def get_description(self):
        return self.obj.content

    def get_vectors(self):
        return (
            Vector(self.obj.title, weight='A'),
            Vector(self.obj.content, weight='B'),
        )To search simply use thepgindex.searchmethod which returns a queryset
from thepgindex.models.Indexmodel:from pgindex import search

index_queryset = search('foo')See tests for examples.pgindex.IndexBase methodsget_title()This should return the title of the indexed object.get_description()This should return the description of the indexed object.get_url()This should return the url of the indexed object.get_data()You can return additional data that will be stored in the index field here, this
value will be pickled and depickled.get_publish()If this returnsFalseand index will not be createdget_start_publish()Can return adatetime.datetimewhich is the time when the index will be used.
ReturningNonemeans that it will always be used.get_end_publish()Can return adatetime.datetimewhich is the time for the index expiration.
ReturningNonemeans that it will never expire.get_vectors()This method needs to return a list or tuple ofpgindex.Vectorinstances. This in turn is the base for the text search column.
Package: django-pg-jsonschema
Django PostgreSQL JSONSchemaDjango PostgreSQL JSONSchema is a package that provides an extension to
Django's PostgreSQL JSONField, by adding support and functions for PostgreSQL
installations withpg_jsonschema.This allows developers to store data in a JSONField, while running validation
over the field and having the ability to generate forms for these model fields.FeaturesCustom JSON Field: Extends Django's built-inJSONFieldto support JSON Schema validation.PostgreSQL JSONSchema: Choose whether you want to validate the data in Python or commit the JSONSchema to the DB.Querying Support: Utilize Django's ORM capabilities to query and filter data stored in the JSON field.Schema Migration: Perform schema migrations smoothly without data loss or compatibility issues.InstallationYou can install the package using pip:pipinstalldjango-pg-jsonschemaUsageAdd'django_pg_jsonschema'to your Django project'sINSTALLED_APPSin the settings module.Configure globally if you want to commit the schemas to PostgreSQL (insettings.py):DJANGO_PG_JSONSCHEMA={'PG_COMMIT_JSONSCHEMA':True}Import theJSONSchemaFieldfrom the package:fromdjango_pg_jsonschema.fieldsimportJSONSchemaFieldIn your Django model, define a field of typeJSONSchemaFieldargument specifying the JSON schema:classPerson(models.Model):data=JSONSchemaField(schema={"$schema":"http://json-schema.org/draft-07/schema#","type":"object","properties":{"name":{"type":"string"},"age":{"type":"integer","minimum":0},},"required":["name","age"]})In the above example, thedatafield will store JSON objects that adhere to the specified schema.Optionally, you can define whether you want the check to be added as a constraint to the database:classPerson(models.Model):data=JSONSchemaField(schema={"$schema":"http://json-schema.org/draft-07/schema#","type":"object","properties":{"name":{"type":"string"},"age":{"type":"integer","minimum":0},},"required":["name","age"]},check_schema_in_db=False)Use the field in your Django models as you would with any other field:obj=Person(data={"name":"John Doe","age":25})obj.save()ContributionContributions to the Django JSON Field with JSON Schema Support package are welcome! If you encounter any issues, have suggestions, or want to contribute code, please open an issueor submit a pull request on the GitHub repository:https://github.com/maxboone/django-pg-jsonschemaPlease make sure to follow thecontribution guidelinesbefore submitting your contributions.LicenseThis package is licensed under theApache 2.0 License.
Package: django-pgmigrate
django-pgmigratedjango-pgmigratehelps you avoid costly downtime with Postgres migrations.Imagine the following happens:A long-running task queries a model in a transaction and keeps the transaction open.python manage.py migratetries to change a field on the model.Because of how Postgres queues locks, this common scenario causeseverysubsequent query on the model to block until the query from 1) has finished.django-pgmigrateprovides the following features to alleviate problematic locking scenarios when running migrations:Detect blocking queries and terminate them automatically (the default behavior).Print blocking queries so that you can inspect and terminate them manually.Set the lock timeout so that migrations are terminated if they block too long.InstallationInstalldjango-pgmigratewith:pip3 install django-pgmigrateAfter this, addpgactivity,pglock, andpgmigrateto theINSTALLED_APPSsetting of your Django project.Quick StartAfter following the installation instructions, runningpython manage.py migratewill automatically terminate any blocking queries. Here's an example of what it looks like:There are two additional outputs in themigratecommand versus the original:The first output line shows the Postgres process ID. This is useful for querying activity that's blocking the process.The yellow text shows when a blocking query was detected and terminated. In our case, it was blocking auth migration 12.You can configuredjango-pgmigrateto show blocked queries instead of automatically killing them, and you can also set the lock timeout to automatically cancel migrations if they block for too long. See the documentation section below for more details.Compatibilitydjango-pgmigrateis compatible with Python 3.8 - 3.12, Django 3.2 - 5.0, Psycopg 2 - 3, and Postgres 12 - 16.DocumentationView the django-pgmigrate docs hereto learn more about:How blocking queries are automatically terminated.Configuring the command to show blocking activity instead of terminating it, along with instructions on how to manually view and terminate activity.Configuring lock timeouts to automatically stop migrations if they block for too long.Advanced usage such as creating custom actions to run when queries are blocked.Contributing GuideFor information on setting up django-pgmigrate for development and contributing changes, viewCONTRIBUTING.md.Primary AuthorsWes KendallPaul Gilmartin
Package: django-pg-partitioning
一个支持 PostgreSQL 11 原生表分区的 Django 扩展，使您可以在 Django 中创建分区表并管理它们。目前它支持两种分区类型：时间范围分区（Time Range Partitioning）：将时序数据分开存储到不同的时间范围分区表中，支持创建连续且不重叠的时间范围分区并进行归档管理。列表分区（List Partitioning）：根据分区字段的确定值将数据分开存储到不同的分区表中。A Django extension that supports PostgreSQL 11 native table partitioning, allowing you to create partitioned tables in Django
and manage them. Currently it supports the following two partition types:Time Range Partitioning: Separate time series data into different time range partition tables,
support the creation of continuous and non-overlapping time range partitions and archival management.List Partitioning: Store data separately into different partition tables based on the determined values of the partition key.Documentationhttps://django-pg-partitioning.readthedocs.ioTODOImprove the details of the function.Improve documentation and testing.Optimization implementation.maybe more…ContributingIf you want to contribute to a project and make it better, you help is very welcome!
Please read throughContributing Guidelines.LicenseThis project is licensed under the MIT. Please seeLICENSE.Project Practice
Package: django-pgroonga
django-pgroonga は Django で PGroonga を利用するためのユーティリティですPGroonga のセットアップPGroonga で全文検索を行うために、以下の設定を行います。PGroonga の Extension 登録検索用インデックスの作成Extensionの登録はデータベース作成後に一回だけ行います。検索用インデックスは、検索対象となるカラムごとにそれぞれ作成します。この設定は、手動でSQLを実行しても構いませんが、以下のようにDjangoのマイグレーションとして登録・実行できます。空のマイグレーションを作成する$python3manage.pymakemigrationtestapp--emptyMigrationsfor'testapp':testapp/migrations/0002_auto_20161210_1544.py:マイグレーションを編集する作成されたマイグレーション(上の例では testapp/migrations/0002_auto_20161210_1544.py ) を、以下のように編集します。この例では、全文検索用のインデックスを、testapp_testmodelテーブルのtext1カラムに作成しています。from__future__importunicode_literalsfromdjango.dbimportmigrationsclassMigration(migrations.Migration):dependencies=[('testapp','0001_initial'),]operations=[# pgroonga を登録する(一回のみ)migrations.RunSQL('CREATE EXTENSION pgroonga','DROP EXTENSION pgroonga',),# 全文検索用インデックスを作成する(検索対象のカラムごとに作成)migrations.RunSQL('CREATE INDEX idx1 ON testapp_testmodel USING pgroonga (id, text1)','DROP INDEX idx1',)]検索するPGroonga用のインデックスを作成したカラムは、Djangoのcontainsを使った検索で全文検索を行えます。TestModel(text1='あいうえお').save()# 日本語のテキストを登録TestModel.objects.filter(text1__contains='あいうえお')この検索はlike演算子を利用した、指定した単語を検索するSQLとして実行されます。@@演算子を使用し、Groongaのクエリ構文で検索する場合は、ルックアップとしてgroongaを指定します。TestModel.objects.filter(text1__groonga='あいうえお OR かきくけこ')検索スコア検索のマッチ度合いは、django_pgroonga.Score()関数を使って取得します。fromdjango_pgroongaimportScoreforrinTestModel.objects.annotate(score=Score(TestModel)).order_by('-score').filter(text1__contains='あいうえお'):print(r.score,r.text1)django_pgroonga.Score()は、pgroonga.score関数を呼び出してスコアを取得します。スコアは、PGroongaインデックスにテーブルのプライマリキーが含まれている場合のみ取得可能で、含まれていなければ常に0を返します。LICENSECopyright (c) 2016 Atsuo IshimotoPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Package: django-pgschemas
This app uses PostgreSQL schemas to support data multi-tenancy in a single
Django project. It is a fork ofdjango-tenantswith some conceptual changes:There are static tenants and dynamic tenants. Static tenants can have their
own apps and urlconf.Tenants can be simultaneously routed via subdomain and via subfolder on shared
subdomain.Public is no longer the schema for storing the main site data. Public should
be used only for true shared data across all tenants. Table “overriding” via
search path is no longer encouraged.Management commands can be run on multiple schemas via wildcards - the
multiproc behavior of migrations was extended to just any tenant command.Documentationhttps://django-pgschemas.readthedocs.io/ContributingJoin the discussion athttps://github.com/lorinkoz/django-pgschemas/discussions.PRs are welcome! If you have questions or comments, please use the discussions
link above.To run the test suite runmakeormake coverage. The tests for this
project live inside a small django project calleddpgs_sandbox. Database
password and database host can be set through the environment variablesDATABASE_PASSWORDandDATABASE_HOST.CreditsTom Turner fordjango-tenants.Bernardo Pires fordjango-tenant-schemas.
Package: django-pgstats
django-pgstatsdjango-pgstatsprovides commands and models for tracking internal postgres stats. Specifically, theIndexStatsmodel stores stats about postgres indices and theTableStatsmodel stores stats about postgres tables.Postgres stat tables contain global statistical information.django-pgstatsis meant to be executed periodically so that one can later analyze table and index usage. This is done by periodically callingpython manage.py snapshot_pgstatsusing a task runner such asCelery.Stats are stored as JSON fields in the respectiveIndexStatsandTableStatsmodels. Each key in the JSON field is in the format of{schema}.{table}for table stats or{schema}.{table}.{index}for index stats.Compatibilitydjango-pgstatsis compatible with Python 3.8 - 3.12, Django 3.2 - 5.0, Psycopg 2 - 3, and Postgres 12 - 16.DocumentationView the django-pgstats docs hereInstallationInstalldjango-pgstatswith:pip3 install django-pgstatsAfter this, addpgstatsto theINSTALLED_APPSsetting of your Django project.Contributing GuideFor information on setting up django-pgstats for development and contributing changes, viewCONTRIBUTING.md.Primary Authors@wesleykendall (Wes Kendall)@tomage (Tómas Árni Jónasson)