Skip to content

Repository files navigation

Custom Functions

Python VersionLicense: MITCode style: blackContributions welcomeStatus

A collection of pre-made Python utilities for everyday tasks. This package provides ready-to-use classes for data handling, database operations, file I/O, and HTTP requests — helping you build projects faster and more effectively.

Features

  • DataHandler: Timestamp formatting, data normalization, and common data manipulation utilities
  • DbHandler: Full-featured SQLite database management with CRUD operations, table schema modifications, and index management
  • FileHandler: Comprehensive file operations including read/write, CSV/Excel/PDF handling, and file system utilities
  • Requester: Simplified HTTP request handling with common patterns and utilities

Installation

From PyPI (Recommended)

pip install custom_functions

From Source

# Clone the repository
git clone https://github.com/coderooz/My_simple_functions.git
cd My_simple_functions
# Install in development mode
pip install -e .# Or install with development dependencies
pip install -e ".[dev]"

Requirements

  • Python 3.12 or higher
  • Dependencies (installed automatically):
    • pytz>=2023.3.0
    • requests>=2.31.0
    • db-sqlite3>=0.0.1
    • pandas>=2.1.3
    • mysql-connector-python>=2.2.9
    • openpyxl>=3.1.2
    • PyPDF2>=3.0.0

Quick Start

# Import the handlersfromDataHandlersimportDataHandlerfromDbHandlerimportDbHandlerfromFileHandlerimportFileHandlerfromRequesterimportRequester# Use DataHandler for timestamp formattingtimestamp=DataHandler.timestamp()
print(timestamp) # Output: 2024-01-15 10:30:45# Use DbHandler for database operationsdb=DbHandler('my_database.db')
db.createTb('users', ['name TEXT', 'email TEXT'])
db.insert('users', ['John Doe', 'john@example.com'])
# Use FileHandler for file operationsFileHandler.write('output.txt', 'Hello, World!')
content=FileHandler.read('output.txt')
# Use Requester for HTTP requests# requester = Requester()# response = requester.get('https://api.example.com/data')

Detailed Usage

DataHandler

The DataHandler class provides utilities for common data manipulation tasks.

timestamp(given_time=None, format="%Y-%m-%d %H:%M:%S", time_zone=None, normalize='sec')

Returns the date and time in the specified format.

Parameters:

  • given_time: Optional datetime object or timestamp (default: current time)
  • format: strftime format string (default: "%Y-%m-%d %H:%M:%S")
  • time_zone: Optional timezone string (e.g., "Asia/Kolkata")
  • normalize: Normalization level — 'sec', 'min', or 'hour' (default: 'sec')

Returns:str — Formatted timestamp string

Example:

fromDataHandlersimportDataHandler# Current timestampprint(DataHandler.timestamp())
# Output: 2024-01-15 10:30:45# Custom formatprint(DataHandler.timestamp(format="%Y-%m-%d"))
# Output: 2024-01-15# With timezoneprint(DataHandler.timestamp(time_zone="US/Pacific"))
# Output: 2024-01-14 21:00:45

DbHandler

The DbHandler class provides a comprehensive interface for SQLite database operations.

Initialization

fromDbHandlerimportDbHandler# Creates new database or connects to existing onedb=DbHandler('my_database.db')

Core Methods

createTb(table_name, columns, insertData=None, addId=False, idKey='id')

Creates a new table with optional data insertion.

Parameters:

  • table_name: Name of the table
  • columns: List of column definitions (e.g., ['col1 TEXT', 'col2 INT'])
  • insertData: Optional data to insert immediately after creation
  • addId: Whether to add an auto-incrementing primary key (default: False)
  • idKey: Name of the primary key column (default: 'id')

Example:

# Create table with columnsdb.createTb('users', ['name TEXT', 'email TEXT', 'age INT'])
# Create with auto ID and initial datadb.createTb('users', ['name TEXT', 'email TEXT'], insertData=['John', 'john@example.com'], addId=True)
insert(table_name, data)

Inserts a row into the specified table.

Example:

db.insert('users', ['Alice', 'alice@example.com', 25])
fetch(table_name, columns='*', query='')

Fetches data from a table with optional filtering.

Example:

# Fetch all rowsall_users=db.fetch('users')
# Fetch specific columns with conditionresult=db.fetch('users', columns='name, email', query="age > 18")
getCount(table_name, query='')

Counts rows in a table, optionally with a filter.

Example:

total=db.getCount('users')
adults=db.getCount('users', query="age >= 18")
update(table_name, data, query)

Updates rows matching the query.

Example:

db.update('users', {'age': 26}, query="name='Alice'")
execute(query, params=None)

Executes raw SQL queries.

Example:

db.execute("DROP TABLE IF EXISTS temp_table")

Additional Methods

MethodDescription
delTb(table_name)Delete a table
renameTb(old_name, new_name)Rename a table
getTb()List all tables
getTbData(table_name)Get all data from a table
alterTb(table_name, operation)Alter table structure
getColumnNames(table_name)Get column names
get_table_info(table_name)Get detailed table info
modifyColumns(table_name, columns)Modify column definitions
checkIndex(table_name, index_name)Check if index exists
getIndexes(table_name)Get all indexes
addIndex(table_name, columns, unique=False)Add an index
delIndex(index_name)Delete an index
cleanTb(table_name)Delete all rows from a table
addColumn(table_name, column_def)Add a new column
renameColumn(table_name, old_name, new_name)Rename a column
removeColumn(table_name, column_name)Remove a column
close_connection()Close database connection

FileHandler

The FileHandler class provides utilities for file system operations and file format handling.

Initialization

fromFileHandlerimportFileHandler# Static class — no initialization needed# Use directly: FileHandler.method_name()

Core Methods

getFiles(file_path, catg=0)

Gets list of files and/or folders in a directory.

Parameters:

  • file_path: Path to the directory
  • catg: Category filter — 0 for both, 1 for files only, 2 for directories only

Returns:list of file/directory names

Example:

# Get both files and foldersitems=FileHandler.getFiles('./my_folder')
# Get only filesfiles=FileHandler.getFiles('./my_folder', catg=1)
# Get only directoriesdirs=FileHandler.getFiles('./my_folder', catg=2)
get_only_filename(file_path)

Extracts just the filename from a path.

getFileCatg(file_path)

Gets the file category/type based on extension.

splitFileName(file_path)

Splits filename into name and extension.

getExtention(file_path)

Gets the file extension.

read(file_name)

Reads and returns file contents.

write(file_name, data, separator='')

Appends data to a file.

Parameters:

  • file_name: Path to the file
  • data: Content to write
  • separator: Optional separator to append after data

Example:

FileHandler.write('output.txt', 'Hello, World!', separator='\n')
write_over(file_name, data, separator='')

Overwrites file contents with new data.

read_csv(file_name, **kwargs)

Reads a CSV file and returns a pandas DataFrame.

write_csv(file_name, data, **kwargs)

Writes data to a CSV file.

read_excel(file_name, **kwargs)

Reads an Excel file and returns a pandas DataFrame.

write_excel(file_name, data, **kwargs)

Writes data to an Excel file.

read_pdf(file_name)

Extracts and returns text content from a PDF file.

Example:

text=FileHandler.read_pdf('document.pdf')
print(text)

Requester

The Requester class provides simplified HTTP request handling.

fromRequesterimportRequester# Initializerequester=Requester()
# GET requestresponse=requester.get('https://api.example.com/data')
# POST requestresponse=requester.post('https://api.example.com/data', json={'key': 'value'})
# With custom headersresponse=requester.get('https://api.example.com/data', headers={'Authorization': 'Bearer token'})

Project Structure

custom_functions/
├── DataHandlers.py # Data manipulation utilities
├── DbHandler.py # SQLite database operations
├── FileHandler.py # File I/O and format handling
├── Requester.py # HTTP request utilities
├── __init__.py # Package initialization
├── setup.py # Package distribution setup
├── pyproject.toml # Modern Python project configuration
├── LICENSE.txt # MIT License
├── README.md # This file
├── CHANGELOG.md # Version history
├── CONTRIBUTING.md # Contribution guidelines
├── CODE_OF_CONDUCT.md # Community guidelines
├── SECURITY.md # Security policy
├── .gitignore # Git ignore rules
├── .editorconfig # Editor configuration
└── .github/ # GitHub-specific files
├── ISSUE_TEMPLATE/ # Issue templates
├── workflows/ # CI/CD workflows
├── CODEOWNERS # Code ownership
├── dependabot.yml # Dependency updates
├── labels.yml # Issue labels
├── PULL_REQUEST_TEMPLATE.md
└── FUNDING.yml # Sponsorship information

Development

Setup Development Environment

# Clone and set up virtual environment
git clone https://github.com/coderooz/My_simple_functions.git
cd My_simple_functions
python -m venv venv
source venv/bin/activate # Windows: venv\Scripts\activate# Install with dev dependencies
pip install -e ".[dev]"

Running Tests

# Run all tests
pytest
# Run with coverage
pytest --cov=custom_functions --cov-report=html
# Run specific test file
pytest tests/test_datahandler.py -v

Code Quality

# Format code
black .# Sort imports
isort .# Lint
flake8 .# Run all checks
black .&& isort .&& flake8 .

Contributing

We welcome contributions of all kinds! Please read our Contributing Guide for details on:

  • How to set up your development environment
  • Our coding standards and conventions
  • How to submit pull requests
  • How to report bugs or request features

Quick Start for Contributors

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Make your changes
  4. Run tests and linting
  5. Commit your changes (git commit -m 'feat: add amazing feature')
  6. Push to the branch (git push origin feature/amazing-feature)
  7. Open a Pull Request

Please read our Code of Conduct before contributing.

Versioning

We use Semantic Versioning (SemVer) for versioning. See the CHANGELOG.md for a list of available versions and the changes in each release.

License

This project is licensed under the MIT License — see the LICENSE.txt file for details.

Author

Ranit Saha (Coderooz)

Acknowledgments

  • Thanks to all contributors who help improve this project
  • Built with the goal of reducing repetitive coding tasks

Support

If you find this project helpful, consider supporting:


Made with ❤️ by CodeRooz

About

No description, website, or topics provided.

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages