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

推荐订阅源

雷峰网
雷峰网
S
Securelist
Y
Y Combinator Blog
云风的 BLOG
云风的 BLOG
A
About on SuperTechFans
Martin Fowler
Martin Fowler
量子位
D
Docker
G
Google Developers Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
U
Unit 42
S
Secure Thoughts
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
K
Kaspersky official blog
NISL@THU
NISL@THU
T
Tailwind CSS Blog
I
Intezer
T
Threat Research - Cisco Blogs
P
Privacy & Cybersecurity Law Blog
D
DataBreaches.Net
Engineering at Meta
Engineering at Meta
C
Cyber Attacks, Cyber Crime and Cyber Security
F
Full Disclosure
Microsoft Security Blog
Microsoft Security Blog
Cisco Talos Blog
Cisco Talos Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Simon Willison's Weblog
Simon Willison's Weblog
Vercel News
Vercel News
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
F
Fortinet All Blogs
W
WeLiveSecurity
C
Cisco Blogs
Security Latest
Security Latest
PCI Perspectives
PCI Perspectives
L
LangChain Blog
P
Palo Alto Networks Blog
IT之家
IT之家
aimingoo的专栏
aimingoo的专栏
Apple Machine Learning Research
Apple Machine Learning Research
宝玉的分享
宝玉的分享
Blog — PlanetScale
Blog — PlanetScale
Help Net Security
Help Net Security
Microsoft Azure Blog
Microsoft Azure Blog
Project Zero
Project Zero
G
GRAHAM CLULEY
Recent Commits to openclaw:main
Recent Commits to openclaw:main
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
L
Lohrmann on Cybersecurity
Cloudbric
Cloudbric
D
Darknet – Hacking Tools, Hacker News & Cyber Security

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Connecting a Biometric Fingerprint Device to a Rails Web App Using Python — A Complete Walkthrough
Lakshay Tyag · 2026-05-07 · via DEV Community

👋 Introduction

When I was building a gym management system for a real gym in New Delhi, one of the most interesting challenges was connecting a physical biometric fingerprint device to my cloud-hosted Ruby on Rails app.

The gym wanted to:

  • ✅ Track member attendance via fingerprint scanning
  • Automatically deny access to members with expired subscriptions
  • ✅ Prevent duplicate check-ins
  • ✅ See attendance on the admin dashboard in real-time

The catch? The biometric device only speaks to the local network. My Rails app is hosted on Render (cloud). They can't talk to each other directly.

The solution? A Python bridge script running on the gym's laptop that reads fingerprint punches from the device and forwards them to the Rails API via HTTP.

This post covers the entire pipeline — Python bridge → Rails API → Database — with real code from production.


🏗️ Architecture: The Full Pipeline

┌─────────────────────┐
│  ZK Fingerprint      │
│  Biometric Device    │
│  (192.168.1.201)     │
└──────────┬──────────┘
           │ pyzk SDK (TCP)
           ▼
┌──────────────────────────┐
│  Python Bridge Script    │
│  (bridge.py)             │
│  Runs on gym laptop      │
│  Polls every 20 seconds  │
│  Deduplicates locally    │
└──────────┬───────────────┘
           │ HTTP POST (JSON)
           ▼
┌──────────────────────────────────────┐
│  Ruby on Rails API (Render cloud)    │
│  POST /api/biometric_attendances     │
│                                      │
│  1. Find biometric mapping           │
│  2. Check for duplicate punches      │
│  3. Validate subscription            │
│  4. Store attendance                 │
│  5. Return ALLOWED / DENIED          │
└──────────┬───────────────────────────┘
           │
           ▼
┌──────────────────────────────────────┐
│  MySQL Database (CleverCloud)        │
│                                      │
│  trn_member_biometric_mappings       │
│  trn_member_attendances              │
│  trn_member_subscriptions            │
└──────────────────────────────────────┘

Enter fullscreen mode Exit fullscreen mode

Three components, two languages, one seamless flow.


🐍 Part 1: The Python Bridge (Gym Laptop Side)

The Problem

The biometric device (a ZK-based fingerprint scanner) is on the gym's local network at 192.168.1.201. It stores fingerprints and punch records internally. It has no concept of "calling a web API."

My Rails app is hosted on Render — a cloud server that the device can't reach directly.

Solution: A Python script that acts as the middleman — reads from the device using the pyzk SDK, and forwards punches to Rails via HTTP.

Configuration

# biometric_bridge/config.py

DEVICE_IP = "192.168.1.201"
DEVICE_PORT = 4370
DEVICE_TIMEOUT = 5

RAILS_API_URL = "https://spine-fitness.com/api/biometric_attendances"
COMP_CODE = "SF"

POLL_INTERVAL_SECONDS = 20

Enter fullscreen mode Exit fullscreen mode

Key decisions:

  • Port 4370 — Standard ZK biometric device communication port
  • 20-second polling — Balances real-time feel vs. not overwhelming the device
  • Company code "SF" — Supports multi-tenant architecture (future-proof for multiple gyms)

The Bridge Script

# biometric_bridge/bridge.py

from zk import ZK
import requests
import time
from datetime import datetime
from config import *

def send_to_rails(payload):
    try:
        response = requests.post(
            RAILS_API_URL,
            json=payload,
            timeout=5
        )
        print(f"Sent: {payload} | Response: {response.status_code}")
    except Exception as e:
        print("Rails API error:", e)

def main():
    zk = ZK(
        DEVICE_IP,
        port=DEVICE_PORT,
        timeout=DEVICE_TIMEOUT,
        password=0,
        force_udp=False,
        ommit_ping=False
    )

    print("Connecting to biometric device...")

    try:
        conn = zk.connect()
        conn.disable_device()

        print("Connected to device")
        print("Fetching attendance logs...")

        last_sent = set()

        while True:
            attendances = conn.get_attendance()

            for att in attendances:
                key = f"{att.user_id}-{att.timestamp}"

                # Prevent duplicate sending
                if key in last_sent:
                    continue

                payload = {
                    "compcode": COMP_CODE,
                    "user_id": att.user_id,
                    "timestamp": att.timestamp.strftime("%Y-%m-%d %H:%M:%S"),
                    "device_sn": conn.serial_number
                }

                send_to_rails(payload)
                last_sent.add(key)

            time.sleep(POLL_INTERVAL_SECONDS)

    except Exception as e:
        print("Device connection error:", e)

    finally:
        try:
            conn.enable_device()
            conn.disconnect()
        except:
            pass

if __name__ == "__main__":
    main()

Enter fullscreen mode Exit fullscreen mode

How It Works Step by Step

1. Connect to the device

zk = ZK(DEVICE_IP, port=DEVICE_PORT, timeout=DEVICE_TIMEOUT, ...)
conn = zk.connect()
conn.disable_device()  # Prevents new operations while reading

Enter fullscreen mode Exit fullscreen mode

The pyzk library connects to the ZK device via TCP on port 4370. We temporarily disable the device during reads to prevent data corruption.

2. Poll every 20 seconds

while True:
    attendances = conn.get_attendance()
    # ... process ...
    time.sleep(POLL_INTERVAL_SECONDS)

Enter fullscreen mode Exit fullscreen mode

The script runs in an infinite loop, fetching all attendance records from the device. The device stores punches internally, so we get the full history each time.

3. Deduplicate locally

last_sent = set()

key = f"{att.user_id}-{att.timestamp}"
if key in last_sent:
    continue

Enter fullscreen mode Exit fullscreen mode

Since get_attendance() returns all historical records, we use an in-memory set to track what's already been sent. Only new punches get forwarded. This is deduplication layer 1 — the Rails API has its own deduplication as layer 2.

4. Forward to Rails API

payload = {
    "compcode": COMP_CODE,
    "user_id": att.user_id,
    "timestamp": att.timestamp.strftime("%Y-%m-%d %H:%M:%S"),
    "device_sn": conn.serial_number
}
send_to_rails(payload)

Enter fullscreen mode Exit fullscreen mode

Each punch becomes a clean JSON payload with all the context Rails needs.

Auto-Start on Windows

The gym staff shouldn't need to "start the bridge" manually. A .bat file handles this:

:: biometric_bridge/start_biometric.bat
cd C:\biometric_bridge
python bridge.py

Enter fullscreen mode Exit fullscreen mode

This can be placed in the Windows Startup folder so the bridge starts automatically when the gym opens and the laptop powers on.

Dependencies

# biometric_bridge/requirements.txt
pyzk
requests

Enter fullscreen mode Exit fullscreen mode

Just two dependencies — pyzk for ZK device communication and requests for HTTP calls. Minimal and reliable.


💎 Part 2: The Rails API (Cloud Server Side)

The Route

# config/routes.rb
Rails.application.routes.draw do
  namespace :api do
    resources :biometric_attendances, only: [:create]
  end
end

Enter fullscreen mode Exit fullscreen mode

This gives us: POST /api/biometric_attendances

The Controller

When the Python bridge sends a punch, the Rails API processes it through a 4-step pipeline:

# app/controllers/api/biometric_attendances_controller.rb

class Api::BiometricAttendancesController < ApplicationController
  skip_before_action :verify_authenticity_token

  def create
    compcode       = params[:compcode].to_s
    device_user_id = params[:user_id].to_i
    device_sn      = params[:device_sn].to_s
    punch_time     = Time.zone.parse(params[:timestamp]) rescue Time.current

    # ── STEP 1: Find biometric mapping ──
    mapping = TrnMemberBiometricMapping.active.find_by(
      mbm_compcode:       compcode,
      mbm_device_user_id: device_user_id,
      mbm_device_sn:      device_sn
    )

    unless mapping
      render json: {
        status: false,
        message: "Biometric user not mapped"
      }, status: 404
      return
    end

    member = mapping.member

    # ── STEP 2: Ignore duplicate punches (same member, same minute) ──
    if duplicate_punch?(member.id, punch_time)
      render json: { status: true, message: "Duplicate ignored" }
      return
    end

    # ── STEP 3: Validate subscription ──
    subscription = latest_subscription(member.id, compcode)

    if subscription && subscription.ms_end_date >= Date.today
      att_status = "ALLOWED"
      reason     = nil
    else
      att_status = "DENIED"
      reason     = "Subscription expired"
    end

    # ── STEP 4: Store attendance ──
    TrnMemberAttendance.create!(
      att_compcode:       compcode,
      att_member_id:      member.id,
      att_device_user_id: device_user_id,
      att_device_sn:      device_sn,
      att_punch_time:     punch_time,
      att_punch_date:     punch_time.to_date,
      att_status:         att_status,
      att_reason:         reason
    )

    render json: { status: true, access: att_status }
  end

  private

  def duplicate_punch?(member_id, time)
    TrnMemberAttendance.where(
      att_member_id: member_id,
      att_punch_time: time.beginning_of_minute..time.end_of_minute
    ).exists?
  end

  def latest_subscription(member_id, compcode)
    TrnMemberSubscription
      .where(ms_compcode: compcode, ms_member_id: member_id)
      .order(ms_end_date: :desc)
      .first
  end
end

Enter fullscreen mode Exit fullscreen mode


🛡️ Two Layers of Deduplication

This is important — deduplication happens at both levels:

Layer Where How Why
Layer 1 Python bridge In-memory set of {user_id}-{timestamp} keys Prevents resending the same device record on every poll cycle
Layer 2 Rails API Database query for same member + same minute Catches duplicates if the bridge restarts (set resets), or if the device sends duplicate records
Member scans finger
       │
       ▼
Python bridge: "Already in last_sent?" ──YES──▶ Skip
       │ NO
       ▼
Rails API: "Punch in same minute?" ──YES──▶ Return "Duplicate ignored"
       │ NO
       ▼
Store attendance ✅

Enter fullscreen mode Exit fullscreen mode

This double-layer approach means the system is resilient to:

  • Bridge restarts (set clears → Layer 2 catches it)
  • Device quirks (some ZK devices record multiple entries per scan)
  • Network retries (if the bridge retries a failed request)

🗄️ Database Design

The Bridge Table: trn_member_biometric_mappings

Column Type Purpose
mbm_compcode string Company code (multi-tenant)
mbm_device_user_id integer User ID on the biometric device
mbm_device_sn string Device serial number
mbm_member_id integer FK → mst_members_lists.id
mbm_status string ACTIVE / INACTIVE

Why is this needed? The biometric device assigns its own user IDs (1, 2, 3...). These don't match your database. This table says "Device user #42 on device SN-ABC = Member Rahul Sharma (ID: 156)".

The Attendance Table: trn_member_attendances

Column Type Purpose
att_member_id integer FK → member
att_device_user_id integer Device user ID
att_device_sn string Device serial
att_punch_time datetime Exact punch time
att_punch_date date For easy date-based queries
att_status string ALLOWED or DENIED
att_reason string Why denied (if applicable)

Key design decision: Even DENIED attempts are stored. This lets the gym owner see which expired members are still trying to come — useful for renewal follow-ups.


🧪 Testing the Full Pipeline

Test with cURL (bypassing the Python bridge)

# Active member
curl -X POST https://spine-fitness.com/api/biometric_attendances \
  -H "Content-Type: application/json" \
  -d '{
    "compcode": "SF",
    "user_id": 42,
    "device_sn": "CRT5200-SN001",
    "timestamp": "2026-03-12 07:30:00"
  }'
# → {"status":true,"access":"ALLOWED"}

# Expired member
# → {"status":true,"access":"DENIED"}

# Unknown biometric ID
# → {"status":false,"message":"Biometric user not mapped"}

Enter fullscreen mode Exit fullscreen mode

Test the Python bridge locally

cd biometric_bridge
pip install -r requirements.txt
python bridge.py
# → Connecting to biometric device...
# → Connected to device
# → Fetching attendance logs...
# → Sent: {...} | Response: 200

Enter fullscreen mode Exit fullscreen mode


🧩 Edge Cases I Solved

Edge Case Solution
Device returns ALL historical records every poll Python-side last_sent set filters to only new records
Member scans finger 3 times rapidly Rails-side 1-minute deduplication window
Bridge script crashes / laptop restarts .bat file in Startup folder auto-restarts; Rails Layer 2 catches re-sent duplicates
Gym has multiple devices device_sn is part of the mapping — same user_id on different devices = different members
Timestamp timezone mismatch Time.zone.parse with rescue Time.current fallback
Member renews subscription mid-day ms_end_date >= Date.today check means renewal takes effect immediately
Member leaves permanently Set mbm_status to INACTIVE.active scope blocks without deleting data
Network/API timeout Python requests.post(timeout=5) with try/except — failed sends are logged, not fatal

📊 How This Powers the Dashboard

All attendance data flows to the admin dashboard in real-time:

  • 🟢 Active members — subscription valid, attendance tracked
  • 🟡 Expiring soon — auto-triggers WhatsApp reminders
  • 🔴 Expired — DENIED attendance logged, visible to gym owner

The gym owner sees a member scan their finger, and within seconds the dashboard reflects it — all without touching a single register.


💡 Key Takeaways

  1. Use a bridge pattern when hardware can't talk to cloud directly. A simple Python script solved the hardware↔cloud gap.

  2. Deduplicate at every layer. Don't trust any single layer to handle it perfectly.

  3. Store denied attempts. They're not failures — they're business intelligence.

  4. Keep the bridge minimal. Two dependencies (pyzk + requests), one config file, one script. Less can go wrong.

  5. Auto-start everything. The gym staff shouldn't need to know Python exists. A .bat file in Startup and it just works.

  6. Multi-language is fine. Python is better at hardware communication (pyzk), Rails is better at web apps. Use the right tool for each layer.


🏁 Conclusion

This feature taught me that production software often lives at the intersection of hardware and software. The biometric device, the Python bridge, the Rails API, and the MySQL database — four different technologies working together to create a seamless experience: member scans finger → attendance appears on dashboard.

The most satisfying moment? Watching the gym owner check the dashboard and see real-time attendance without touching a single notebook.


🔗 Live App: spine-fitness.com
💻 Full Source Code: GitHub
📂 Python Bridge Code: biometric_bridge/

Found this useful? Drop a ❤️! Got questions about biometric integration or the Python bridge? Let's chat in the comments!