惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

S
SegmentFault 最新的问题
The Last Watchdog
The Last Watchdog
C
Cisco Blogs
L
LINUX DO - 热门话题
T
Tenable Blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Cyberwarzone
Cyberwarzone
O
OpenAI News
The Hacker News
The Hacker News
V
Vulnerabilities – Threatpost
A
Arctic Wolf
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Vercel News
Vercel News
量子位
V2EX - 技术
V2EX - 技术
GbyAI
GbyAI
W
WeLiveSecurity
Recorded Future
Recorded Future
P
Proofpoint News Feed
Project Zero
Project Zero
P
Palo Alto Networks Blog
Microsoft Security Blog
Microsoft Security Blog
S
Security Affairs
Stack Overflow Blog
Stack Overflow Blog
B
Blog
Y
Y Combinator Blog
月光博客
月光博客
K
Kaspersky official blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Latest news
Latest news
Forbes - Security
Forbes - Security
T
Troy Hunt's Blog
T
The Blog of Author Tim Ferriss
C
Check Point Blog
D
DataBreaches.Net
MyScale Blog
MyScale Blog
博客园 - 三生石上(FineUI控件)
博客园 - 聂微东
D
Docker
P
Privacy International News Feed
C
Cybersecurity and Infrastructure Security Agency CISA
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
C
Cyber Attacks, Cyber Crime and Cyber Security
S
Securelist
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
雷峰网
雷峰网
SecWiki News
SecWiki News
腾讯CDC
博客园 - Franky

Stonecharioteer on Tech

I Traced My Traffic Through a Home Tailscale Exit Node What Was I Reading Last? In Three Not-So-Easy Pieces Dogfooding Is Hard Code blocks in your books, finally GoForGo v0.9.0 Merrilin - We built an app to read books I use a Macbook now Data Structures & Algorithms - Preparing for Interviews Using a local DNS namespace for local service discovery Direction KOllector - Publishing KOReader Highlights gbt: branches touched in the last 24 hours A Soiree into Symbols in Ruby Some Smalltalk about Ruby Loops Ruby Blocks Returning from Ruby Blocks, Procs and Lambdas My Linux Laptop Finally Works: How Claude Helped Me Fix Years of Annoyances TIL: Watchexec - Modern File Watching for Development Workflows A Less Busy Mind GoForGo - Learn Go through live examples Migrating My Old Blog to Hugo with Claude The Qtile Window Manager: A Python-Powered Tiling Experience Read the RFCs that Built the Internet Py-x-Protobuf - Or How I Learned to Stop Worrying and Love Protocol Buffers Python Reverse a List New Beginnings Leaving ChainSafe Systems Screen Lock for Cinnamon Desktop using Zenity and Terminal Commands Crews Not Teams A System for Getting Better at LeetCode So Far So Rust Retrying HTTP Requests with Rust A Primer on Control Charts Learning Rust Explicit is Better than Implicit: Rust for Pythonistas Using Custom Delimiters in Jinja Templates TIL: Creating Fixed Length Iterables in Python Documentation Without Assumption Vagrant Python - A Reflection in 2022 Learning Golang No, A Virtual Machine Is Not Enough: Why Developers Need Native Linux Empathy in Tech For Those Who Came in Late A Weekend With PostgreSQL TIL: Gooey and Python Fire for Quick GUIs and CLIs TIL: 2ality - Dr. Axel Rauschmayer's JavaScript Blog TIL: MassDNS - High-Performance Bulk DNS Lookups TIL: Matomo Analytics, Google Tech Writing, Memory Programming, and NES TV Signals TIL: MontyDB - MongoDB Implemented in Python Returning to the Craft of Programming TIL: CPUFetch, OneFetch, and Learn CSS TIL: DNS Performance Testing and Pi-hole with Unbound TIL: Eli Bendersky's Blog, Awesome By Example, NoCoDB, and Martin Kleppmann TIL: CRDTs, Extreme HTTP Performance, and BYTEPATH Game TIL: AutoInvent, ASGI, Python Packaging, RAPIDS GPU Computing, and FlaskCon TIL: MangaDesk - Terminal Client for MangaDex TIL: McFly - Smart Shell History Search TIL: Siege Load Testing and Awesome FastAPI Resources TIL: Ventoy Bootable USB and Justniffer Network Analysis TIL: CLI Code Review, Git Split Diffs, and Internal Combustion Engine TIL: Benford's Law, Web Security Headers, Event Sourcing, and Mozilla Security Guidelines How to Write Documentation - The README.md File The Importance of Documentation TIL: NNgroup UX Research, SponsorBlock, and Labella Python Library TIL: The Little Book of Rust Macros and Rust Performance Book TIL: Git-Bug Distributed Issue Tracker and Omni Kubernetes Monitoring TIL: Zellij - Modern Terminal Multiplexer TIL: How Discord Handles 2.5 Million Concurrent Voice Users TIL: Volumio - The Audiophile Music Player TIL: Areopagitica - Milton's Defense of Free Speech TIL: Fast Node Manager, Zoxide Smart CD, Technical Writing, PyO3, and Qubes OS TIL: Slurm Workload Manager for HPC Clusters TIL: Data Visualization Guide and Oso Authorization Academy TIL: CORS Deep Dive, Piku Tiny PaaS, Rust Strings, and Deno Standard Library TIL: Raspberry Pi OS Development, Vim Beginner Guide, Password Management, and QueryBook TIL: uBlock Origin Performance Optimization on Firefox TIL: Breaking PostgreSQL at Scale and LeetCode Problem Patterns TIL: Awesome Tmux Resources for Terminal Multiplexing TIL: Grit - A Multitree-Based Personal Task Manager TIL: Lens 4.2 Kubernetes IDE, Shell Scripting Guide, and Dark HTTP Server Do The Job You Hate So You Won't Hate The Job You Love TIL: Innernet VPN Solution and NoteCalc Calculator App TIL: Argo CD for GitOps and Lens Kubernetes IDE TIL: Modern Rust CLI Tools - System Monitoring, HTTP Requests, and DNS TIL: tz - A Time Zone Helper Tool TIL: Distributed Systems Education, Fallacies, and Self-Hosted Internet Archiving TIL: Real-Time Voice Cloning Technology TIL: ChartMuseum for Helm, AMD's Corporate Journey, and Kubernetes Pod Scaling TIL: Docker and Kubernetes Tools - Whaler, Descheduler, and Dive TIL: Post-Mortem Collection, Terminal Plotting, and Technical Twitter TIL: Dark Mode Toggle Web Component by Google Chrome Labs TIL: Python eval(), exec(), and compile() Functions TIL: Camelot PDF Tables, PostgreSQL Row Level Security, Zerodha Varsity, and Write Yourself a Git TIL: fuser Command for Process and File Investigation TIL: i Hate Regex - The Ultimate Regex Cheat Sheet TIL: Dolt - Git for Data and Database Version Control TIL: x86 Assembly Programming and SafeEyes Break Reminder TIL: Comprehensive Distributed Systems Reading List TIL: Cosmopolitan C Library, Distributed Systems Book, High Performance Browser Networking, and Rust Roguelike Tutorial
TIL: Python Performance, REST API Design, Rich Terminal Trees, and Python Launcher
2021-02-23 · via Stonecharioteer on Tech

12 Requests Per Second in Python

12 requests per second in Python

Detailed analysis of Python web application performance optimization:

The Challenge:

  • Performance Bottlenecks: Identifying what limits Python web app throughput
  • Realistic Benchmarking: Testing with real-world scenarios, not just hello world
  • Optimization Strategies: Practical techniques for improving performance
  • Infrastructure Considerations: Hardware and deployment factors

Performance Analysis:

Baseline Measurements:

  • Flask Application: Basic REST API with database operations
  • Load Testing: Using realistic request patterns and data
  • Bottleneck Identification: CPU, I/O, memory, and network constraints
  • Profiling Tools: cProfile, line_profiler, and memory profilers

Optimization Techniques:

Database Optimization:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
# Connection pooling
from sqlalchemy.pool import QueuePool
engine = create_engine(
    'postgresql://...',
    poolclass=QueuePool,
    pool_size=20,
    max_overflow=30
)

# Query optimization
# Before: N+1 queries
users = User.query.all()
for user in users:
    print(user.profile.name)  # Additional query per user

# After: Eager loading
users = User.query.options(joinedload(User.profile)).all()
for user in users:
    print(user.profile.name)  # No additional queries

Caching Strategies:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
import redis
from functools import wraps

cache = redis.Redis()

def cached(expiration=3600):
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            key = f"{func.__name__}:{hash(str(args) + str(kwargs))}"
            result = cache.get(key)
            if result is None:
                result = func(*args, **kwargs)
                cache.setex(key, expiration, result)
            return result
        return wrapper
    return decorator

Key Insights:

  • Database is Usually the Bottleneck: Optimize queries first
  • Connection Pooling: Essential for concurrent request handling
  • Caching: Dramatic improvements for repeated operations
  • Async Processing: Use Celery for heavy background tasks

Designing Beautiful REST + JSON APIs

Oktane17: Designing Beautiful REST + JSON APIs - YouTube

Comprehensive guide to REST API design principles:

Core Design Principles:

Resource-Oriented Design:

GET    /users           # List users
POST   /users           # Create user
GET    /users/123       # Get specific user
PUT    /users/123       # Update user
DELETE /users/123       # Delete user

Consistent Naming:

  • Plural Nouns: Use /users not /user
  • Hierarchical: /users/123/posts for nested resources
  • Lowercase: Consistent casing throughout API
  • Hyphen Separation: Use /user-profiles not /userProfiles

REST Must Be Hypertext-Driven

REST APIs must be hypertext-driven » Untangled

Roy Fielding’s clarification on true REST principles:

HATEOAS (Hypermedia as the Engine of Application State):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
{
  "id": 123,
  "name": "John Doe",
  "email": "[email protected]",
  "_links": {
    "self": { "href": "/users/123" },
    "posts": { "href": "/users/123/posts" },
    "edit": { "href": "/users/123", "method": "PUT" },
    "delete": { "href": "/users/123", "method": "DELETE" }
  }
}

API Evolution:

  • Discoverability: Clients discover available actions through links
  • Loose Coupling: Clients don’t hardcode URLs
  • Version Independence: Links adapt to API changes
  • Self-Documenting: API structure evident from responses

HTTP Status Codes:

200 OK              # Successful GET, PUT
201 Created         # Successful POST
204 No Content      # Successful DELETE
400 Bad Request     # Client error
401 Unauthorized    # Authentication required
403 Forbidden       # Insufficient permissions
404 Not Found       # Resource doesn't exist
500 Internal Error  # Server error

Rich Terminal Tree Views

Rendering a tree view in the terminal with Python and Rich

Creating beautiful terminal interfaces with the Rich library:

Rich Library Features:

  • Styled Output: Colors, bold, italic, underline in terminal
  • Complex Layouts: Tables, panels, columns, and trees
  • Progress Bars: Beautiful progress indicators
  • Syntax Highlighting: Code syntax highlighting in terminal

Tree Rendering:

Basic Tree Structure:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
from rich.console import Console
from rich.tree import Tree

console = Console()

# Create root node
tree = Tree("📁 Project Root")

# Add branches
src_branch = tree.add("📁 src")
src_branch.add("🐍 main.py")
src_branch.add("🐍 utils.py")

tests_branch = tree.add("📁 tests")
tests_branch.add("🧪 test_main.py")
tests_branch.add("🧪 test_utils.py")

tree.add("📄 README.md")
tree.add("📄 requirements.txt")

console.print(tree)

File System Tree:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
import os
from pathlib import Path

def create_file_tree(directory: Path) -> Tree:
    tree = Tree(f"📁 {directory.name}")

    for item in sorted(directory.iterdir()):
        if item.is_dir():
            # Recursively add subdirectories
            subtree = create_file_tree(item)
            tree.add(subtree)
        else:
            # Add files with appropriate icons
            icon = "🐍" if item.suffix == ".py" else "📄"
            tree.add(f"{icon} {item.name}")

    return tree

Advanced Features:

  • Styling: Custom colors and styles for different node types
  • Interactive: Combine with click events for navigation
  • Live Updates: Dynamic tree updates for monitoring
  • Large Datasets: Efficient rendering of large hierarchies

python-launcher - crates.io

Rust-based Python version launcher and manager:

What It Does:

  • Version Detection: Automatically detects appropriate Python version
  • PEP 514 Compliance: Follows Python launcher specification
  • Fast Performance: Rust implementation for speed
  • Cross-Platform: Works on Windows, macOS, and Linux

Key Features:

Automatic Version Selection:

1
2
3
4
5
6
# Checks pyproject.toml, .python-version, or uses default
python3 script.py

# Explicit version specification
python3.9 script.py
python3.10 -m pip install package

Configuration:

1
2
3
4
# pyproject.toml
[tool.python-launcher]
default = "3.10"
prefer-active-venv = true

Advantages:

  • Performance: Faster startup than shell-based launchers
  • Reliability: Robust version detection and selection
  • Standards Compliance: Follows Python packaging standards
  • Modern Implementation: Written in modern Rust with good error handling

Each resource demonstrates different aspects of Python ecosystem optimization - from web application performance tuning to API design best practices, terminal UI enhancement, and development tool innovation.