Utilities for Python in postgresql
Project description
wpostgresql
wpostgresql is a library for specific functions for interacting with PostgreSQL databases.
Description
wpostgresql simplifies code for interacting with PostgreSQL databases. It provides a number of functions for creating, reading, updating, and deleting data in PostgreSQL databases.
Installation
To install the library, use pip:
pip install wpostgresql
Description
The wpostgresql library offers a number of general-purpose modules.
License
MIT
This project is licensed under the MIT License. See the LICENSE file for details.
Examples
This directory contains a collection of examples that demonstrate the usage of various modules and functionalities in this project. Each subfolder corresponds to a specific module and includes example scripts to help you understand how to use that module.
Directory Structure
The examples are organized as follows:
examples/
wpostgresql/
crupd.py
new_columns.py
with_restrictions.py
How to Use
- Navigate to the module folder of interest, e.g.,
examples/module1/. - Open the
README.mdin that folder to get detailed information about the examples. - Run the scripts directly using:
python example1.py
Modules and Examples
wpostgresql
Description
This module demonstrates specific functionalities.
- crupd.py: Example demonstrating functionality.
from pydantic import BaseModel
from wpostgresql import WPostgreSQL # Asegúrate de tener definida la clase WPostgreSQL
# Configuración de conex ión a PostgreSQL
db_config = {
'dbname': 'wpostgresql',
'user': 'postgres',
'password': 'postgres',
'host': 'localhost',
'port': 5432
}
# Definir el modelo sin restricciones adicionales
class SimpleModel2(BaseModel):
id: int
name: str
age: int
is_active: bool
# Crear la base de datos y la tabla (se crean o sincronizan automáticamente)
db = WPostgreSQL(SimpleModel2, db_config)
# Insertar datos
db.insert(SimpleModel2(id=1, name="Juan Pérez", age=30, is_active=True))
db.insert(SimpleModel2(id=2, name="Ana López", age=25, is_active=True))
db.insert(SimpleModel2(id=3, name="Pedro Gómez", age=40, is_active=False))
# Consultar todos los registros
print("Todos los usuarios:", db.get_all())
# Consultar por un campo específico
print("Usuarios llamados Juan Pérez:", db.get_by_field(name="Juan Pérez"))
# Consultar por múltiples filtros
print("Usuarios activos con 25 años:", db.get_by_field(age=25, is_active=True))
# Actualizar un usuario (por ejemplo, actualizando el registro con id=1)
db.update(1, SimpleModel2(id=1, name="Juan Pérez", age=31, is_active=False))
print("Usuario actualizado (id=1):", db.get_by_field(id=1))
# Eliminar un usuario (por ejemplo, el de id=3)
db.delete(3)
print("Usuarios después de eliminar a Pedro Gómez:", db.get_all())
- new_columns.py: Example demonstrating functionality.
from pydantic import BaseModel, Field
from typing import Optional
from wpostgresql import WPostgreSQL
db_config = {
'dbname': 'wpostgresql',
'user': 'postgres',
'password': 'postgres',
'host': 'localhost',
'port': 5432
}
# Modelo inicial sin el campo email
class SimpleModel4(BaseModel):
id: int = Field(..., description="Primary Key")
name: str = Field(..., description="NOT NULL")
age: int
is_active: bool
# Crear la tabla con el modelo inicial e insertar un registro
db = WPostgreSQL(SimpleModel4, db_config)
db.insert(SimpleModel4(id=1, name="Ana López", age=25, is_active=True))
# === AHORA SE AÑADE UN NUEVO CAMPO AL MODELO ===
class SimpleModel4(BaseModel):
id: int = Field(..., description="Primary Key")
name: str = Field(..., description="NOT NULL")
age: int
is_active: bool
email: Optional[str] # Nuevo campo sin restricciones en la base de datos
# Al instanciar nuevamente WPostgreSQL con el modelo actualizado se sincroniza la tabla
db = WPostgreSQL(SimpleModel4, db_config)
# Insertar un nuevo registro que incluya el nuevo campo
db.insert(SimpleModel4(id=2, name="Ana López", age=25, is_active=True, email="ana@example.com"))
# Mostrar todos los registros después de la actualización
print("Usuarios después de actualizar el modelo:", db.get_all())
- with_restrictions.py: Example demonstrating functionality.
from pydantic import BaseModel, Field
from typing import Optional
from wpostgresql import WPostgreSQL
db_config = {
'dbname': 'wpostgresql',
'user': 'postgres',
'password': 'postgres',
'host': 'localhost',
'port': 5432
}
# Definir el modelo con restricciones
class SimpleModel5(BaseModel):
id: int = Field(..., description="Primary Key")
name: str = Field(..., description="NOT NULL")
age: int
is_active: bool
email: Optional[str] = Field(None, description="UNIQUE") # Email debe ser único
# Crear la base de datos y sincronizar con el modelo
db = WPostgreSQL(SimpleModel5, db_config)
# Insertar un registro válido
db.insert(SimpleModel5(id=1, name="Juan Pérez", age=30, is_active=True, email="juan@example.com"))
# Intentar insertar un registro con un email duplicado (esto debería fallar)
try:
db.insert(SimpleModel5(id=2, name="Ana López", age=25, is_active=True, email="juan@example.com"))
except Exception as e:
print("Error al insertar usuario duplicado:", e)
# Insertar otro registro con un email único (esto funcionará)
db.insert(SimpleModel5(id=3, name="Pedro Gómez", age=40, is_active=False, email="pedro@example.com"))
# Mostrar los registros almacenados
print("Usuarios en la base de datos:", db.get_all())
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file wpostgresql-0.1.0.tar.gz.
File metadata
- Download URL: wpostgresql-0.1.0.tar.gz
- Upload date:
- Size: 8.5 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/5.1.1 CPython/3.11.5
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
5e8c007392273483bc3fb52a7f1cac859762fef8b46045f74d8cf41ef90dca3d
|
|
| MD5 |
1077f7664c62b457a9b43447bfedee87
|
|
| BLAKE2b-256 |
01ade2b22221c8a2ebad902769d784a2fb20b6792c24e9f3d2baa65a09d13940
|
File details
Details for the file wpostgresql-0.1.0-py3-none-any.whl.
File metadata
- Download URL: wpostgresql-0.1.0-py3-none-any.whl
- Upload date:
- Size: 7.0 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/5.1.1 CPython/3.11.5
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
6c70633372e74b827094a3c9fb1ee8769d96a97713a611fa24d253f6e80d7177
|
|
| MD5 |
edcc6c020173801da4e2c3657d0066e8
|
|
| BLAKE2b-256 |
c05dcda9738c2e7ab8d2a595f403b4772997dac1a59bec00f92344b5731882f7
|