{"id":50489103,"url":"https://github.com/ztamdev/dars-framework","last_synced_at":"2026-06-02T01:00:53.673Z","repository":{"id":356963525,"uuid":"1031529146","full_name":"ZtaMDev/Dars-Framework","owner":"ZtaMDev","description":"Dars is a Full-Stack multiplatform Python UI framework for building modern, interactive web and desktop apps with Python code. Seamlessly integrated with FastAPI, it allows you to build complete applications with Server-Side Rendering and reactive SPA capabilities also classic multipage html and desktop apps in a single codebase.","archived":false,"fork":false,"pushed_at":"2026-05-25T00:54:34.000Z","size":33140,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"CrystalMain","last_synced_at":"2026-05-25T02:34:40.033Z","etag":null,"topics":["backend","desktop","desktop-app","electron","framework","frontend","gui","interface","python","ui","webapp","website"],"latest_commit_sha":null,"homepage":"https://ztamdev.github.io/Dars-Framework/","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mpl-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ZtaMDev.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":"docs/roadmap.html","authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-08-03T23:46:05.000Z","updated_at":"2026-05-25T00:54:37.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/ZtaMDev/Dars-Framework","commit_stats":null,"previous_names":["ztamdev/dars-framework"],"tags_count":104,"template":false,"template_full_name":null,"purl":"pkg:github/ZtaMDev/Dars-Framework","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ZtaMDev%2FDars-Framework","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ZtaMDev%2FDars-Framework/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ZtaMDev%2FDars-Framework/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ZtaMDev%2FDars-Framework/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ZtaMDev","download_url":"https://codeload.github.com/ZtaMDev/Dars-Framework/tar.gz/refs/heads/CrystalMain","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ZtaMDev%2FDars-Framework/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":33800676,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-06-01T02:00:06.963Z","response_time":115,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["backend","desktop","desktop-app","electron","framework","frontend","gui","interface","python","ui","webapp","website"],"created_at":"2026-06-02T01:00:37.302Z","updated_at":"2026-06-02T01:00:53.661Z","avatar_url":"https://github.com/ZtaMDev.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"\u003ch1 align=\"center\"\u003eDars Framework\u003c/h1\u003e\n \n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"https://raw.githubusercontent.com/ZtaMDev/Dars-Framework/CrystalMain/Dars-logo.png\" alt=\"Dars Framework Logo\" width=\"200\" /\u003e\n\u003c/p\u003e\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"https://img.shields.io/pypi/v/dars-framework?color=brightgreen\" alt=\"PyPI Version\" /\u003e\n  \u003cimg src=\"https://img.shields.io/pypi/pyversions/dars-framework?color=blue\" alt=\"Python Versions\" /\u003e\n  \u003ca href=\"https://deepwiki.com/ZtaMDev/Dars-Framework\"\u003e\u003cimg src=\"https://deepwiki.com/badge.svg\" alt=\"Ask DeepWiki\"\u003e\u003c/a\u003e\n\u003c/p\u003e\n\n\u003cp align=\"center\"\u003e\n  \u003cem\u003eDars is a Full-Stack Python UI framework for building modern, interactive web applications entirely in Python. Seamlessly integrated with FastAPI, it lets you build complete applications with Server-Side Rendering (SSR), reactive SPA routing, static site generation, and a production-ready backend API — all from a single Python codebase, with zero JavaScript required.\u003c/em\u003e\n\u003c/p\u003e\n\n\u003cdiv align=\"center\"\u003e\n\nOfficial [Website](https://ztamdev.github.io/Dars-Framework/) |\nDocumentation [Docs](https://ztamdev.github.io/Dars-Framework/docs.html) |\nOfficial [Roadmap](https://ztamdev.github.io/Dars-Framework/roadmap.html) |\nExtension for VSCode [here](https://marketplace.visualstudio.com/items?itemName=ZtaMDev.dars-framework) and OpenVSX version [here](https://open-vsx.org/extension/ztamdev/dars-framework)\n\n\u003c/div\u003e\n\n```bash\npip install dars-framework\n```\n\nTry Dars without installing anything — visit the [Dars Playground](https://dars-playground.vercel.app/)\n\n---\n\n## How It Works\n\n- Build your UI using Python classes and components (`Text`, `Button`, `Container`, `Page`, `Each`, `Show`, `If`, etc.).\n- Preview instantly with hot-reload using `app.rTimeCompile()`.\n- Export your app to static/dynamic/SSR web files with a single CLI command.\n- Use multipage layouts, scripts, hooks, and more — see docs for advanced features.\n- **One app, four deployment targets simultaneously:** Dars supports Static Site Generation (SSG), Single-Page Application (SPA) routing, Server-Side Rendering (SSR) with FastAPI, and a full Backend API — all from the same Python codebase. Mix and match freely: export some pages as static HTML for SEO, serve others via SSR for dynamic content, and expose REST API endpoints alongside your UI.\n- **Production-grade Authentication:** Build secure apps with built-in Multi-Auth, HttpOnly JWT cookies, CSRF protection, and role-based access control — all without writing Javascript.\n- **Full backend toolkit included:** `useFetch` for declarative data fetching, `FormValidator` for client-side validation, `Each` for runtime list rendering from API responses, `JsonStore` for file-backed persistence, `UploadPipeline` for secure file uploads, `SecurityHeadersMiddleware` for HTTP security, and `DarsEnv` for `.env` file support.\n- **Database \u0026 Models:** Built-in SQLite ORM with `DarsModel`, auto-generated CRUD API, and migration tracking.\n- **Server Actions:** Call Python backend functions directly from client-side events with automatic validation and auth.\n- **Middleware System:** Production-grade middleware pipeline — Auth, CORS, Rate limiting, Logging, Compression, Security headers.\n- For more information visit the [Documentation](https://ztamdev.github.io/Dars-Framework/docs.html)\n\n---\n\n## Quick Example: Your First App\n\n```python\nfrom dars.all import *\n\napp = App(title=\"Hello World\", theme=\"dark\")\n\n# 1. Define State\nstate = State(\"app\", title_val=\"Simple Counter\", count=0)\n\n# 2. Define Route\n@route(\"/\")\ndef index():\n    return Page(\n        Text(\n            text=useValue(\"app.title_val\"),\n            style=\"fs-[33px] text-black font-bold mb-[5px]\",\n        ),\n        Text(\n            text=useDynamic(\"app.count\"),\n            style=\"fs-[48px] mt-5 mb-[12px]\"\n        ),\n        Button(\n            text=\"+1\",\n            on_click=state.count.increment(1),\n            style=\"bg-[#3498db] text-white p-[15px] px-[30px] rounded-[8px] cursor-pointer fs-[18px]\",\n        ),\n        Button(\n            text=\"-1\",\n            on_click=state.count.decrement(1),\n            style=\"bg-[#3498db] text-white p-[15px] px-[30px] rounded-[8px] cursor-pointer fs-[18px] mt-[5px]\",\n        ),\n        Button(\n            text=\"Reset\",\n            on_click=state.reset(),\n            style=\"bg-[#3498db] text-white p-[15px] px-[30px] rounded-[8px] cursor-pointer fs-[18px] mt-[5px]\",\n        ),\n        style=\"flex flex-col items-center justify-center h-[100vh] ffam-[Arial] bg-[#f0f2f5]\",\n    )\n\napp.add_page(\"index\", index(), title=\"index\")\n\nif __name__ == \"__main__\":\n    app.rTimeCompile()\n```\n\n---\n\n## State Management System\n\nDars features a **powerful state management system** designed for different use cases.\n\n### Hook-Based State Management\n\nModern, Pythonic state management for reactive updates. Best for counters, timers, and component interactions.\n\n**Hooks System:**\n\n- `useDynamic()`: Reactive state binding for automatic UI updates.\n- `useValue()`: Set initial values from state (non-reactive).\n- `useWatch()`: Monitor state changes and trigger side effects.\n\n[Learn more about Hooks](https://ztamdev.github.io/Dars-Framework/docs.html#hooks-system)\n\n```python\nfrom dars.all import *\n\napp = App(\"State Demo\")\nstate = State(\"counter\", count=0)\n\n@route(\"/\")\ndef index():\n    return Page(\n        Text(text=useDynamic(\"counter.count\"), style=\"fs-[24px]\"),\n        Button(\"Increment\", on_click=state.count.increment(1)),\n        Button(\"Decrement\", on_click=state.count.decrement(1)),\n        Button(\"Reset\",     on_click=state.count.set(0)),\n    )\n\napp.add_page(\"index\", index())\n\nif __name__ == \"__main__\":\n    app.rTimeCompile()\n```\n\n\u003e [!WARNING]\n\u003e **Important:** When using hooks, the State ID is used for binding. **Do not use an ID that belongs to another unrelated component**, as hooks use this ID as the State ID. Using a conflicting ID may cause unexpected behavior or state collisions.\n\nFor detailed documentation, visit the [State Management Guide](https://ztamdev.github.io/Dars-Framework/docs.html#state-management-in-dars).\n\n---\n\n## Animation System\n\nDars includes **15+ built-in animations** that work seamlessly with state management:\n\n```python\nfrom dars.all import fadeIn, fadeOut, pulse, shake, sequence\n\n# Single animation\nbutton.on_click = fadeIn(id=\"modal\", duration=500)\n\n# Chain multiple animations\nbutton.on_click = sequence(\n    fadeIn(id=\"box\"),\n    pulse(id=\"box\", scale=1.2, iterations=2),\n    shake(id=\"box\", intensity=5)\n)\n```\n\n**Available Animations:** `fadeIn`, `fadeOut`, `slideIn`, `slideOut`, `scaleIn`, `scaleOut`, `pulse`, `shake`, `bounce`, `rotate`, `flip`, `colorChange`, `morphSize`, `popIn`, `popOut`\n\nFor complete animation documentation, visit the [Animation Guide](https://ztamdev.github.io/Dars-Framework/docs.html#dars-animation-system).\n\n---\n\n## Routing System (SPA \u0026 SSR)\n\nDars offers a flexible routing system supporting Client-Side Routing (SPA), Server-Side Rendering (SSR), and Static Site Generation — all in one app.\n\n### Server-Side Rendering (SSR)\n\n```python\nfrom dars.all import *\n\n@route(\"/dashboard\", route_type=RouteType.SSR)\ndef dashboard():\n    return Page(\n        Text(\"Server-Side Rendered Page\"),\n        Button(\"Click Me\", on_click=alert(\"Hello from Client\")),\n    )\n```\n\n### Client-Side Routing (SPA)\n\n```python\n@route(\"/\")\ndef home():\n    return Page(Text(\"Home Page\"))\n\n@route(\"/about\")\ndef about():\n    return Page(Text(\"About Us\"))\n```\n\n### Nested Routes with Outlet\n\n```python\n@route(\"/dashboard\")\ndef dashboard():\n    return Page(\n        Text(\"Dashboard\", style=\"fs-[24px]\"),\n        Container(\n            Link(\"Settings\", href=\"/dashboard/settings\"),\n            Link(\"Profile\",  href=\"/dashboard/profile\"),\n        ),\n        Outlet(),\n    )\n\napp.add_page(\"dashboard\", dashboard(), index=True)\napp.add_page(\"settings\", settings_page, route=\"/dashboard/settings\", parent=\"dashboard\")\napp.add_page(\"profile\",  profile_page,  route=\"/dashboard/profile\",  parent=\"dashboard\")\n```\n\n### 404 Error Handling\n\n```python\napp.set_404_page(Page(\n    Text(\"Page not found\", style=\"fs-[32px] text-red-500\"),\n    Link(\"Go Home\", href=\"/\"),\n))\n```\n\n---\n\n## Authentication \u0026 Security\n\nDars provides a production-grade, secure-by-default authentication system. Tokens never touch the browser's JavaScript context — they live exclusively in HttpOnly cookies managed by the browser itself.\n\n- **HttpOnly Cookie-Based Sessions** with automatic CSRF protection\n- **`@requires_auth` Decorator** — Protect any route, auto-injects `request.state.user`\n- **`@requires_role(\"admin\")`** — Role-based access control\n- **Multi-Auth Support** — Multiple isolated auth schemes in the same app\n- **Pure Python JWT** — Zero third-party dependencies\n- **Auto-generated Auth Endpoints** — `/_dars/auth/{id}/login`, `/me`, `/logout`, `/refresh`\n- **Refresh Token Rotation** with server-side revocation\n- **PBKDF2 Password Hashing** — 100k iterations, timing-attack resistant\n\n### Quick Example\n\n```python\nfrom dars.all import *\n\ndef verify_user(username, password):\n    if username == \"admin\" and password == \"secret\":\n        return {\"id\": \"1\", \"username\": \"admin\", \"role\": \"admin\"}\n    return None\n\n@route(\"/dashboard\", route_type=RouteType.SSR)\n@requires_auth(verify_credentials_callback=verify_user, secret=\"super_secret\")\nasync def dashboard(request: Request):\n    user = request.state.user  # injected by @requires_auth\n    return Page(\n        Text(f\"Welcome, {user['username']}!\"),\n    )\n```\n\nFor a complete working example, check out the [`/examples/FullStack-app`](https://github.com/ZtaMDev/Dars-Framework/tree/CrystalMain/examples/FullStack-app) in the repository.\n\nFor complete documentation, visit the [Authentication Guide](https://ztamdev.github.io/Dars-Framework/docs.html#authentication-and-security).\n\n---\n\n## Server Actions\n\nCall Python backend functions directly from client-side events with zero boilerplate:\n\n```python\nfrom dars.backend.actions import server_action, call_server\n\n@server_action(csrf_protected=False)\ndef greet(name: str, count: int = 1) -\u003e list:\n    return [f\"Hello {name}! x{i}\" for i in range(count)]\n\n# In your page:\nButton(\"Greet\", on_click=call_server(\"greet\", name=\"World\", count=3))\n```\n\nFeatures:\n- **Type validation** via Pydantic models built from annotations\n- **Sync \u0026 async** support\n- **Auth-protected actions** with `@server_action(auth_required=True, roles=[\"admin\"])`\n- **CSRF protection** for mutating actions\n- **Success/error callbacks** — `call_server(\"action\", on_success=..., on_error=...)`\n\n---\n\n## Database \u0026 Models (SQLite ORM)\n\nDars ships with a built-in declarative ORM for SQLite with auto-generated CRUD API:\n\n```python\nfrom dars.backend.models import DarsModel, TextField, IntegerField\nfrom dars.backend.database import Database\n\nclass Product(DarsModel):\n    __tablename__ = \"products\"\n    name = TextField(nullable=False)\n    price = IntegerField(default=0)\n\ndb = Database(\"app.db\")\ndb.register(Product)\ndb.create_all()\n\n# CRUD\nproduct = Product(name=\"Widget\", price=99)\nproduct.save()\nall_products = Product.objects.all()\nProduct.objects.filter(price=0)\n\n# Auto-generate REST API\nfrom dars.backend.models import register_model_api\nregister_model_api(app, db, prefix=\"/api/models\")\n```\n\n---\n\n## Route Types \u0026 Guards\n\nDars supports four route types with client-side security guards:\n\n```python\nfrom dars.core.route_types import RouteType\n\n@route(\"/\")                                    # PUBLIC (default)\n@route(\"/dashboard\", route_type=RouteType.SSR) # Server-side rendered\n@route(\"/account\", route_type=RouteType.PRIVATE) # Auth required\n@route(\"/admin\", route_type=RouteType.PROTECTED, roles=[\"admin\"]) # Auth + role\n```\n\n---\n\n## Middleware System\n\nProduction-grade middleware pipeline for FastAPI backends:\n\n```python\nfrom dars.backend.middleware import (\n    AuthMiddleware, SecurityHeadersMiddleware,\n    CORSMiddleware, RateLimitMiddleware,\n    LoggingMiddleware, CompressionMiddleware,\n)\n\napp.add_middleware(AuthMiddleware, secret=\"your-secret\", exclude_paths=[\"/_dars/auth\"])\napp.add_middleware(SecurityHeadersMiddleware, csp=\"default-src 'self'\", hsts=True)\napp.add_middleware(RateLimitMiddleware, calls_per_minute=60)\n```\n\n---\n\n## Custom Components\n\n### Function Components\n\n```python\nfrom dars.all import *\n\n@FunctionComponent\ndef UserCard(name, email, **props):\n    return f\"\"\"\n    \u003cdiv {Props.id} {Props.class_name} {Props.style}\u003e\n        \u003ch3\u003e{name}\u003c/h3\u003e\n        \u003cp\u003e{email}\u003c/p\u003e\n        \u003cdiv class=\"card-body\"\u003e{Props.children}\u003c/div\u003e\n    \u003c/div\u003e\n    \"\"\"\n\ncard = UserCard(\"John Doe\", \"john@example.com\", id=\"user-1\", style=\"p-[20px]\")\n```\n\n---\n\n## Control Flow Components\n\n### `Show` — Runtime Visibility Toggle\n\nAlways renders children into the DOM. A falsy VRef condition hides the wrapper with `display:none`. Reacts to VRef changes at runtime — perfect for loading spinners, error banners, and any UI that toggles based on live state.\n\n```python\nfrom dars.all import *\n\nis_loading = setVRef(True,  \".loading\")\nhas_error  = setVRef(False, \".error\")\n\nShow(\n    is_loading,\n    Container(Spinner(), Text(\"Loading…\"), style=\"flex items-center gap-2\"),\n)\n\nShow(\n    has_error,\n    Container(\n        Text(\"Something went wrong.\", style=\"text-red-600\"),\n        style=\"bg-red-50 border rounded p-3\",\n    ),\n)\n```\n\n### `Each` — List Rendering from Python or API\n\nRenders a list using a template function. Works with both compile-time Python lists and runtime VRef arrays (e.g. from `useFetch`).\n\n**Compile-time list:**\n\n```python\nusers = [{\"name\": \"Alice\"}, {\"name\": \"Bob\"}]\n\nEach(items=users, render=lambda u: Text(u[\"name\"]))\n```\n\n**Runtime VRef list (from API):**\n\nThe render function is called at export time with a sentinel dict containing `__item_\u003cfield\u003e__` placeholders. At runtime, `dom_each_render` substitutes real values for each item. Use `__item_done_class__` to get `\"line-through text-gray-400\"` for done items automatically.\n\n```python\ntasks_vref = setVRef([], \".tasks-data\")  # filled by useFetch\n\ndef task_item(t):\n    title   = t.get(\"title\", \"__item_title__\") if isinstance(t, dict) else \"__item_title__\"\n    item_id = t.get(\"id\",    \"__item_id__\")    if isinstance(t, dict) else \"__item_id__\"\n    return Container(\n        Text(title,         style=\"flex: 1 1 0%\", class_name=\"__item_done_class__\"),\n        Text(f\"#{item_id}\", style=\"text-xs text-gray-400 ml-2\"),\n        style=\"flex items-center gap-2 p-2 border rounded bg-white shadow-sm\",\n    )\n\nEach(items=tasks_vref, render=task_item, class_name=\"space-y-1 mb-6\")\n```\n\nSupported API response shapes are automatically unwrapped: `{\"tasks\":[...]}`, `{\"items\":[...]}`, `{\"data\":[...]}`, `{\"results\":[...]}`, or a plain `[...]` array.\n\n---\n\n## Backend \u0026 API Communication\n\nDars ships a complete production-grade backend toolkit. Everything is pure Python — no JavaScript required.\n\n### `useFetch` — Declarative Data Fetching\n\nFetch data from any API and bind the response to reactive VRefs automatically:\n\n```python\nfrom dars.all import *\n\ntasks_sel = \".tasks-data\"\n_tasks    = setVRef([], tasks_sel)\n\ntrigger, loading, data, error = useFetch(\n    \"/api/tasks\",\n    on_success=runSequence(\n        updateVRef(\".loading\", False),\n        updateVRefFromResponse(tasks_sel),  # stores API response → VRef\n    ),\n    on_error=runSequence(\n        updateVRef(\".loading\", False),\n        updateVRef(\".error\", True),\n    ),\n)\n\npage = Page(\n    Show(loading, Spinner()),\n    Show(error,   Text(\"Could not load tasks.\", style=\"text-red-500\")),\n    Each(items=_tasks, render=lambda t: Container(\n        Text(t.get(\"title\", \"__item_title__\"), style=\"flex-1\"),\n        Text(f\"#{t.get('id', '__item_id__')}\",  style=\"text-xs text-gray-400\"),\n        style=\"flex gap-2 p-2 border rounded bg-white\",\n    )),\n    Button(\"↻ Refresh\", on_click=trigger),\n)\npage.add_script(trigger)  # auto-run on page load\n```\n\n### `FormValidator` — Client-Side Validation\n\nValidate forms before submitting — rules declared once in Python, enforced both client-side and server-side:\n\n```python\nvalidator = FormValidator({\n    \"email\":    [required(), email()],\n    \"password\": [required(), min_length(8)],\n})\n\nsubmit = validator.validated_submit(\n    url=\"/api/login\",\n    form_data=collect_form(email=V(\"#email\"), password=V(\"#password\")),\n    on_success=goTo(\"/dashboard\"),\n    on_error=setText(\"error-msg\", \"Login failed.\"),\n)\n\npage = Page(\n    Input(id=\"email\",    placeholder=\"Email\"),\n    Text(\"\", id=\"email-error\",    style=\"text-red-500 text-sm\"),\n    Input(id=\"password\", placeholder=\"Password\"),\n    Text(\"\", id=\"password-error\", style=\"text-red-500 text-sm\"),\n    Text(\"\", id=\"error-msg\",      style=\"text-red-500 text-sm\"),\n    Button(\"Login\", on_click=submit),\n)\n```\n\n### `JsonStore` — File-Backed Persistence\n\nThread-safe, atomic-write JSON storage for rapid prototyping and small backends:\n\n```python\nfrom dars.backend.store import JsonStore\n\nstore = JsonStore(\"tasks.json\", default={\"tasks\": []})\n\ntasks = store.get(\"tasks\", [])\ntasks.append({\"id\": 1, \"title\": \"New task\", \"done\": False})\nstore.set(\"tasks\", tasks)\n```\n\n### `UploadPipeline` — Secure File Uploads\n\n```python\nfrom dars.backend.upload import UploadPipeline\n\npipeline = UploadPipeline(\n    upload_dir=\"uploads\",\n    allowed_types=[\"image/png\", \"image/jpeg\", \"application/pdf\"],\n    max_size_bytes=10 * 1024 * 1024,\n)\npipeline.create_endpoint(app, path=\"/api/upload\")\n```\n\nFrontend component:\n\n```python\nFileUpload(\n    upload_url=\"/api/upload\",\n    accepted_types=[\"image/png\", \"image/jpeg\"],\n    max_size_bytes=5 * 1024 * 1024,\n    on_upload_complete=setText(\"status\", \"Uploaded!\"),\n    on_upload_error=setText(\"status\", \"Upload failed.\"),\n)\n```\n\n### `SecurityHeadersMiddleware` — HTTP Security\n\n```python\nfrom dars.backend.ssr import SSRApp\n\nssr = SSRApp(dars_app, prefix=\"/api/ssr\")\nssr.use_cors(origins=[\"http://localhost:4000\"], credentials=True)\nssr.use_security_headers()  # X-Frame-Options, CSP, HSTS, etc.\nssr.use_upload(upload_dir=\"uploads\", allowed_types=[\"image/*\"])\n\napp = ssr.fastapi_app\n```\n\n### `DarsEnv` — Environment Variables\n\n```python\nfrom dars.env import DarsEnv\n\nDarsEnv.load()                          # loads .env silently if present\napi_key = DarsEnv.get(\"API_KEY\")        # None if missing\nsecret   = DarsEnv.require(\"SECRET\")   # raises KeyError if missing\n```\n\n### Full Backend API Example\n\n```python\nfrom dars.backend.ssr import SSRApp\nfrom dars.backend.store import JsonStore\nfrom main import app as dars_app\nfrom fastapi import Request\nfrom fastapi.responses import JSONResponse\nimport os\n\nssr = SSRApp(dars_app, prefix=\"/api/ssr\")\nssr.use_cors(origins=[\"http://localhost:4000\"], credentials=True)\nssr.use_security_headers()\n\napp = ssr.fastapi_app\n\n# ── Production: serve dist/ as static files with SPA fallback ───────────────\nfrom backend.apiConfig import DarsEnv\nif not DarsEnv.is_dev():\n    ssr.use_spa_fallback()\n# ────────────────────────────────────────────────────────────────────────────\n\n_store = JsonStore(\"tasks_db.json\", default={\"tasks\": []})\n\n@app.get(\"/api/tasks\")\nasync def get_tasks():\n    return JSONResponse({\"tasks\": _store.get(\"tasks\", [])})\n\n@app.post(\"/api/tasks\")\nasync def create_task(request: Request):\n    body  = await request.json()\n    tasks = _store.get(\"tasks\", [])\n    task  = {\"id\": len(tasks) + 1, \"title\": body.get(\"title\", \"\"), \"done\": False}\n    tasks.append(task)\n    _store.set(\"tasks\", tasks)\n    return JSONResponse(task, status_code=201)\n\n@app.put(\"/api/tasks/{task_id}\")\nasync def update_task(task_id: int, request: Request):\n    body  = await request.json()\n    tasks = _store.get(\"tasks\", [])\n    for t in tasks:\n        if t[\"id\"] == task_id:\n            t.update({k: v for k, v in body.items() if k != \"id\"})\n            _store.set(\"tasks\", tasks)\n            return JSONResponse(t)\n    return JSONResponse({\"error\": \"Not found\"}, status_code=404)\n\n@app.delete(\"/api/tasks/{task_id}\")\nasync def delete_task(task_id: int):\n    tasks = [t for t in _store.get(\"tasks\", []) if t[\"id\"] != task_id]\n    _store.set(\"tasks\", tasks)\n    return JSONResponse({\"deleted\": task_id})\n\nif __name__ == \"__main__\":\n    import uvicorn\n    print(\"\\n\" + \"=\" * 60)\n    print(\"Dars Fullstack Backend\")\n    print(\"=\" * 60)\n    if DarsEnv.is_dev():\n        port, host = 3000, \"127.0.0.1\"\n    else:\n        port, host = 8000, \"0.0.0.0\"\n    print(\"=\" * 60 + \"\\n\")\n    uvicorn.run(app, host=host, port=port)\n```\n\nFor complete backend documentation, see the [Backend \u0026 API Guide](https://ztamdev.github.io/Dars-Framework/docs.html#backend-http-utilities).\n\n---\n\n## CLI Usage\n\n| Command                               | What it does                                             |\n| ------------------------------------- | -------------------------------------------------------- |\n| `dars export my_app.py --format html` | Export app to HTML/CSS/JS in `./my_app_web`              |\n| `dars init --type fullstack`          | Scaffold full-stack project (SPA + SSR + API)            |\n| `dars preview`                        | Preview exported app (auto-detects output)               |\n| `dars preview --port 9000`            | Preview on a custom port                                 |\n| `dars init my_project`                | Create a new Dars project                                |\n| `dars init --update`                  | Create/Update dars.config.json in current dir            |\n| `dars build`                          | Build using dars.config.json                             |\n| `dars config validate`                | Validate dars.config.json and print report               |\n| `dars info my_app.py`                 | Show info about your app                                 |\n| `dars formats`                        | List supported export formats                            |\n| `dars dev`                            | Run the configured entry file with hot preview           |\n| `dars dev --port 9000`                | Run dev server on a custom port                          |\n| `dars dev --backend`                  | Deprecated: use `dars dev` with backendEntry configured. |\n| `dars generate component \u003cname\u003e`      | Scaffold a new FunctionComponent                         |\n| `dars generate page \u003cname\u003e`           | Scaffold a new page (static, SPA, or SSR)                |\n| `dars --help`                         | Show help and all CLI options                            |\n\nTip: use `dars doctor` to review optional tooling that can enhance bundling/minification.\n\n### Running with Backend\n\n```bash\n# Run both frontend and backend together in development\n# (backendEntry must be configured in dars.config.json)\ndars dev\n```\n\n\u003e Note: `dars dev --backend` is deprecated in v1.9.14. `dars dev` now starts the fullstack development server automatically when `backendEntry` is configured.\n\n---\n\n## Local Execution and Live Preview\n\n```python\nif __name__ == \"__main__\":\n    app.rTimeCompile()\n```\n\n```bash\npython my_app.py\n# → http://localhost:8000\n\npython my_app.py --port 8088\n```\n\n```bash\n# Auto-detects output directory and port from config\ndars preview\n\n# Or specify a custom path and port\ndars preview ./my_exported_app -p 8080\n```\n\n---\n\n## Project Configuration (`dars.config.json`)\n\n```json\n{\n  \"entry\": \"main.py\",\n  \"format\": \"html\",\n  \"outdir\": \"dist\",\n  \"publicDir\": null,\n  \"include\": [],\n  \"exclude\": [\"**/__pycache__\", \".git\", \".venv\", \"node_modules\"],\n  \"bundle\": true,\n  \"minify\": true,\n  \"utility_styles\": {},\n  \"markdownHighlight\": true,\n  \"markdownHighlightTheme\": \"auto\",\n  \"port\": 8000,\n  \"backendEntry\": \"backend.api:app\"\n}\n```\n\n| Key                 | Description                                                                                           |\n| ------------------- | ----------------------------------------------------------------------------------------------------- |\n| `entry`             | Python entry file for `dars build` and `dars export config`                                           |\n| `format`            | Export format: `html`                                                                                 |\n| `outdir`            | Output directory                                                                                      |\n| `publicDir`         | Folder copied into output (auto-detected if null)                                                     |\n| `bundle`            | Reserved for future use                                                                               |\n| `minify`            | Enable/disable JS \u0026 CSS minification via **dars-bundler** (default `true`). No Node.js/Vite required. |\n| `utility_styles`    | Custom utility class definitions                                                                      |\n| `markdownHighlight` | Auto-inject Prism.js for Markdown code blocks (default `true`)                                        |\n| `backendEntry`      | Python import path for SSR/backend app (e.g. `\"backend.api:app\"`)                                     |\n| `port`              | Dev preview server port (default `8000`)                                                              |\n\n```bash\ndars config validate\ndars build\n```\n\n---\n\n## Documentation\n\n- [Getting Started](https://ztamdev.github.io/Dars-Framework/docs.html#getting-started-with-dars)\n- [Components](https://ztamdev.github.io/Dars-Framework/docs.html#dars-components-documentation)\n- [Hooks \u0026 Utilities](https://ztamdev.github.io/Dars-Framework/docs.html#hooks-system)\n- [Backend \u0026 API](https://ztamdev.github.io/Dars-Framework/docs.html#backend-http-utilities)\n- [State Management](https://ztamdev.github.io/Dars-Framework/docs.html#state-management-in-dars)\n- [Styling](https://ztamdev.github.io/Dars-Framework/docs.html#styling-system-in-dars)\n- [Routing \u0026 Route Types](https://ztamdev.github.io/Dars-Framework/docs.html#spa-routing-in-dars-framework)\n- [SSR \u0026 Deployment](https://ztamdev.github.io/Dars-Framework/docs.html#server-side-rendering-in-dars-framework)\n- [Authentication \u0026 Security](https://ztamdev.github.io/Dars-Framework/docs.html#authentication-and-security)\n- [Database \u0026 Models](https://ztamdev.github.io/Dars-Framework/docs.html#database-and-models)\n- [Server Actions](https://ztamdev.github.io/Dars-Framework/docs.html#server-actions)\n- [Middleware System](https://ztamdev.github.io/Dars-Framework/docs.html#middleware-system)\n- [Animations](https://ztamdev.github.io/Dars-Framework/docs.html#dars-animation-system)\n- [Release Notes](LandingPage/releases/versions.md)\n\n---\n\n- Visit the Dars [official website](https://ztamdev.github.io/Dars-Framework/)\n- Visit the Dars official [Documentation](https://ztamdev.github.io/Dars-Framework/docs.html)\n- Try Dars without installing anything — visit the [Dars Playground](https://dars-playground.vercel.app/)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fztamdev%2Fdars-framework","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fztamdev%2Fdars-framework","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fztamdev%2Fdars-framework/lists"}