-
-
Save Viicos/2339e207aeec25b608942bb28eb9c299 to your computer and use it in GitHub Desktop.
web-framework-performance
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| curl -X POST http://localhost:9000/test \ | |
| -H "Content-Type: application/json" \ | |
| -d '{ | |
| "customer": { | |
| "id": 1, | |
| "name": "John Doe", | |
| "status": "active", | |
| "addresses": [ | |
| {"street": "123 Main St", "city": "Springfield", "country": "US", "postal_code": "62701", "coordinates": [39.7817, -89.6501]}, | |
| {"street": "456 Oak Ave", "city": "Chicago", "country": "US", "postal_code": "60601", "coordinates": [41.8781, -87.6298]}, | |
| {"street": "789 Pine Rd", "city": "Austin", "country": "US", "postal_code": "73301", "coordinates": [30.2672, -97.7431]}, | |
| {"street": "101 Maple Dr", "city": "Denver", "country": "US", "postal_code": "80201", "coordinates": [39.7392, -104.9903]}, | |
| {"street": "202 Elm St", "city": "Seattle", "country": "US", "postal_code": "98101", "coordinates": [47.6062, -122.3321]}, | |
| {"street": "303 Birch Ln", "city": "Portland", "country": "US", "postal_code": "97201", "coordinates": [45.5152, -122.6784]}, | |
| {"street": "404 Cedar Ct", "city": "Miami", "country": "US", "postal_code": "33101", "coordinates": [25.7617, -80.1918]}, | |
| {"street": "505 Walnut Blvd", "city": "Boston", "country": "US", "postal_code": "02101", "coordinates": [42.3601, -71.0589]}, | |
| {"street": "606 Spruce Way", "city": "Atlanta", "country": "US", "postal_code": "30301", "coordinates": [33.7490, -84.3880]}, | |
| {"street": "707 Willow Pl", "city": "San Francisco", "country": "US", "postal_code": "94101", "coordinates": [37.7749, -122.4194]} | |
| ], | |
| "contacts": [ | |
| {"email": "john@example.com", "phone": "+1234567890", "preferred": true}, | |
| {"email": "john.doe@work.com", "phone": "+1234567891", "preferred": false}, | |
| {"email": "jdoe@personal.net", "phone": "+1234567892", "preferred": false}, | |
| {"email": "john.d@startup.io", "phone": "+1234567893", "preferred": false}, | |
| {"email": "johndoe@mail.org", "phone": "+1234567894", "preferred": false}, | |
| {"email": "j.doe@corp.com", "phone": "+1234567895", "preferred": false}, | |
| {"email": "john.doe@uni.edu", "phone": "+1234567896", "preferred": false}, | |
| {"email": "jd@freelance.dev", "phone": "+1234567897", "preferred": false}, | |
| {"email": "johnd@shop.co", "phone": "+1234567898", "preferred": false}, | |
| {"email": "doe.john@cloud.com", "phone": "+1234567899", "preferred": false} | |
| ], | |
| "created_at": "2024-01-15T10:30:00", | |
| "birth_date": "1990-05-20" | |
| }, | |
| "items": [ | |
| {"product_id": 42, "name": "Widget Pro", "order_date": "2024-06-15T14:00:00", "quantity": 3, "unit_price": "29.99", "discount": 0.1, "tags": ["electronics", "sale"], "metadata": {"warehouse": "A1", "weight": 1.5}}, | |
| {"product_id": 43, "name": "Gadget Plus", "order_date": "2024-06-15T14:05:00", "quantity": 1, "unit_price": "49.99", "discount": 0.0, "tags": ["electronics", "new"], "metadata": {"warehouse": "B2", "weight": 0.8}}, | |
| {"product_id": 44, "name": "Sensor Max", "order_date": "2024-06-15T14:10:00", "quantity": 5, "unit_price": "15.50", "discount": 0.15, "tags": ["industrial", "bulk"], "metadata": {"warehouse": "C3", "weight": 0.3}}, | |
| {"product_id": 45, "name": "Cable Ultra", "order_date": "2024-06-16T09:00:00", "quantity": 10, "unit_price": "8.99", "discount": 0.2, "tags": ["accessories", "sale", "popular"], "metadata": {"warehouse": "A1", "weight": 0.1}}, | |
| {"product_id": 46, "name": "Battery Pack XL", "order_date": "2024-06-16T09:30:00", "quantity": 2, "unit_price": "34.99", "discount": 0.05, "tags": ["power", "portable"], "metadata": {"warehouse": "D4", "weight": 2.0}}, | |
| {"product_id": 47, "name": "Screen Guard HD", "order_date": "2024-06-16T10:00:00", "quantity": 8, "unit_price": "12.49", "discount": 0.0, "tags": ["accessories", "protection"], "metadata": {"warehouse": "B2", "weight": 0.05}}, | |
| {"product_id": 48, "name": "Dock Station Pro", "order_date": "2024-06-16T11:00:00", "quantity": 1, "unit_price": "89.99", "discount": 0.1, "tags": ["electronics", "premium", "office"], "metadata": {"warehouse": "E5", "weight": 3.5}}, | |
| {"product_id": 49, "name": "Wireless Mouse", "order_date": "2024-06-17T08:00:00", "quantity": 4, "unit_price": "24.99", "discount": 0.0, "tags": ["peripherals", "wireless"], "metadata": {"warehouse": "A1", "weight": 0.2}}, | |
| {"product_id": 50, "name": "USB Hub 7-Port", "order_date": "2024-06-17T08:30:00", "quantity": 2, "unit_price": "19.99", "discount": 0.25, "tags": ["accessories", "connectivity"], "metadata": {"warehouse": "C3", "weight": 0.4}}, | |
| {"product_id": 51, "name": "Keyboard Mech RGB", "order_date": "2024-06-17T09:00:00", "quantity": 1, "unit_price": "129.99", "discount": 0.05, "tags": ["peripherals", "gaming", "rgb"], "metadata": {"warehouse": "D4", "weight": 1.2}} | |
| ], | |
| "payments": [ | |
| {"method": "credit_card", "amount": "80.97", "currency": "USD", "processed_at": "2024-06-15T14:05:00"}, | |
| {"method": "debit_card", "amount": "49.99", "currency": "USD", "processed_at": "2024-06-15T14:10:00"}, | |
| {"method": "paypal", "amount": "65.88", "currency": "USD", "processed_at": "2024-06-15T14:15:00"}, | |
| {"method": "credit_card", "amount": "89.90", "currency": "EUR", "processed_at": "2024-06-16T09:05:00"}, | |
| {"method": "bank_transfer", "amount": "69.98", "currency": "USD", "processed_at": "2024-06-16T09:35:00"}, | |
| {"method": "credit_card", "amount": "99.92", "currency": "USD", "processed_at": "2024-06-16T10:05:00"}, | |
| {"method": "apple_pay", "amount": "80.99", "currency": "GBP", "processed_at": "2024-06-16T11:05:00"}, | |
| {"method": "google_pay", "amount": "99.96", "currency": "USD", "processed_at": "2024-06-17T08:05:00"}, | |
| {"method": "credit_card", "amount": "29.99", "currency": "USD", "processed_at": "2024-06-17T08:35:00"}, | |
| {"method": "crypto", "amount": "129.99", "currency": "BTC", "processed_at": "2024-06-17T09:05:00"} | |
| ], | |
| "notes": [ | |
| "Rush order", "Gift wrap requested", "Handle with care", "Leave at door", | |
| "Signature required", "Insure shipment", "Include receipt", "No plastic packaging", | |
| "Deliver before noon", "Call before delivery", "Fragile items inside", "Stack upright only", | |
| "Temperature sensitive", "Do not bend", "Priority customer", "Loyalty member discount applied", | |
| "Back-ordered item included", "Partial shipment OK", "Consolidate packages", "Return label included" | |
| ], | |
| "priority": 9, | |
| "scheduled_time": "14:30:00", | |
| "total_amount": "797.57", | |
| "is_express": true, | |
| "extra_data": { | |
| "shipping": [ | |
| {"zone": 3, "carrier": "FedEx", "cost": 12.5}, | |
| {"zone": 1, "carrier": "UPS", "cost": 8.99}, | |
| {"zone": 5, "carrier": "DHL", "cost": 22.0}, | |
| {"zone": 2, "carrier": "USPS", "cost": 5.99}, | |
| {"zone": 4, "carrier": "FedEx", "cost": 18.75} | |
| ], | |
| "promotions": [ | |
| {"code": "SUMMER24", "discount_pct": 10, "min_order": 50.0}, | |
| {"code": "WELCOME", "discount_pct": 15, "min_order": 0.0}, | |
| {"code": "BULK20", "discount_pct": 20, "min_order": 200.0} | |
| ], | |
| "warehouse_notes": [ | |
| {"facility": "East", "priority": 1, "handler": "Team A"}, | |
| {"facility": "West", "priority": 2, "handler": "Team B"} | |
| ] | |
| }, | |
| "nested_lists": [ | |
| [[1, 2], [3, 4]], [[5, 6]], [[7, 8, 9], [10]], | |
| [[11, 12], [13, 14, 15]], [[16], [17, 18]], [[19, 20]], | |
| [[21, 22, 23]], [[24, 25], [26, 27, 28], [29, 30]], | |
| [[31, 32]], [[33, 34, 35, 36]] | |
| ], | |
| "tags_map": { | |
| "category": ["electronics", "gadgets", "peripherals", "accessories"], | |
| "priority": ["express", "rush", "fragile"], | |
| "warehouse": ["east", "west", "central"], | |
| "shipping": ["ground", "air", "overnight", "two-day"], | |
| "customer_type": ["premium", "loyalty", "wholesale"] | |
| } | |
| }' |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| curl -X POST http://localhost:9000/test-light \ | |
| -H "Content-Type: application/json" \ | |
| -d '{ | |
| "customer": { | |
| "id": 1, | |
| "name": "John Doe", | |
| "status": "active", | |
| "addresses": [ | |
| {"street": "123 Main St", "city": "Springfield", "country": "US", "postal_code": "62701", "coordinates": [39.7817, -89.6501]} | |
| ], | |
| "contacts": [ | |
| {"email": "john@example.com", "phone": "+1234567890", "preferred": true} | |
| ], | |
| "created_at": "2024-01-15T10:30:00" | |
| }, | |
| "total_amount": "80.97" | |
| }' |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # /// script | |
| # requires-python = ">=3.14" | |
| # dependencies = [ | |
| # "fastapi>=0.129.0", | |
| # "logfire[fastapi,sqlite3]>=4.22.0", | |
| # "pydantic[email]>=2.12.5", | |
| # "uvicorn>=0.40.0", | |
| # ] | |
| # /// | |
| import sqlite3 | |
| from datetime import date, datetime, time | |
| from decimal import Decimal | |
| from enum import Enum | |
| from pathlib import Path | |
| from typing import Annotated | |
| import logfire | |
| import uvicorn | |
| from fastapi import Body, FastAPI | |
| from pydantic import BaseModel, EmailStr, Field | |
| logfire.configure() | |
| app = FastAPI() | |
| logfire.instrument_fastapi(app) | |
| logfire.instrument_sqlite3() | |
| logfire.instrument_pydantic(include={"fastapi"}) | |
| class Status(str, Enum): | |
| active = "active" | |
| inactive = "inactive" | |
| pending = "pending" | |
| class Address(BaseModel): | |
| street: str | |
| city: str | |
| country: str | |
| postal_code: str | |
| coordinates: tuple[float, float] | |
| class Contact(BaseModel): | |
| email: EmailStr | |
| phone: str | None = None | |
| preferred: bool = False | |
| class OrderItem(BaseModel): | |
| product_id: int | |
| name: str | |
| order_date: datetime | |
| quantity: int = Field(ge=1) | |
| unit_price: Decimal | |
| discount: float = Field(ge=0, le=1) | |
| tags: list[str] = [] | |
| metadata: dict[str, str | int | float] = {} | |
| class Payment(BaseModel): | |
| method: str | |
| amount: Decimal | |
| currency: str = "USD" | |
| processed_at: datetime | None = None | |
| class Customer(BaseModel): | |
| id: int | |
| name: str | |
| status: Status | |
| addresses: list[Address] | |
| contacts: list[Contact] | |
| created_at: datetime | |
| birth_date: date | None = None | |
| class Data(BaseModel): | |
| customer: Customer | |
| items: list[OrderItem] | |
| payments: list[Payment] | |
| notes: list[str] = [] | |
| priority: int = Field(ge=1, le=10, default=5) | |
| scheduled_time: time | None = None | |
| total_amount: Decimal | |
| is_express: bool = False | |
| extra_data: dict[str, list[dict[str, int | str | float]]] = {} | |
| nested_lists: list[list[list[int]]] = [] | |
| tags_map: dict[str, list[str]] = {} | |
| def _init_connection() -> sqlite3.Connection: | |
| """Create tables and populate data in an in-memory SQLite database.""" | |
| init_db = not Path("blog_post.db").is_file() | |
| conn = sqlite3.connect("blog_post.db", check_same_thread=False) | |
| if init_db: | |
| with logfire.suppress_instrumentation(): | |
| cursor = conn.cursor() | |
| # Create tables | |
| cursor.execute(""" | |
| CREATE TABLE customers ( | |
| id INTEGER PRIMARY KEY, | |
| name TEXT NOT NULL, | |
| email TEXT, | |
| created_at TEXT | |
| ) | |
| """) | |
| cursor.execute(""" | |
| CREATE TABLE products ( | |
| id INTEGER PRIMARY KEY, | |
| name TEXT NOT NULL, | |
| category_id INTEGER, | |
| price REAL | |
| ) | |
| """) | |
| cursor.execute(""" | |
| CREATE TABLE categories ( | |
| id INTEGER PRIMARY KEY, | |
| name TEXT NOT NULL, | |
| parent_id INTEGER | |
| ) | |
| """) | |
| cursor.execute(""" | |
| CREATE TABLE orders ( | |
| id INTEGER PRIMARY KEY, | |
| customer_id INTEGER, | |
| order_date TEXT, | |
| status TEXT, | |
| FOREIGN KEY (customer_id) REFERENCES customers(id) | |
| ) | |
| """) | |
| cursor.execute(""" | |
| CREATE TABLE order_items ( | |
| id INTEGER PRIMARY KEY, | |
| order_id INTEGER, | |
| product_id INTEGER, | |
| quantity INTEGER, | |
| unit_price REAL, | |
| FOREIGN KEY (order_id) REFERENCES orders(id), | |
| FOREIGN KEY (product_id) REFERENCES products(id) | |
| ) | |
| """) | |
| cursor.execute(""" | |
| CREATE TABLE reviews ( | |
| id INTEGER PRIMARY KEY, | |
| product_id INTEGER, | |
| customer_id INTEGER, | |
| rating INTEGER, | |
| comment TEXT, | |
| FOREIGN KEY (product_id) REFERENCES products(id), | |
| FOREIGN KEY (customer_id) REFERENCES customers(id) | |
| ) | |
| """) | |
| # Insert sample data | |
| for i in range(1, 101): | |
| cursor.execute( | |
| "INSERT INTO customers VALUES (?, ?, ?, ?)", | |
| (i, f"Customer {i}", f"customer{i}@example.com", "2024-01-01"), | |
| ) | |
| for i in range(1, 21): | |
| cursor.execute( | |
| "INSERT INTO categories VALUES (?, ?, ?)", | |
| (i, f"Category {i}", i - 1 if i > 1 else None), | |
| ) | |
| for i in range(1, 501): | |
| cursor.execute( | |
| "INSERT INTO products VALUES (?, ?, ?, ?)", | |
| (i, f"Product {i}", (i % 20) + 1, 10.0 + (i % 100)), | |
| ) | |
| for i in range(1, 1001): | |
| cursor.execute( | |
| "INSERT INTO orders VALUES (?, ?, ?, ?)", | |
| ( | |
| i, | |
| (i % 100) + 1, | |
| "2024-06-15", | |
| "completed" if i % 3 == 0 else "pending", | |
| ), | |
| ) | |
| for i in range(1, 5001): | |
| cursor.execute( | |
| "INSERT INTO order_items VALUES (?, ?, ?, ?, ?)", | |
| (i, (i % 1000) + 1, (i % 500) + 1, (i % 10) + 1, 15.0 + (i % 50)), | |
| ) | |
| for i in range(1, 2001): | |
| cursor.execute( | |
| "INSERT INTO reviews VALUES (?, ?, ?, ?, ?)", | |
| ( | |
| i, | |
| (i % 500) + 1, | |
| (i % 100) + 1, | |
| (i % 5) + 1, | |
| f"Review comment {i}", | |
| ), | |
| ) | |
| conn.commit() | |
| return conn | |
| _db_conn = _init_connection() | |
| # Programmatically register 1000 routes with varying paths and methods | |
| _resources = [ | |
| "users", | |
| "products", | |
| "orders", | |
| "reviews", | |
| "categories", | |
| "invoices", | |
| "shipments", | |
| "payments", | |
| "refunds", | |
| "coupons", | |
| "warehouses", | |
| "suppliers", | |
| "employees", | |
| "departments", | |
| "reports", | |
| "tickets", | |
| "comments", | |
| "tags", | |
| "notifications", | |
| "settings", | |
| ] | |
| _actions = [ | |
| "list", | |
| "search", | |
| "export", | |
| "import", | |
| "validate", | |
| "archive", | |
| "restore", | |
| "sync", | |
| "analyze", | |
| "preview", | |
| ] | |
| _methods = ["GET", "POST", "PUT", "PATCH", "DELETE"] | |
| _route_counter = 0 | |
| for _resource in _resources: | |
| for _action in _actions: | |
| for _method in _methods: | |
| _path = f"/api/{_resource}/{_action}" | |
| _route_id = _route_counter | |
| async def _handler( | |
| request_id: int = _route_id, | |
| ) -> dict: | |
| return {"route_id": request_id, "status": "ok"} | |
| app.add_api_route( | |
| _path, | |
| _handler, | |
| methods=[_method], | |
| name=f"{_resource}_{_action}_{_method.lower()}_{_route_id}", | |
| ) | |
| _route_counter += 1 | |
| def run_sqlite_heavy_query(): | |
| """Run a query with multiple joins on the pre-initialized SQLite database.""" | |
| cursor = _db_conn.cursor() | |
| # Complex query with multiple joins | |
| cursor.execute(""" | |
| SELECT | |
| c.id AS customer_id, | |
| c.name AS customer_name, | |
| COUNT(DISTINCT o.id) AS total_orders, | |
| SUM(oi.quantity * oi.unit_price) AS total_spent, | |
| AVG(r.rating) AS avg_rating_given, | |
| cat.name AS most_ordered_category | |
| FROM customers c | |
| LEFT JOIN orders o ON c.id = o.customer_id | |
| LEFT JOIN order_items oi ON o.id = oi.order_id | |
| LEFT JOIN products p ON oi.product_id = p.id | |
| LEFT JOIN categories cat ON p.category_id = cat.id | |
| LEFT JOIN reviews r ON c.id = r.customer_id | |
| GROUP BY c.id, c.name | |
| HAVING total_orders > 0 | |
| ORDER BY total_spent DESC | |
| LIMIT 50 | |
| """) | |
| columns = [description[0] for description in cursor.description] | |
| results = [dict(zip(columns, row)) for row in cursor.fetchall()] | |
| return results | |
| @app.post("/test", response_model=Data) | |
| async def test(body: Annotated[Data, Body()]): | |
| # Run heavy SQLite query | |
| run_sqlite_heavy_query() | |
| # Store the count in the response for visibility | |
| return body | |
| class DataLight(BaseModel): | |
| customer: Customer | |
| total_amount: Decimal | |
| def run_sqlite_light_query(): | |
| """Run a simpler query on the pre-initialized SQLite database. | |
| Only one join is performed. | |
| """ | |
| cursor = _db_conn.cursor() | |
| # Simple query with a single join | |
| cursor.execute(""" | |
| SELECT | |
| c.id AS customer_id, | |
| c.name AS customer_name, | |
| COUNT(o.id) AS total_orders | |
| FROM customers c | |
| LEFT JOIN orders o ON c.id = o.customer_id | |
| GROUP BY c.id, c.name | |
| HAVING total_orders > 0 | |
| ORDER BY total_orders DESC | |
| LIMIT 50 | |
| """) | |
| columns = [description[0] for description in cursor.description] | |
| results = [dict(zip(columns, row)) for row in cursor.fetchall()] | |
| return results | |
| @app.post("/test-light", response_model=DataLight) | |
| async def test_light(body: Annotated[DataLight, Body()]): | |
| # Run light SQLite query | |
| run_sqlite_light_query() | |
| # Store the count in the response for visibility | |
| return body | |
| uvicorn.run(app, port=9000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment