### Django Project Structure Setup (Bash) Source: https://context7.com/heqz1993/onn_template/llms.txt Commands to install Django, create a new Django project and app, run initial migrations, create a superuser, and start the development server. It also notes that the .gitignore already excludes common Django artifacts like database files and logs. ```bash # Install Django pip install django # Create Django project django-admin startproject mysite . # Create app python manage.py startapp myapp # Run migrations python manage.py migrate # Create superuser python manage.py createsuperuser # Run development server python manage.py runserver # The .gitignore already excludes: # - db.sqlite3 # - *.log # - local_settings.py # - __pycache__/ ``` -------------------------------- ### UV Environment Setup and Usage (Bash) Source: https://context7.com/heqz1993/onn_template/llms.txt Instructions to install the UV package manager, create a virtual environment, activate it, install packages, and generate a requirements.txt file. This provides an alternative for fast dependency management and environment setup. ```bash # Install uv package manager curl -LsSf https://astral.sh/uv/install.sh | sh # Create virtual environment uv venv # Activate virtual environment source .venv/bin/activate # Linux/Mac # or .venv\Scripts\activate # Windows # Install packages uv pip install requests pydantic pytest black ruff # Create requirements.txt uv pip freeze > requirements.txt # Run application python main.py ``` -------------------------------- ### Poetry Environment Setup and Usage (Bash) Source: https://context7.com/heqz1993/onn_template/llms.txt Commands to install Poetry, initialize a new project, add dependencies (including development dependencies), install all dependencies, and run scripts or tests using Poetry. This facilitates dependency management and virtual environment creation. ```bash # Install poetry if not already installed curl -sSL https://install.python-poetry.org | python3 - # Initialize poetry project (creates pyproject.toml) poetry init --no-interaction \ --name my-project \ --description "My Python project" \ --author "Your Name " \ --python "^3.9" # Add dependencies poetry add requests pydantic poetry add --group dev pytest black ruff mypy # Install dependencies and create virtual environment poetry install # Run your application poetry run python main.py # Run tests poetry run pytest # Format code poetry run black . poetry run ruff check . ``` -------------------------------- ### Jupyter Notebook Management Commands Source: https://context7.com/heqz1993/onn_template/llms.txt Commands for installing and managing Jupyter Notebook and JupyterLab, including starting the servers and exporting notebooks to different formats like Python scripts and HTML. ```bash # Install Jupyter pip install jupyter notebook jupyterlab # Start Jupyter Notebook jupyter notebook # Start JupyterLab jupyter lab # Export notebook to Python script jupyter nbconvert --to script notebooks/analysis.ipynb # Export notebook to HTML jupyter nbconvert --to html notebooks/analysis.ipynb ``` -------------------------------- ### Basic Flask Application Example (Python) Source: https://context7.com/heqz1993/onn_template/llms.txt A minimal Flask application demonstrating how to initialize a Flask app, define basic routes, and handle JSON responses. This serves as a starting point for building web applications with Flask. ```python # app.py """ Flask application example """ from flask import Flask, jsonify, request from pathlib import Path import os app = Flask(__name__) ``` -------------------------------- ### Pytest Example Test Suite Source: https://context7.com/heqz1993/onn_template/llms.txt An example test suite for a Python project using Pytest. It includes basic assertion tests, string operation tests, tests utilizing fixtures for data setup, parameterized tests for running tests with multiple inputs, and tests organized within classes. ```python # tests/test_main.py """ Example test suite """ import pytest from pathlib import Path def test_basic(): """Basic test example""" assert 1 + 1 == 2 def test_string_operations(): """Test string operations""" text = "Hello World" assert text.lower() == "hello world" assert text.split() == ["Hello", "World"] @pytest.pyplot.fixture def sample_data(): """Fixture providing test data""" return { "users": [ {"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"} ] } def test_with_fixture(sample_data): """Test using fixture""" assert len(sample_data["users"]) == 2 assert sample_data["users"][0]["name"] == "Alice" @pytest.mark.parametrize("input,expected", [ (2, 4), (3, 9), (4, 16), ]) def test_square(input, expected): """Parameterized test""" assert input ** 2 == expected class TestCalculator: """Test class example""" def test_add(self): assert 2 + 2 == 4 def test_subtract(self): assert 5 - 3 == 2 # Run tests with: # pytest tests/ # pytest tests/ -v --tb=short # pytest tests/ --cov=my_project ``` -------------------------------- ### Pre-commit Hook Management Source: https://context7.com/heqz1993/onn_template/llms.txt Bash commands to install the pre-commit tool, install the configured hooks into the repository, and run all configured hooks on all files in the project. ```bash # Install pre-commit pip install pre-commit # Install hooks pre-commit install # Run on all files pre-commit run --all-files # Hooks will now run automatically on git commit ``` -------------------------------- ### Data API Endpoint Source: https://context7.com/heqz1993/onn_template/llms.txt An example API endpoint for handling data, supporting both GET and POST requests. ```APIDOC ## API Data Endpoint ### Description This endpoint allows for retrieving a list of data items via GET requests and processing received JSON data via POST requests. ### Method GET, POST ### Endpoint /api/data ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body (for POST requests) - **field1** (any) - Description of the field. ### Request Example (POST) ```json { "key": "value" } ``` ### Response #### Success Response (200 for GET) - **items** (array) - A list of data items, where each item is an object with 'id' and 'name' fields. #### Success Response (201 for POST) - **received** (object) - The data that was received in the request body. - **status** (string) - Indicates that the data has been processed. #### Response Example (GET) ```json { "items": [ {"id": 1, "name": "Item 1"}, {"id": 2, "name": "Item 2"} ] } ``` #### Response Example (POST) ```json { "received": { "key": "value" }, "status": "processed" } ``` ``` -------------------------------- ### Build and Distribute Python Package Source: https://context7.com/heqz1993/onn_template/llms.txt Commands to build a Python package using the 'build' tool and upload it to a package index using 'twine'. It ensures the necessary build tools are installed and then executes the build process, creating source and wheel distributions in the 'dist/' directory. ```bash # Ensure build tools are installed pip install build twine # Build package python -m build # This creates: # - dist/my_project-0.1.0.tar.gz (source distribution) # - dist/my_project-0.1.0-py3-none-any.whl (wheel) ``` -------------------------------- ### Configure GitHub Actions CI/CD Source: https://context7.com/heqz1993/onn_template/llms.txt A GitHub Actions workflow configuration for CI/CD. It sets up multiple Python versions, installs dependencies using Poetry, and runs linters (ruff), formatters (black), type checkers (mypy), and tests (pytest). It also uploads test coverage to Codecov. ```yaml # .github/workflows/test.yml name: Test on: push: branches: [ main, develop ] pull_request: branches: [ main ] jobs: test: runs-on: ubuntu-latest strategy: matrix: python-version: ['3.9', '3.10', '3.11', '3.12'] steps: - uses: actions/checkout@v4 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v4 with: python-version: ${{ matrix.python-version }} - name: Install dependencies run: | python -m pip install --upgrade pip pip install poetry poetry install - name: Lint with ruff run: poetry run ruff check . - name: Format check with black run: poetry run black --check . - name: Type check with mypy run: poetry run mypy . - name: Test with pytest run: | poetry run pytest --cov=. --cov-report=xml - name: Upload coverage uses: codecov/codecov-action@v3 with: file: ./coverage.xml ``` -------------------------------- ### Jupyter Notebook Analysis Example Source: https://context7.com/heqz1993/onn_template/llms.txt A Python script representing a Jupyter Notebook for data analysis. It includes importing libraries, loading sample data into a Pandas DataFrame, performing group-by aggregation, and visualizing the results using Matplotlib and Seaborn. It also lists ignored files by .gitignore. ```python # notebooks/analysis.ipynb (as Python script for documentation) """ Data analysis notebook example """ # Cell 1: Imports import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns # Cell 2: Load data data = pd.DataFrame({ 'date': pd.date_range('2024-01-01', periods=100), 'value': np.random.randn(100).cumsum(), 'category': np.random.choice(['A', 'B', 'C'], 100) }) # Cell 3: Analyze summary = data.groupby('category')['value'].agg(['mean', 'std', 'count']) print(summary) # Cell 4: Visualize fig, ax = plt.subplots(figsize=(12, 6)) for category in data['category'].unique(): subset = data[data['category'] == category] ax.plot(subset['date'], subset['value'], label=category, alpha=0.7) ax.legend() ax.set_title('Time Series by Category') plt.show() # The .gitignore already excludes: # - .ipynb_checkpoints # - __pycache__/ # - .hypothesis/ ``` -------------------------------- ### Initialize Project from Template (Bash) Source: https://context7.com/heqz1993/onn_template/llms.txt Steps to clone the template repository, remove existing git history, initialize a new git repository, and set up a remote origin for a new project. ```bash # Clone the template repository git clone https://github.com/heqz1993/onn_template.git my-new-project cd my-new-project # Remove the original git history rm -rf .git # Initialize a new git repository git init git add . git commit -m "Initial commit from onn_template" # Add your remote and push git remote add origin https://github.com/yourusername/my-new-project.git git push -u origin main ``` -------------------------------- ### Project Configuration with pyproject.toml (TOML) Source: https://context7.com/heqz1993/onn_template/llms.txt A sample `pyproject.toml` file demonstrating configuration for project metadata, dependencies (including optional development dependencies), script entry points, and tool-specific settings for Black, Ruff, MyPy, and Pytest. ```toml # pyproject.toml [project] name = "my-project" version = "0.1.0" description = "My Python project from onn_template" authors = [ {name = "Your Name", email = "email@example.com"} ] readme = "README.md" requires-python = ">=3.9" dependencies = [ "requests>=2.31.0", "pydantic>=2.0.0", ] [project.optional-dependencies] dev = [ "pytest>=7.4.0", "black>=23.0.0", "ruff>=0.1.0", "mypy>=1.5.0", ] [project.scripts] my-cli = "my_project.cli:main" [tool.black] line-length = 100 target-version = ['py39', 'py310', 'py311'] exclude = ''' /( \.eggs | \.git | \.venv | build | dist )/ ''' [tool.ruff] line-length = 100 target-version = "py39" select = ["E", "F", "I", "N", "W"] ignore = ["E501"] [tool.mypy] python_version = "3.9" warn_return_any = true warn_unused_configs = true disallow_untyped_defs = true [tool.pytest.ini_options] testpaths = ["tests"] python_files = "test_*.py" python_classes = "Test*" python_functions = "test_*" addopts = "-v --tb=short" ``` -------------------------------- ### Package Management: Check and Upload Source: https://context7.com/heqz1993/onn_template/llms.txt Commands to check a Python package using twine and upload it to TestPyPI or PyPI. Assumes the package distribution files are in the 'dist/' directory. ```bash # Check package twine check dist/* # Upload to TestPyPI twine upload --repository testpypi dist/* # Upload to PyPI twine upload dist/* # Install from TestPyPI pip install --index-url https://test.pypi.org/simple/ my-project ``` -------------------------------- ### Configure Pre-commit Hooks Source: https://context7.com/heqz1993/onn_template/llms.txt Configuration for pre-commit hooks to automate code formatting, linting, and other checks. This YAML file specifies repositories and hooks to be used. ```yaml # .pre-commit-config.yaml repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v4.5.0 hooks: - id: trailing-whitespace - id: end-of-file-fixer - id: check-yaml - id: check-added-large-files - id: check-json - id: check-toml - id: detect-private-key - repo: https://github.com/psf/black rev: 23.12.1 hooks: - id: black language_version: python3.9 - repo: https://github.com/astral-sh/ruff-pre-commit rev: v0.1.9 hooks: - id: ruff args: [--fix, --exit-non-zero-on-fix] - repo: https://github.com/pre-commit/mirrors-mypy rev: v1.8.0 hooks: - id: mypy additional_dependencies: [types-all] ``` -------------------------------- ### Basic Python Application Structure (Python) Source: https://context7.com/heqz1993/onn_template/llms.txt A simple Python script demonstrating a basic application entry point with a main function and a helper function for processing data. It includes basic error handling and sys.exit for proper exit codes. ```python # main.py """ Example application entry point """ import sys from pathlib import Path def main(): """Main application entry point""" print("Hello from onn_template!") print(f"Python version: {sys.version}") print(f"Working directory: {Path.cwd()}") try: # Your application logic here result = process_data() print(f"Result: {result}") return 0 except Exception as e: print(f"Error: {e}", file=sys.stderr) return 1 def process_data(): """Example processing function""" return {"status": "success", "data": [1, 2, 3]} if __name__ == "__main__": sys.exit(main()) ``` -------------------------------- ### Run Flask Application Source: https://context7.com/heqz1993/onn_template/llms.txt Commands to run a Flask application locally and in production using gunicorn. It involves setting environment variables for Flask to recognize the application file and environment, then executing the Flask development server or the gunicorn production server. ```bash # Run Flask application export FLASK_APP=app.py export FLASK_ENV=development flask run # Or with gunicorn (production) pip install gunicorn gunicorn -w 4 -b 0.0.0.0:8000 app:app ``` -------------------------------- ### 404 Error Handler Source: https://context7.com/heqz1993/onn_template/llms.txt Handles and returns a standardized JSON response for 404 Not Found errors. ```APIDOC ## 404 Error Handler ### Description This endpoint is automatically triggered when a requested resource is not found, returning a JSON object indicating the error. ### Method N/A (Error Handler) ### Endpoint N/A (Error Handler) ### Parameters None ### Request Example None ### Response #### Error Response (404) - **error** (string) - A message indicating that the requested resource was not found. #### Response Example ```json { "error": "Not found" } ``` ``` -------------------------------- ### Root Endpoint Source: https://context7.com/heqz1993/onn_template/llms.txt The root endpoint of the application, returning basic status information. ```APIDOC ## GET / ### Description Returns the status of the running application, including its name and version. ### Method GET ### Endpoint / ### Parameters #### Path Parameters None #### Query Parameters None ### Request Example None ### Response #### Success Response (200) - **status** (string) - The current status of the application. - **name** (string) - The name of the application. - **version** (string) - The version of the application. #### Response Example ```json { "status": "running", "name": "My Flask App", "version": "0.1.0" } ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.