今日已更新 339 条资讯 | 累计 19899 条内容
关于我们

标签:#fastapi

找到 12 篇相关文章

AI 资讯

Did you ever face "stale singleton httpx connection" and "cold-start connection problem" problem, Well I did tonight.

It is been while I am learning and build around FastAPI. So there is a project where I was thinking how to add this new feature over exiting one. Like what changes I need to make in database which need to be reflected in my backend and frontend. I already lunched the web locally. Problem started When I when back to the web and reload it it shows this error: ERROR: ConnectTimeout: Unauthorized 401. I was like what? Why? I thougth there is some issue with login endpoint or refresh token function. When i did some debugging and found some new information which is: "Either Supabase's edge/pooler (or OS, or an intermediate proxy/NAT) silently kills those idle connections server-side after some timeout but client-side pool doesn't know that." As I was doing nothing in become idle state so to save the resources server side silently close that particular connection. So I came back and try to connect it give this error. First thought come it my mind after this was there should be a way to automatically check this idle state and if user was in ideal state then create a new connection. Proposed Solutions After a while I come up with these solution: Calculate the Idle time: if it is more then server connection timeout then establish new connection. Retry logic: retry once on the specific connection errors. I thought this will work but This again give me error then this new issue I faced. Cold-start connection problem There is something call dual-stack (IPv4 and IPv6) networks and Happy Eyeballs is a network mechanism which automatically move to IPv4 connection if IPv6 fails. But supabase-py uses httpx and it doesn't support Happy Eyeballs. So in first try after the connection time out it try to establish IPv6 connection which is not routeable in most Pakistani ISPs and ultimately it fails and wait for timeout. There is no way to try it again for IPv4. So we have to do it manually. So this error help me to learn many thing in process. Share your thoughts.

2026-07-09 原文 →
AI 资讯

Hardening my own Nmap web UI: the security holes I shipped, and what actually saved me

I built a web front end for an Nmap-based port scanner: a FastAPI backend, a React dashboard, background scan jobs, a plugin system. It worked. Then I sat down and audited it like an attacker would — and found a stack of real weaknesses, plus a lesson in why you verify an exploit before you call it one. This is the honest version: the holes I found, the unauthenticated-RCE chain I thought I had, why it didn't actually fire, and the hardening I shipped anyway. Repo: https://github.com/DipesThapa/PortScanner This is my own project, audited and fixed by me. No third-party systems were touched. Scanners are dual-use — only ever point one at hosts you own or are authorised to test. Hole 1: no authentication, anywhere The foundation: every API route and the /ws/status WebSocket were open. No API key, no session. The Dockerfile bound 0.0.0.0:8000 and ran as root. Anyone who could reach the port could drive scans, hit the upload endpoint, and read every job's logs. api_router = APIRouter () # no dependencies — fully open This is the real, unambiguous problem. Everything below is only interesting because it sat behind no auth. Hole 2: an upload endpoint that allowlisted its own files Deep-dive follow-up commands ran against an allowlist — good instinct. But an upload endpoint wrote a file, chmod +x 'd it, and then added it to that same allowlist: for item in scripts_dir . glob ( " * " ): if item . is_file (): allowed . add ( str ( item . absolute ())) # upload authorises itself An allowlist any input can extend isn't an allowlist. This is a genuine design footgun. Hole 3: the RCE I thought I had — and why it didn't fire Here's the chain I got excited about: the scan target flows toward Nmap's argv, and it's subprocess.run(..., shell=False) . No shell injection — but you don't need a shell to abuse Nmap. If a target became --script=/uploaded.nse , Nmap would load and run that NSE (Lua) script, and NSE can call os.execute . Upload a malicious .nse (Hole 2), get Nmap to load it

2026-07-07 原文 →
AI 资讯

Stop Overtraining: Build an AI Agent to Auto-Sync Your Fitness Plan with Your Heart Rate (LangGraph + Notion)

We’ve all been there. You have a "Leg Day" scheduled in your Notion database, but you woke up feeling like a truck hit you. Your Apple Watch says your Heart Rate Variability (HRV) is in the gutter, but your rigid calendar doesn't care. Usually, you’d either push through and risk injury or manually move cards around in Notion—which is a friction-filled nightmare. In this tutorial, we are building a Self-Optimizing Health Agent using LangGraph , Notion API , and HealthKit . This agent acts as a closed-loop system: it analyzes your physiological recovery data, reasons about your physical state using an LLM, and automatically rewrites your training schedule. By mastering AI agents , LLM orchestration , and fitness automation , you’ll turn your static "To-Do" list into a dynamic "Should-Do" list. 🥑 The Architecture: The Bio-Feedback Loop Using LangGraph , we can treat our fitness logic as a state machine. Unlike a linear script, a graph allows our agent to decide whether it needs to fetch more context (like yesterday's sleep) before making a final decision on your workout. graph TD Start((Start)) --> FetchHRV[Fetch HRV Data via HealthKit] FetchHRV --> CheckRecovery{LLM: Analyze Recovery} CheckRecovery -- "Low Recovery (Fatigued)" --> ModifyNotion[Action: Downgrade Workout Intensity] CheckRecovery -- "High Recovery (Fresh)" --> KeepNotion[Action: Maintain/Boost Intensity] ModifyNotion --> UpdateNotion[Update Notion Page] KeepNotion --> UpdateNotion UpdateNotion --> End((Done)) style CheckRecovery fill:#f96,stroke:#333,stroke-width:2px style FetchHRV fill:#bbf,stroke:#333 Prerequisites Before we dive into the code, ensure you have: Python 3.10+ LangChain & LangGraph installed ( pip install langgraph langchain_openai ) Notion Integration Token (with access to your workout database) HealthKit SDK (Note: Since we are in a Python environment, we'll simulate the HealthKit fetcher, though in a real-world scenario, this would be bridged via a FastAPI endpoint from an iOS app). St

2026-07-05 原文 →
AI 资讯

Shifting Left: How TDD Became the Foundation of SokoFlow's Core Engine

SokoFlow Build Log — Month 1 of 4 Last semester I set out on a new strategic plan to level up my software development skills through deliberate, project-based learning. That work produced one of the most ambitious things I've built so far: Sim-Pesa , a local-first transactional appliance that lets developers working in the M-Pesa ecosystem test and simulate STK Push workflows entirely on their own machines, without depending on the Daraja sandbox. I documented that build in 16 weekly posts, which you can find here . This semester, the focus shifts — from fintech foundations to cloud-native integration and real-world systems. The flagship project is SokoFlow , a conversational ERP for small Kenyan shopkeepers to track inventory and record sales entirely through WhatsApp chat. No app to download, no training session required — just natural language. Where Sim-Pesa lived in a controlled, predictable transactional world, SokoFlow steps into the mess of cloud-native reality: third-party API failures, webhook signature verification, the statelessness of HTTP, and container orchestration. The target audience shifts too — Kenyan SMEs operating on infrastructure that is often unreliable by design, not by exception. It's an ambitious project, but the goal was always to learn as much as possible from it. With the plan in place, I got to work. 1. The Vision of a Headless ERP The first real question I had to answer before writing a line of code: what does "headless" actually mean? Headless architecture decouples the frontend — the "head," or user interface — from the backend, the "body" that holds the data and business logic. A conventional ERP bundles both: backend plus a dashboard or UI on top. A headless ERP, by contrast, is just the engine. The brain. There's no built-in screen. So how do users interact with a system that has no interface of its own? SokoFlow doesn't actually care. It could be: WhatsApp SMS A web app A mobile app A voice assistant In this case, the "frontend

2026-06-30 原文 →
AI 资讯

"You code. We cloud." — Why the Cleverest FastAPI Hosting Headline Still Misses

There's a headline pattern that feels like sharp marketing writing but quietly costs conversions. "You code. We cloud." It's clever. The parallel structure is tight. It names a clear division of labor. But it describes the service delivery model , not the developer outcome — and those are different things to someone scanning a landing page in five seconds. The audit fastapicloud.com is a managed hosting product built specifically for FastAPI developers. The hero H1 is: "You code. We cloud." On the surface this reads as clean, confident B2B positioning. In practice, it names the mechanism: You = who does the coding We cloud = who handles the infrastructure What's missing is the output. What does the developer actually walk away with? The gap (mechanism-first H1): The headline describes the service model without anchoring it in the developer outcome. The visitor has to make a three-step inference: "they handle the cloud" → "that means I don't do ops" → "so my app gets to production without a week of DevOps work." In five seconds of scrolling, most won't finish that chain. The headline earns a nod of recognition. It doesn't earn the scroll. The fix One line changes the frame completely. Before: "You code. We cloud." After: "Your FastAPI app is live in production — zero config rabbit holes, zero deploy-day surprises." The rewrite keeps the same promise — they handle the infrastructure — but anchors it in the developer's world. The outcome (app in production) is first. The pain points ("config rabbit holes," "deploy-day surprises") are the exact things a FastAPI developer has already lived through. "Zero config rabbit holes" names the experience of spinning up a production server for the first time. "Zero deploy-day surprises" names the dread: the Sunday night broken deploy that wasn't caught in staging. Any backend developer who reads that line knows exactly what it's describing. The mechanism (managed cloud, they handle ops) is still implied. But the headline earns the

2026-06-23 原文 →
AI 资讯

From Pixels to Proteins: Building a Precise Dietary Analysis System with GPT-4o and SAM

Have you ever tried to track your calories by manually searching for "half-eaten avocado toast" in a database? It’s a nightmare. While basic AI Computer Vision can identify an "apple," traditional models often fail at the granular level—distinguishing between 100g and 250g of pasta or identifying hidden toppings in a complex salad. In this tutorial, we are building a high-precision food nutrition AI engine. By combining the Segment Anything Model (SAM) for pixel-perfect object isolation and GPT-4o Vision for multi-modal reasoning and volume estimation, we can transform a simple smartphone photo into a detailed nutritional report. If you’re looking to dive deeper into production-grade AI patterns, I highly recommend checking out the advanced engineering guides at WellAlly Blog , which served as a major inspiration for this architecture. 🏗️ The Architecture: A Hybrid Vision Pipeline To achieve high accuracy, we don't just throw an image at an LLM. We use a "Segment-then-Analyze" pipeline. This ensures the LLM focuses on specific regions of interest (ROIs) rather than getting distracted by the background. graph TD A[User Uploads Food Image] --> B[Pre-processing with OpenCV] B --> C[SAM: Segment Anything Model] C --> D{Multi-Object Masking} D -->|Mask 1: Protein| E[GPT-4o Vision Reasoning] D -->|Mask 2: Carbs| E D -->|Mask 3: Veggies| E E --> F[Nutrient Mapping & Volume Estimation] F --> G[FastAPI Response: JSON Schema] G --> H[Final Dashboard] 🛠️ Prerequisites Before we start, ensure you have your environment ready: Python 3.10+ GPT-4o API Key (OpenAI) SAM Weights ( sam_vit_h_4b8939.pth ) Tech Stack : FastAPI , OpenCV , PyTorch , segment-anything 🚀 Step-by-Step Implementation 1. Object Segmentation with SAM First, we use Meta’s SAM to generate masks. This allows us to "cut out" each individual food item. import numpy as np import cv2 from segment_anything import sam_model_registry , SamPredictor # Initialize SAM sam_checkpoint = " sam_vit_h_4b8939.pth " model_type = "

2026-06-18 原文 →
AI 资讯

FastAPI for AI Engineers - Part 4: Stop Bad Data Before It Breaks Your API (Pydantic and Data Validation)

In the previous article, we connected our FastAPI application to a database using SQLite and SQLAlchemy. We also used classes like: class StudentCreate ( BaseModel ): name : str department : str cgpa : float without fully understanding what was happening behind the scenes. Today, we'll fix that. If you haven't read it check it out: FastAPI for AI Engineers - Part 3: Connecting to a database Ananya S Ananya S Ananya S Follow Jun 6 FastAPI for AI Engineers - Part 3: Connecting to a database # ai # fastapi # python # backend 6 reactions Add Comment 6 min read Why Do We Need Data Validation? Imagine you're building a weather application. A user asks: What is the temperature in Chennai? A valid response might be: 35 or 35°C But what if the API returns: Sunny This is clearly wrong. Temperature should be represented as a number. Even if the value itself is inaccurate, we still know that temperature must be numeric. This is where validation becomes important. Validation allows us to define rules about what data is acceptable before it enters our application. For example: Temperature should be numeric Age cannot be negative CGPA should be between 0 and 10 Email addresses should follow a valid format Without validation, applications can receive invalid data and behave unexpectedly. The Problem Without Validation Consider a student registration API. @app.post ( " /student " ) def create_student ( student ): return student A user could send: { "name" : "Ananya" , "cgpa" : "Excellent" } The API would accept it. But a CGPA should be a number, not text. As applications grow, manually checking every field becomes difficult. We need a better solution. Enter Pydantic Pydantic is a Python library used for data validation. FastAPI uses Pydantic extensively behind the scenes. Instead of manually validating data, we define a schema. from pydantic import BaseModel class Student ( BaseModel ): name : str cgpa : float Now FastAPI knows: name must be a string cgpa must be a floating-point nu

2026-06-09 原文 →
AI 资讯

FastAPI for AI Engineers - Part 3: Connecting to a database

In the previous article, we explored how to build our first CRUD API using FastAPI. While our API worked correctly, there was one major problem. We were storing data inside Python lists, which exist only in memory. If you've ever wondered how applications like Instagram, LinkedIn, or ChatGPT remember information even after a server restart, the answer is simple: databases. In this article, we'll solve the problem of in-memory storage by connecting our FastAPI application to SQLite using SQLAlchemy. If you haven't read the previous post, check it out: FastAPI for AI Engineers - Part 2: Building Your First CRUD API Ananya S Ananya S Ananya S Follow Jun 1 FastAPI for AI Engineers - Part 2: Building Your First CRUD API # ai # backend # fastapi # python 7 reactions Comments Add Comment 4 min read By the end of this article, you'll understand: Why in-memory storage is a problem What SQLite is What SQLAlchemy is How ORM works How to create database tables using Python classes How to perform CRUD operations using a real database The Problem with In-Memory Storage Previously, our application stored students inside a Python list. students = [ { " id " : 1 , " name " : " Ananya " , " department " : " CSE " , " cgpa " : 8.9 } ] This worked for learning CRUD operations. However, consider what happens when the server restarts: FastAPI Server Stops ↓ Python Memory Cleared ↓ All Student Data Lost This is unacceptable in real-world applications. We need a place where data can survive application restarts. This is where databases come in. What is SQLite? SQLite is a lightweight relational database. Unlike MySQL or PostgreSQL, SQLite doesn't require a separate database server. Instead, everything is stored inside a single file. students.db Advantages of SQLite: No installation required Lightweight Easy to learn Perfect for local development Great for small projects For this article, we'll use SQLite. What is SQLAlchemy? Before SQLAlchemy, developers often wrote raw SQL queries. Exampl

2026-06-06 原文 →
AI 资讯

Stop Juggling 5 Tools , Python's uv Does It All (And It's Blazing Fast)

If you've been writing Python for more than a year, you know the ritual. A new project. A fresh terminal. And then: pyenv install 3.12.3 pyenv local 3.12.3 python -m venv .venv source .venv/bin/activate pip install pip --upgrade pip install -r requirements.txt Six commands before you've written a single line of code. And that's if nothing breaks. Enter uv a single binary that replaces pip , virtualenv , pip-tools , pyenv , and pipx . Written in Rust. 10–100x faster than pip. And honestly, one of the most pleasant tools I've used in the Python ecosystem in years. Let's dig into it. What Even Is uv ? uv is a Python package and project manager built by Astral , the same team behind ruff , the linter that everyone switched to and never looked back. The goal is simple: be the Cargo for Python . One tool, one lockfile, no friction. It's a standalone binary with zero Python dependencies, which means it works even before Python is installed. Installing uv # macOS / Linux curl -LsSf https://astral.sh/uv/install.sh | sh # Windows (PowerShell) powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex" # Or via pip if you prefer pip install uv Verify: uv --version # uv 0.9.x The Speed Claim Is It Real? Yes. Embarrassingly so. Here's a timed comparison on Apple Silicon (Python 3.14): Operation pip / venv uv Create virtual env ~2 seconds 35 milliseconds Install FastAPI + deps (cold) ~12s ~1.2s Install with warm cache ~8s ~0.1s The warm cache case is where uv really shines it uses a global cache and hard-links packages into environments instead of copying them. If you've installed requests in any previous project, your next project gets it nearly instantly. Starting a New Project This is where uv feels like a completely different world: uv init my-api cd my-api That single command gives you: my-api/ ├── .git/ ├── .venv/ ← already created ├── .python-version ├── pyproject.toml ├── README.md └── main.py No separate python -m venv , no git init , no template c

2026-06-03 原文 →
AI 资讯

Building KindaSeen with FastAPI, Next.js, and PostgreSQL

“Did We Already Watch This?” — Building KindaSeen with FastAPI and Next.js A few months ago, my friends and I kept running into the same question whenever we talked about movies, dramas, anime, or variety shows: “Did we already watch this before?” Sometimes we remembered the title but forgot whether we had finished it. Other times, we completely forgot we had already seen it at all. That simple problem inspired me to build KindaSeen, a full-stack personal media repository designed to help users track and organize the media they’ve consumed in one centralized platform. The goal of the project was not only to create a useful application, but also to gain hands-on experience building a real-world full-stack system with modern web technologies. What KindaSeen Currently Supports User authentication with Supabase CRUD operations for personal media records TMDB-powered search functionality Watchlist system Favorites system Persistent PostgreSQL storage Dockerized backend deployment Separate frontend/backend deployment workflow Tech Stack Frontend Next.js React Tailwind CSS Shadcn/ui Vercel deployment Backend FastAPI PostgreSQL Docker Render deployment External Services Supabase Authentication TMDB API integration One of the main goals of this project was to simulate a more realistic production workflow by using a decoupled frontend/backend architecture instead of building everything inside a single monolithic application. In this article, I’ll share: Why I chose this architecture How I integrated TMDB into the application Challenges I faced during deployment What I Learned From Building KindaSeen Why I Chose This Architecture Instead of building a monolith using Next.js API routes, I decided to decouple the application into a Next.js frontend and a FastAPI backend. This decision was driven by three main factors: AI Compatibility & Future Proofing : While researching the job market, I noticed that most companies building AI products heavily rely on Python. By choosing FastA

2026-06-02 原文 →
AI 资讯

PostgreSQL LISTEN/NOTIFY for Real-Time Multi-Tenant Events: Ditching Polling and WebSocket Complexity

PostgreSQL LISTEN/NOTIFY for Real-Time Multi-Tenant Events: Ditching Polling and WebSocket Complexity I've shipped real-time features in CitizenApp using three different approaches: naive polling (embarrassing), Redis pub/sub (overkill), and now PostgreSQL's native LISTEN/NOTIFY. The third option is what I should have started with. Most teams reach for Redis or RabbitMQ the moment they need real-time updates. It's the conventional wisdom. But here's the truth: if you're already running PostgreSQL, you have a battle-tested pub/sub system sitting right there. It handles multi-tenancy correctly, scales to thousands of concurrent connections, and eliminates an entire infrastructure dependency—which matters when you're deploying to Render or Vercel where every added service is friction. Why LISTEN/NOTIFY beats the alternatives Polling is dead. HTTP requests every 2-5 seconds for "new notifications"? That's technical debt masquerading as simplicity. It wastes bandwidth, kills your database with unnecessary queries, and users see stale data. Redis is powerful but expensive. Not just in dollars—in operational overhead. You need to manage connection pools, handle failover, monitor memory usage, and keep another service running in production. At CitizenApp's scale (thousands of concurrent tenants), we were paying $50/month for Redis on top of Render just to broadcast notifications that PostgreSQL could handle natively. WebSockets without a broker are a nightmare. If you're running multiple FastAPI workers (and you should be), a WebSocket connection to Worker A doesn't know about events published by Worker B. You need a message broker to fan-out events across processes. Unless you use PostgreSQL LISTEN/NOTIFY, which handles that automatically. PostgreSQL's pub/sub is: Transactional. Notifications only fire after a transaction commits. Tenant-aware. Use channel names like tenant_123_notifications and broadcast only to the right subscribers. Zero extra infrastructure. It's part

2026-06-01 原文 →
AI 资讯

I built a RAG pipeline from scratch — no LangChain, just FastAPI + FAISS

Most RAG tutorials I found were either "pip install langchain and you're done" or 50-page academic papers. I wanted something in between — a pipeline I could actually explain in an interview, where I understood every line. So I built one from scratch. No LangChain, no LlamaIndex, no frameworks. Just FastAPI, FAISS, sentence-transformers, and an LLM API. Here's what I built, what worked, and what broke. The architecture PDF --> extract text (pypdf) --> chunk (500 char, 50 overlap) --> embed (MiniLM-L6-v2) | v question --> embed --> FAISS top-k search --> build prompt with chunks --> LLM --> answer + sources Five Python files, ~300 lines total: File Responsibility main.py FastAPI app, 3 endpoints, prompt engineering pdf_loader.py PDF text extraction via pypdf rag.py Chunking + embedding store.py FAISS vector store wrapper llm.py Swappable LLM client (Groq / OpenAI / Anthropic) How the upload works When you POST a PDF to /upload , three things happen: 1. Text extraction — pypdf reads each page and returns the raw text. Pages with no extractable text (scanned images) are skipped. 2. Chunking — each page is split into ~500-character chunks with 50 characters of overlap. The overlap prevents losing context at chunk boundaries. CHUNK_SIZE = 500 CHUNK_OVERLAP = 50 def chunk_pages ( pages ): chunks = [] chunk_id = 0 for text , page_num in pages : start = 0 while start < len ( text ): end = min ( start + CHUNK_SIZE , len ( text )) chunk_text = text [ start : end ]. strip () if chunk_text : chunks . append ( Chunk ( chunk_id = chunk_id , text = chunk_text , page = page_num )) chunk_id += 1 if end == len ( text ): break start = end - CHUNK_OVERLAP return chunks 3. Embedding — each chunk is embedded into a 384-dimensional vector using all-MiniLM-L6-v2 . This runs locally on CPU, no API call needed. Vectors are normalized so we can use inner product as cosine similarity. def embed_texts ( texts ): model = get_embed_model () # lazy-loaded singleton vectors = model . encode ( texts

2026-05-31 原文 →