```
├── .devcontainer/
├── devcontainer.json (100 tokens)
├── .github/
├── CODEOWNERS
├── ISSUE_TEMPLATE/
├── bug_report.md (100 tokens)
├── build_issue.md (100 tokens)
├── cloud_issue.md (100 tokens)
├── custom_component_request.md (100 tokens)
├── enhancement_request.md (100 tokens)
├── enterprise_issue.md (100 tokens)
├── feature_request.md (100 tokens)
├── actions/
├── setup_build_env/
├── action.yml (300 tokens)
├── codeql-config.yml
├── pull_request_template.md (300 tokens)
├── workflows/
├── check_node_latest.yml (200 tokens)
├── check_outdated_dependencies.yml (600 tokens)
├── codeql.yml (1000 tokens)
├── dependency-review.yml (100 tokens)
├── integration_app_harness.yml (300 tokens)
├── integration_tests.yml (1500 tokens)
├── performance.yml (200 tokens)
├── pre-commit.yml (200 tokens)
├── reflex_init_in_docker_test.yml (200 tokens)
├── unit_tests.yml (600 tokens)
├── .gitignore (100 tokens)
├── .python-version
├── CODE_OF_CONDUCT.md (1100 tokens)
├── CONTRIBUTING.md (700 tokens)
├── LICENSE (omitted)
├── MCP_README.md (100 tokens)
├── README.md (2.2k tokens)
├── SECURITY.md (100 tokens)
├── docker-example/
├── README.md (200 tokens)
├── production-app-platform/
├── .dockerignore
├── Dockerfile (500 tokens)
├── README.md (800 tokens)
├── production-compose/
├── .dockerignore
├── Caddy.Dockerfile
├── Caddyfile
├── Dockerfile (300 tokens)
├── README.md (500 tokens)
├── compose.prod.yaml (100 tokens)
├── compose.tools.yaml (100 tokens)
├── compose.yaml (200 tokens)
├── production-one-port/
├── .dockerignore
├── Caddyfile
├── Dockerfile (400 tokens)
├── README.md (200 tokens)
├── simple-one-port/
├── .dockerignore
├── Caddyfile
├── Dockerfile (300 tokens)
├── README.md (200 tokens)
├── simple-two-port/
├── .dockerignore
├── Dockerfile (200 tokens)
├── README.md (200 tokens)
├── docs/
├── DEBUGGING.md (100 tokens)
├── de/
├── README.md (2.1k tokens)
├── es/
├── README.md (2.1k tokens)
├── images/
├── dalle.gif
├── dalle_colored_code_example.png
├── reflex.png
├── reflex.svg (100 tokens)
├── reflex_dark.svg (200 tokens)
├── reflex_light.svg (200 tokens)
├── in/
├── README.md (2.1k tokens)
├── it/
├── README.md (2k tokens)
├── ja/
├── README.md (1600 tokens)
├── kr/
├── README.md (1600 tokens)
├── pe/
├── README.md (2k tokens)
├── pt/
├── pt_br/
├── README.md (2.1k tokens)
├── tr/
├── README.md (2.1k tokens)
├── vi/
├── README.md (2000 tokens)
├── zh/
├── zh_cn/
├── README.md (1400 tokens)
├── zh_tw/
├── README.md (1400 tokens)
├── pyi_hashes.json (2.1k tokens)
├── pyproject.toml (1300 tokens)
├── reflex/
├── .templates/
├── apps/
├── blank/
├── assets/
├── favicon.ico
├── code/
├── __init__.py
├── blank.py (200 tokens)
├── web/
├── .gitignore (100 tokens)
├── app/
├── entry.client.js (100 tokens)
├── routes.js (100 tokens)
├── components/
├── reflex/
├── radix_themes_color_mode_provider.js (200 tokens)
├── shiki/
├── code.js (200 tokens)
├── jsconfig.json
├── postcss.config.js
├── react-router.config.js
├── styles/
├── __reflex_style_reset.css (1800 tokens)
├── utils/
├── helpers/
├── dataeditor.js (300 tokens)
├── debounce.js (100 tokens)
├── paste.js (400 tokens)
├── range.js (200 tokens)
├── throttle.js (100 tokens)
├── upload.js (1000 tokens)
├── react-theme.js (500 tokens)
├── state.js (7k tokens)
├── vite-plugin-safari-cachebust.js (1100 tokens)
├── __init__.py (2.1k tokens)
├── __main__.py
├── admin.py (100 tokens)
├── app.py (16.2k tokens)
├── app_mixins/
├── __init__.py
├── lifespan.py (900 tokens)
├── middleware.py (600 tokens)
├── mixin.py (100 tokens)
├── assets.py (700 tokens)
├── base.py (500 tokens)
├── compiler/
├── __init__.py
├── compiler.py (5.8k tokens)
├── templates.py (4.2k tokens)
├── utils.py (3.9k tokens)
├── components/
├── __init__.py (100 tokens)
├── base/
├── __init__.py (100 tokens)
├── app_wrap.py (100 tokens)
├── bare.py (1700 tokens)
├── body.py
├── document.py (100 tokens)
├── error_boundary.py (1500 tokens)
├── fragment.py (100 tokens)
├── link.py (200 tokens)
├── meta.py (200 tokens)
├── script.py (500 tokens)
├── strict_mode.py (100 tokens)
├── component.py (19.5k tokens)
├── core/
├── __init__.py (300 tokens)
├── auto_scroll.py (800 tokens)
├── banner.py (3.7k tokens)
├── breakpoints.py (500 tokens)
├── clipboard.py (700 tokens)
├── colors.py (300 tokens)
├── cond.py (1100 tokens)
├── debounce.py (1000 tokens)
├── foreach.py (1200 tokens)
├── helmet.py
├── html.py (300 tokens)
├── layout/
├── __init__.py
├── match.py (2000 tokens)
├── responsive.py (400 tokens)
├── sticky.py (800 tokens)
├── upload.py (3k tokens)
├── window_events.py (800 tokens)
├── datadisplay/
├── __init__.py (100 tokens)
├── code.py (2.5k tokens)
├── dataeditor.py (2.8k tokens)
├── logo.py (400 tokens)
├── shiki_code_block.py (4.8k tokens)
├── dynamic.py (1500 tokens)
├── el/
├── __init__.py (100 tokens)
├── element.py (100 tokens)
├── elements/
├── __init__.py (600 tokens)
├── base.py (600 tokens)
├── forms.py (4.4k tokens)
├── inline.py (800 tokens)
├── media.py (5.2k tokens)
├── metadata.py (500 tokens)
├── other.py (300 tokens)
├── scripts.py (200 tokens)
├── sectioning.py (300 tokens)
├── tables.py (400 tokens)
├── typography.py (500 tokens)
├── field.py (1200 tokens)
├── gridjs/
├── __init__.py
├── datatable.py (800 tokens)
├── literals.py (100 tokens)
├── lucide/
├── __init__.py
├── icon.py (7.1k tokens)
├── markdown/
├── __init__.py
├── markdown.py (3.3k tokens)
├── moment/
├── __init__.py
├── moment.py (800 tokens)
├── plotly/
├── __init__.py (100 tokens)
├── plotly.py (3k tokens)
├── props.py (3k tokens)
├── radix/
├── __init__.py (100 tokens)
├── primitives/
├── __init__.py (100 tokens)
├── accordion.py (3.2k tokens)
├── base.py (400 tokens)
├── dialog.py (1100 tokens)
├── drawer.py (1800 tokens)
├── form.py (1000 tokens)
├── progress.py (800 tokens)
├── slider.py (1000 tokens)
├── themes/
├── __init__.py (100 tokens)
├── base.py (1700 tokens)
├── color_mode.py (1300 tokens)
├── components/
├── __init__.py (100 tokens)
├── alert_dialog.py (700 tokens)
├── aspect_ratio.py (100 tokens)
├── avatar.py (200 tokens)
├── badge.py (200 tokens)
├── button.py (300 tokens)
├── callout.py (500 tokens)
├── card.py (200 tokens)
├── checkbox.py (900 tokens)
├── checkbox_cards.py (300 tokens)
├── checkbox_group.py (300 tokens)
├── context_menu.py (2.6k tokens)
├── data_list.py (400 tokens)
├── dialog.py (500 tokens)
├── dropdown_menu.py (2.1k tokens)
├── hover_card.py (700 tokens)
├── icon_button.py (600 tokens)
├── inset.py (200 tokens)
├── popover.py (800 tokens)
├── progress.py (500 tokens)
├── radio.py (200 tokens)
├── radio_cards.py (600 tokens)
├── radio_group.py (1400 tokens)
├── scroll_area.py (200 tokens)
├── segmented_control.py (500 tokens)
├── select.py (1600 tokens)
├── separator.py (200 tokens)
├── skeleton.py (200 tokens)
├── slider.py (700 tokens)
├── spinner.py (100 tokens)
├── switch.py (400 tokens)
├── table.py (800 tokens)
├── tabs.py (900 tokens)
├── text_area.py (700 tokens)
├── text_field.py (900 tokens)
├── tooltip.py (900 tokens)
├── layout/
├── __init__.py (100 tokens)
├── base.py (200 tokens)
├── box.py (100 tokens)
├── center.py (100 tokens)
├── container.py (300 tokens)
├── flex.py (300 tokens)
├── grid.py (300 tokens)
├── list.py (1100 tokens)
├── section.py (100 tokens)
├── spacer.py (100 tokens)
├── stack.py (300 tokens)
├── typography/
├── __init__.py (100 tokens)
├── base.py (100 tokens)
├── blockquote.py (200 tokens)
├── code.py (200 tokens)
├── heading.py (300 tokens)
├── link.py (800 tokens)
├── text.py (600 tokens)
├── react_player/
├── __init__.py
├── audio.py
├── react_player.py (1600 tokens)
├── video.py
├── react_router/
├── __init__.py
├── dom.py (500 tokens)
├── recharts/
├── __init__.py (500 tokens)
├── cartesian.py (6.8k tokens)
├── charts.py (3.8k tokens)
├── general.py (1800 tokens)
├── polar.py (3.1k tokens)
├── recharts.py (600 tokens)
├── sonner/
├── __init__.py
├── toast.py (2.5k tokens)
├── tags/
├── __init__.py
├── cond_tag.py (200 tokens)
├── iter_tag.py (700 tokens)
├── match_tag.py (200 tokens)
├── tag.py (800 tokens)
├── tagless.py (200 tokens)
├── config.py (4.3k tokens)
├── constants/
├── __init__.py (400 tokens)
├── base.py (1500 tokens)
├── colors.py (400 tokens)
├── compiler.py (1100 tokens)
├── config.py (300 tokens)
├── custom_components.py (300 tokens)
├── event.py (600 tokens)
├── installer.py (800 tokens)
├── route.py (500 tokens)
├── state.py (100 tokens)
├── utils.py (200 tokens)
├── custom_components/
├── __init__.py
├── custom_components.py (5.1k tokens)
├── environment.py (5.4k tokens)
├── event.py (15.4k tokens)
├── experimental/
├── __init__.py (300 tokens)
├── client_state.py (2000 tokens)
├── hooks.py (500 tokens)
├── istate/
├── __init__.py (400 tokens)
├── data.py (1600 tokens)
├── dynamic.py
├── manager/
├── __init__.py (900 tokens)
├── disk.py (2.7k tokens)
├── memory.py (600 tokens)
├── redis.py (8.4k tokens)
├── proxy.py (5.3k tokens)
├── storage.py (900 tokens)
├── wrappers.py (200 tokens)
├── middleware/
├── __init__.py
├── hydrate_middleware.py (300 tokens)
├── middleware.py (200 tokens)
├── model.py (4.5k tokens)
├── page.py (700 tokens)
├── plugins/
├── __init__.py (100 tokens)
├── _screenshot.py (800 tokens)
├── base.py (700 tokens)
├── shared_tailwind.py (1400 tokens)
├── sitemap.py (1200 tokens)
├── tailwind_v3.py (1000 tokens)
├── tailwind_v4.py (1000 tokens)
├── py.typed
├── reflex.py (5.2k tokens)
├── route.py (1600 tokens)
├── state.py (19.5k tokens)
├── style.py (2.7k tokens)
├── testing.py (8.4k tokens)
├── utils/
├── __init__.py
├── build.py (2000 tokens)
├── codespaces.py (900 tokens)
├── compat.py (600 tokens)
├── console.py (2.7k tokens)
├── decorator.py (800 tokens)
├── exceptions.py (1800 tokens)
├── exec.py (4.6k tokens)
├── export.py (600 tokens)
├── format.py (4.2k tokens)
├── frontend_skeleton.py (1800 tokens)
├── imports.py (900 tokens)
├── js_runtimes.py (2.7k tokens)
├── lazy_loader.py (900 tokens)
├── misc.py (900 tokens)
├── monitoring.py (1000 tokens)
├── net.py (900 tokens)
├── path_ops.py (1600 tokens)
├── prerequisites.py (4.3k tokens)
├── processes.py (3.6k tokens)
├── pyi_generator.py (9.2k tokens)
├── redir.py (200 tokens)
├── registry.py (400 tokens)
├── rename.py (1000 tokens)
├── serializers.py (2.8k tokens)
├── tasks.py (900 tokens)
├── telemetry.py (2.2k tokens)
├── templates.py (2.8k tokens)
├── token_manager.py (3.2k tokens)
├── types.py (8k tokens)
├── vars/
├── __init__.py (300 tokens)
├── base.py (22.6k tokens)
├── color.py (1000 tokens)
├── datetime.py (1000 tokens)
├── dep_tracking.py (2.8k tokens)
├── function.py (2.8k tokens)
├── number.py (5.8k tokens)
├── object.py (3.6k tokens)
├── sequence.py (10.5k tokens)
├── scripts/
├── __init__.py
├── bun_install.sh (1500 tokens)
├── darglint_test.bat (100 tokens)
├── hatch_build.py (400 tokens)
├── install.ps1 (2.4k tokens)
├── integration.sh (200 tokens)
├── make_pyi.py (700 tokens)
├── wait_for_listening_port.py (400 tokens)
├── tests/
├── __init__.py
├── benchmarks/
├── __init__.py
├── conftest.py
├── fixtures.py (2.6k tokens)
├── test_compilation.py (200 tokens)
├── test_evaluate.py (100 tokens)
├── integration/
├── __init__.py
├── conftest.py (200 tokens)
├── init-test/
├── Dockerfile
├── in_docker_test_script.sh (200 tokens)
├── shared/
├── state.py
├── test_background_task.py (3.1k tokens)
├── test_call_script.py (3.9k tokens)
├── test_client_storage.py (6k tokens)
├── test_component_state.py (1400 tokens)
├── test_computed_vars.py (1700 tokens)
├── test_connection_banner.py (1700 tokens)
├── test_deploy_url.py (600 tokens)
├── test_dynamic_components.py (800 tokens)
├── test_dynamic_routes.py (3.1k tokens)
├── test_event_actions.py (2.8k tokens)
├── test_event_chain.py (4.1k tokens)
├── test_exception_handlers.py (1200 tokens)
├── test_extra_overlay_function.py (500 tokens)
├── test_form_submit.py (1600 tokens)
├── test_icon.py (600 tokens)
├── test_input.py (1300 tokens)
├── test_large_state.py (600 tokens)
├── test_lifespan.py (1200 tokens)
├── test_login_flow.py (800 tokens)
├── test_media.py (1100 tokens)
├── test_memo.py (600 tokens)
├── test_navigation.py (500 tokens)
├── test_server_side_event.py (1100 tokens)
├── test_shared_state.py (300 tokens)
├── test_state_inheritance.py (3.3k tokens)
├── test_tailwind.py (1000 tokens)
├── test_upload.py (4k tokens)
├── test_urls.py (400 tokens)
├── test_var_operations.py (7.6k tokens)
├── tests_playwright/
├── test_appearance.py (1300 tokens)
├── test_datetime_operations.py (700 tokens)
├── test_link_hover.py (200 tokens)
├── test_stateless_app.py (300 tokens)
├── test_table.py (600 tokens)
├── utils.py (900 tokens)
├── test_node_version.py (400 tokens)
├── units/
├── __init__.py
├── assets/
├── custom_script.js
├── test_assets.py (500 tokens)
├── compiler/
├── __init__.py
├── test_compiler.py (3k tokens)
├── test_compiler_utils.py
├── components/
├── __init__.py
├── base/
├── test_bare.py (100 tokens)
├── test_link.py (100 tokens)
├── test_script.py (200 tokens)
├── core/
├── __init__.py
├── test_banner.py (300 tokens)
├── test_colors.py (1100 tokens)
├── test_cond.py (900 tokens)
├── test_debounce.py (1100 tokens)
├── test_foreach.py (1900 tokens)
├── test_html.py (200 tokens)
├── test_match.py (2.3k tokens)
├── test_responsive.py (200 tokens)
├── test_upload.py (600 tokens)
├── datadisplay/
├── __init__.py
├── conftest.py (300 tokens)
├── test_code.py (100 tokens)
├── test_dataeditor.py (100 tokens)
├── test_datatable.py (800 tokens)
├── test_shiki_code.py (1200 tokens)
├── el/
├── test_svg.py (300 tokens)
├── forms/
├── __init__.py
├── test_form.py (200 tokens)
├── graphing/
├── __init__.py
├── test_plotly.py (200 tokens)
├── test_recharts.py (300 tokens)
├── layout/
├── __init__.py
├── lucide/
├── test_icon.py (200 tokens)
├── markdown/
├── __init__.py
├── test_markdown.py (1600 tokens)
├── media/
├── __init__.py
├── test_image.py (200 tokens)
├── radix/
├── test_icon_button.py (200 tokens)
├── test_layout.py
├── recharts/
├── test_cartesian.py (200 tokens)
├── test_polar.py (200 tokens)
├── test_component.py (13.8k tokens)
├── test_component_future_annotations.py (200 tokens)
├── test_component_state.py (400 tokens)
├── test_props.py (1200 tokens)
├── test_tag.py (700 tokens)
├── typography/
├── __init__.py
├── test_markdown.py (300 tokens)
├── conftest.py (900 tokens)
├── istate/
├── __init__.py
├── manager/
├── __init__.py
├── test_redis.py (4.1k tokens)
├── middleware/
├── __init__.py
├── conftest.py (100 tokens)
├── test_hydrate_middleware.py (300 tokens)
├── mock_redis.py (1900 tokens)
├── plugins/
├── test_sitemap.py (2.8k tokens)
├── states/
├── __init__.py (100 tokens)
├── mutation.py (300 tokens)
├── upload.py (800 tokens)
├── test_app.py (13.6k tokens)
├── test_attribute_access_type.py (2.2k tokens)
├── test_base.py (300 tokens)
├── test_config.py (2.3k tokens)
├── test_db_config.py (1200 tokens)
├── test_environment.py (4.5k tokens)
├── test_event.py (4.6k tokens)
├── test_health_endpoint.py (1000 tokens)
├── test_model.py (1400 tokens)
├── test_page.py (300 tokens)
├── test_prerequisites.py (1600 tokens)
├── test_route.py (700 tokens)
├── test_sqlalchemy.py (1900 tokens)
├── test_state.py (26.2k tokens)
├── test_state_tree.py (1800 tokens)
├── test_style.py (3.6k tokens)
├── test_telemetry.py (400 tokens)
├── test_testing.py (200 tokens)
├── test_var.py (11.5k tokens)
├── utils/
├── __init__.py
├── test_format.py (4.5k tokens)
├── test_imports.py (700 tokens)
├── test_processes.py (1000 tokens)
├── test_serializers.py (1400 tokens)
├── test_tasks.py (700 tokens)
├── test_token_manager.py (4.5k tokens)
├── test_types.py (800 tokens)
├── test_utils.py (3.5k tokens)
├── vars/
├── test_base.py (300 tokens)
├── test_dep_tracking.py (2.1k tokens)
├── test_dep_tracking_integration.py (1500 tokens)
├── test_object.py (1000 tokens)
├── uv.lock (omitted)
```
## /.devcontainer/devcontainer.json
```json path="/.devcontainer/devcontainer.json"
{
"image": "mcr.microsoft.com/devcontainers/python:1-3.11-bookworm",
"postCreateCommand": "/bin/bash -c 'python -m pip install uv && python -m uv sync & git clone https://github.com/reflex-dev/reflex-examples; wait'",
"forwardPorts": [3000, 8000],
"portsAttributes": {
"3000": {
"label": "Frontend",
"onAutoForward": "notify"
},
"8000": {
"label": "Backend"
}
}
}
```
## /.github/CODEOWNERS
```github/CODEOWNERS path="/.github/CODEOWNERS"
@reflex-dev/reflex-team
```
## /.github/ISSUE_TEMPLATE/bug_report.md
---
name: Bug report
about: Create a report to help us improve
title: ""
assignees: ""
---
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
- Code/Link to Repo:
**Expected behavior**
A clear and concise description of what you expected to happen.
**Screenshots**
If applicable, add screenshots to help explain your problem.
**Specifics (please complete the following information):**
- Python Version:
- Reflex Version:
- OS:
- Browser (Optional):
**Additional context**
Add any other context about the problem here.
## /.github/ISSUE_TEMPLATE/build_issue.md
---
name: Build Issue
about: Report an issue related to reflex.build
title: "[BUILD] " # This acts as a hint, but users can change it.
labels: build
assignees: ""
---
## Describe the issue
Provide details about the issue.
...
## Expected behavior
What should have happened?
...
## Steps to reproduce (if applicable)
1.
2.
3.
## Environment
- Reflex Version:
- Python Version:
- OS:
- Browser:
## /.github/ISSUE_TEMPLATE/cloud_issue.md
---
name: Cloud Issue
about: Report an issue related to Reflex Cloud
title: "[CLOUD] " # This acts as a hint, but users can change it.
labels: cloud
assignees: ""
---
## Describe the issue
Provide details about the issue.
...
## Expected behavior
What should have happened?
...
## Steps to reproduce (if applicable)
1.
2.
3.
## Environment
- Reflex Version:
- Python Version:
- OS:
- Browser:
## /.github/ISSUE_TEMPLATE/custom_component_request.md
---
name: Custom Component Request
about: Suggest a new custom component for Reflex
title: ""
labels: "custom component request"
assignees: ""
---
**Describe the Custom Component**
A clear and concise description of what the custom component does.
- What is the purpose of the custom component?
- What is the expected behavior of the custom component?
- What are the use cases for the custom component?
**Specifics (please complete the following information):**
- Do you have a specific react package in mind? (Optional):
**Additional context**
Add any other context about the custom component here.
## /.github/ISSUE_TEMPLATE/enhancement_request.md
---
name: Enhancement Request
about: Suggest an enhancement for an existing Reflex feature.
title: ""
labels: "enhancement"
assignees: ""
---
**Describe the Enhancement you want**
A clear and concise description of what the improvement does.
- Which feature do you want to improve? (and what problem does it have)
- What is the benefit of the enhancement?
- Show an example/usecase were the improvement are needed.
**Additional context**
Add any other context here.
## /.github/ISSUE_TEMPLATE/enterprise_issue.md
---
name: Enterprise Issue
about: Report an issue related to Reflex Enterprise
title: "[ENTERPRISE] " # This acts as a hint, but users can change it.
labels: enterprise
assignees: ""
---
## Describe the issue
Provide details about the issue.
...
## Expected behavior
What should have happened?
...
## Steps to reproduce (if applicable)
1.
2.
3.
## Environment
- Reflex Version:
- Python Version:
- OS:
- Browser:
## /.github/ISSUE_TEMPLATE/feature_request.md
---
name: Feature Request
about: Suggest a new feature for Reflex
title: ""
labels: "feature request"
assignees: ""
---
**Describe the Features**
A clear and concise description of what the features does.
- What is the purpose of the feature?
- Show an example / use cases for the new feature.
**Additional context**
Add any other context here.
## /.github/actions/setup_build_env/action.yml
```yml path="/.github/actions/setup_build_env/action.yml"
# Entry conditions:
# - `setup/checkout` has already happened
# - working dir is the root directory of your project (e.g. `reflex/`).
# - You have a `uv.lock` file in the root directory of your project
# - You have a `pyproject.toml` file in the root directory of your project
#
# Exit conditions:
# - Python of version `python-version` is ready to be invoked as `python`.
# - If `run-uv-sync` is true, deps as defined in `pyproject.toml` will have been installed into the venv at `create-venv-at-path`.
name: "Setup Reflex build environment"
description: "Sets up Python, install uv (cached), install project deps (cached)"
inputs:
python-version:
description: "Python version setup"
required: true
run-uv-sync:
description: "Whether to run uv sync on current dir"
required: false
default: false
create-venv-at-path:
description: "Path to venv (if uv sync is enabled)"
required: false
default: ".venv"
runs:
using: "composite"
steps:
- name: Install UV
uses: astral-sh/setup-uv@v6
with:
python-version: ${{ inputs.python-version }}
enable-cache: true
prune-cache: false
activate-environment: true
cache-dependency-glob: "uv.lock"
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version: 22
- name: Install Dependencies
if: inputs.run-uv-sync == 'true'
run: uv sync
shell: bash
```
## /.github/codeql-config.yml
```yml path="/.github/codeql-config.yml"
paths-ignore:
- "**/tests/**"
```
## /.github/pull_request_template.md
### All Submissions:
- [ ] Have you followed the guidelines stated in [CONTRIBUTING.md](https://github.com/reflex-dev/reflex/blob/main/CONTRIBUTING.md) file?
- [ ] Have you checked to ensure there aren't any other open [Pull Requests](https://github.com/reflex-dev/reflex/pulls) for the desired changed?
<!-- You can erase any parts of this template not applicable to your Pull Request. -->
### Type of change
Please delete options that are not relevant.
- [ ] Bug fix (non-breaking change which fixes an issue)
- [ ] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected)
- [ ] This change requires a documentation update
### New Feature Submission:
- [ ] Does your submission pass the tests?
- [ ] Have you linted your code locally prior to submission?
### Changes To Core Features:
- [ ] Have you added an explanation of what your changes do and why you'd like us to include them?
- [ ] Have you written new tests for your core changes, as applicable?
- [ ] Have you successfully ran tests with your changes locally?
### **After** these steps, you're ready to open a pull request.
a. Give a descriptive title to your PR.
b. Describe your changes.
c. Put `closes #XXXX` in your comment to auto-close the issue that your PR fixes (if such).
## /.github/workflows/check_node_latest.yml
```yml path="/.github/workflows/check_node_latest.yml"
name: integration-node-latest
permissions:
contents: read
on:
push:
branches:
- main
pull_request:
branches:
- main
env:
REFLEX_TELEMETRY_ENABLED: false
jobs:
check_latest_node:
runs-on: ubuntu-22.04
strategy:
matrix:
split_index: [1, 2]
node-version: ["node"]
fail-fast: false
steps:
- uses: actions/checkout@v4
- uses: ./.github/actions/setup_build_env
with:
python-version: 3.13
run-uv-sync: true
- uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node-version }}
- run: uv run playwright install --with-deps
- run: |
uv run pytest tests/test_node_version.py -v
uv run pytest tests/integration --splits 2 -v --group ${{matrix.split_index}}
```
## /.github/workflows/check_outdated_dependencies.yml
```yml path="/.github/workflows/check_outdated_dependencies.yml"
name: check-outdated-dependencies
permissions:
contents: read
on:
push: # This will trigger the action when a pull request is opened or updated.
branches:
- "release/**" # This will trigger the action when any branch starting with "release/" is created.
workflow_dispatch: # Allow manual triggering if needed.
jobs:
backend:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v3
- uses: ./.github/actions/setup_build_env
with:
python-version: 3.13
run-uv-sync: true
- name: Check outdated backend dependencies
run: |
outdated=$(uv pip list --outdated)
echo "Outdated:"
echo "$outdated"
filtered_outdated=$(echo "$outdated" | grep -vE 'pyright|ruff' || true)
if [ ! -z "$filtered_outdated" ]; then
echo "Outdated dependencies found:"
echo "$filtered_outdated"
exit 1
else
echo "All dependencies are up to date. (pyright and ruff are ignored)"
fi
frontend:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- uses: ./.github/actions/setup_build_env
with:
python-version: 3.13
run-uv-sync: true
- name: Clone Reflex Website Repo
uses: actions/checkout@v4
with:
repository: reflex-dev/reflex-web
ref: main
path: reflex-web
- name: Compile pyproject.toml into requirements.txt
working-directory: ./reflex-web
run: |
uv pip compile pyproject.toml --no-annotate --no-header --no-deps --output-file requirements.txt
grep -ivE "reflex " requirements.txt > requirements.txt.tmp && mv requirements.txt.tmp requirements.txt
- name: Install Requirements for reflex-web
working-directory: ./reflex-web
run: uv pip install -r requirements.txt
- name: Init Website for reflex-web
working-directory: ./reflex-web
run: uv run reflex init
- name: Run Website and Check for errors
run: |
uv run bash scripts/integration.sh ./reflex-web dev
- name: Check outdated frontend dependencies
working-directory: ./reflex-web/.web
run: |
raw_outdated=$(/home/runner/.local/share/reflex/bun/bin/bun outdated)
outdated=$(echo "$raw_outdated" | grep -vE '\|\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\|' || true)
echo "Outdated:"
echo "$outdated"
# Ignore 3rd party dependencies that are not updated.
filtered_outdated=$(echo "$outdated" | grep -vE 'Package|@chakra-ui|lucide-react|@splinetool/runtime|ag-grid-react|framer-motion|react-markdown|remark-math|remark-gfm|rehype-katex|rehype-raw|remark-unwrap-images|ag-grid' || true)
no_extra=$(echo "$filtered_outdated" | grep -vE '\|\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-' || true)
if [ ! -z "$no_extra" ]; then
echo "Outdated dependencies found:"
echo "$filtered_outdated"
exit 1
else
echo "All dependencies are up to date. (3rd party packages are ignored)"
fi
```
## /.github/workflows/codeql.yml
```yml path="/.github/workflows/codeql.yml"
# For most projects, this workflow file will not need changing; you simply need
# to commit it to your repository.
#
# You may wish to alter this file to override the set of languages analyzed,
# or to provide custom queries or build logic.
#
# ******** NOTE ********
# We have attempted to detect the languages in your repository. Please check
# the `language` matrix defined below to confirm you have the correct set of
# supported CodeQL languages.
#
name: "CodeQL Advanced"
on:
push:
branches: ["main"]
pull_request:
branches: ["main"]
schedule:
- cron: "36 7 * * 4"
jobs:
analyze:
name: Analyze (${{ matrix.language }})
# Runner size impacts CodeQL analysis time. To learn more, please see:
# - https://gh.io/recommended-hardware-resources-for-running-codeql
# - https://gh.io/supported-runners-and-hardware-resources
# - https://gh.io/using-larger-runners (GitHub.com only)
# Consider using larger runners or machines with greater resources for possible analysis time improvements.
runs-on: ${{ (matrix.language == 'swift' && 'macos-latest') || 'ubuntu-latest' }}
permissions:
# required for all workflows
security-events: write
# required to fetch internal or private CodeQL packs
packages: read
# only required for workflows in private repositories
actions: read
contents: read
strategy:
fail-fast: false
matrix:
include:
- language: javascript-typescript
build-mode: none
- language: python
build-mode: none
- language: actions
build-mode: none
# CodeQL supports the following values keywords for 'language': 'c-cpp', 'csharp', 'go', 'java-kotlin', 'javascript-typescript', 'python', 'ruby', 'swift'
# Use `c-cpp` to analyze code written in C, C++ or both
# Use 'java-kotlin' to analyze code written in Java, Kotlin or both
# Use 'javascript-typescript' to analyze code written in JavaScript, TypeScript or both
# To learn more about changing the languages that are analyzed or customizing the build mode for your analysis,
# see https://docs.github.com/en/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/customizing-your-advanced-setup-for-code-scanning.
# If you are analyzing a compiled language, you can modify the 'build-mode' for that language to customize how
# your codebase is analyzed, see https://docs.github.com/en/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/codeql-code-scanning-for-compiled-languages
steps:
- name: Checkout repository
uses: actions/checkout@v4
# Add any setup steps before running the `github/codeql-action/init` action.
# This includes steps like installing compilers or runtimes (`actions/setup-node`
# or others). This is typically only required for manual builds.
# - name: Setup runtime (example)
# uses: actions/setup-example@v1
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v3
with:
languages: ${{ matrix.language }}
config-file: .github/codeql-config.yml
build-mode: ${{ matrix.build-mode }}
# If you wish to specify custom queries, you can do so here or in a config file.
# By default, queries listed here will override any specified in a config file.
# Prefix the list here with "+" to use these queries and those in the config file.
# For more details on CodeQL's query packs, refer to: https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs
# queries: security-extended,security-and-quality
# If the analyze step fails for one of the languages you are analyzing with
# "We were unable to automatically build your code", modify the matrix above
# to set the build mode to "manual" for that language. Then modify this step
# to build your code.
# ℹ️ Command-line programs to run using the OS shell.
# 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun
- if: matrix.build-mode == 'manual'
shell: bash
run: |
echo 'If you are using a "manual" build mode for one or more of the' \
'languages you are analyzing, replace this with the commands to build' \
'your code, for example:'
echo ' make bootstrap'
echo ' make release'
exit 1
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v3
with:
category: "/language:${{matrix.language}}"
```
## /.github/workflows/dependency-review.yml
```yml path="/.github/workflows/dependency-review.yml"
name: "Dependency Review"
on: [pull_request]
permissions:
contents: read
jobs:
dependency-review:
runs-on: ubuntu-latest
steps:
- name: "Checkout Repository"
uses: actions/checkout@v4
- name: "Dependency Review"
uses: actions/dependency-review-action@v4
with:
allow-licenses: Apache-2.0, BSD-2-Clause, BSD-3-Clause, HPND, ISC, MIT, MPL-2.0, Unlicense, Python-2.0, Python-2.0.1, Apache-2.0 AND MIT, BSD-2-Clause AND BSD-3-Clause, Apache-2.0 AND BSD-3-Clause
allow-dependencies-licenses: "pkg:pypi/lazy-loader"
```
## /.github/workflows/integration_app_harness.yml
```yml path="/.github/workflows/integration_app_harness.yml"
name: integration-app-harness
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.id }}
cancel-in-progress: true
on:
push:
branches: ["main"]
paths-ignore:
- "**/*.md"
pull_request:
branches: ["main"]
paths-ignore:
- "**/*.md"
env:
APP_HARNESS_HEADLESS: 1
PYTHONUNBUFFERED: 1
permissions:
contents: read
jobs:
integration-app-harness:
timeout-minutes: 30
strategy:
matrix:
state_manager: ["redis", "memory"]
python-version: ["3.11", "3.12", "3.13", "3.14"]
split_index: [1, 2]
fail-fast: false
runs-on: ubuntu-22.04
services:
# Label used to access the service container
redis:
image: ${{ matrix.state_manager == 'redis' && 'redis' || '' }}
# Set health checks to wait until redis has started
options: >-
--health-cmd "redis-cli ping"
--health-interval 10s
--health-timeout 5s
--health-retries 5
ports:
# Maps port 6379 on service container to the host
- 6379:6379
steps:
- uses: actions/checkout@v4
- uses: ./.github/actions/setup_build_env
with:
python-version: ${{ matrix.python-version }}
run-uv-sync: true
- name: Install playwright
run: uv run playwright install chromium --only-shell
- name: Run app harness tests
env:
REFLEX_REDIS_URL: ${{ matrix.state_manager == 'redis' && 'redis://localhost:6379' || '' }}
run: uv run pytest tests/integration --reruns 3 -v --maxfail=5 --splits 2 --group ${{matrix.split_index}}
```
## /.github/workflows/integration_tests.yml
```yml path="/.github/workflows/integration_tests.yml"
name: integration-tests
on:
push:
branches: ["main"]
paths-ignore:
- "**/*.md"
pull_request:
branches: ["main"]
paths-ignore:
- "**/*.md"
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.id }}
cancel-in-progress: true
permissions:
contents: read
defaults:
run:
shell: bash
env:
# Windows CI would fail without this.
# Ref: https://gist.github.com/NodeJSmith/e7e37f2d3f162456869f015f842bcf15
# TODO: can we fix windows encoding natively within reflex? Bug above can hit real users too (less common, but possible)
# - Catch encoding errors when printing logs
# - Best effort print lines that contain illegal chars (map to some default char, etc.)
PYTHONIOENCODING: "utf8"
REFLEX_TELEMETRY_ENABLED: false
NODE_OPTIONS: "--max_old_space_size=8192"
PR_TITLE: ${{ github.event.pull_request.title }}
jobs:
example-counter-and-nba-proxy:
env:
OUTPUT_FILE: import_benchmark.json
timeout-minutes: 30
strategy:
# Prioritize getting more information out of the workflow (even if something fails)
fail-fast: false
matrix:
# Show OS combos first in GUI
os: [ubuntu-latest, windows-latest]
python-version: ["3.10", "3.11", "3.12", "3.13"]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v4
- uses: ./.github/actions/setup_build_env
with:
python-version: ${{ matrix.python-version }}
run-uv-sync: true
- name: Clone Reflex Examples Repo
uses: actions/checkout@v4
with:
repository: reflex-dev/reflex-examples
path: reflex-examples
- name: Install requirements for counter example
working-directory: ./reflex-examples/counter
run: |
uv pip install -r requirements.txt
- name: Check export --backend-only before init for counter example
working-directory: ./reflex-examples/counter
run: |
uv run reflex export --backend-only
- name: Check run --backend-only before init for counter example
run: |
uv run bash scripts/integration.sh ./reflex-examples/counter dev 8001 --backend-only --backend-port 8001
- name: Init Website for counter example
working-directory: ./reflex-examples/counter
run: |
uv run reflex init --loglevel debug
- name: Check export for counter example
working-directory: ./reflex-examples/counter
run: |
uv run reflex export
- name: Run Website and Check for errors
run: |
# Check that npm is home
npm -v
uv run bash scripts/integration.sh ./reflex-examples/counter dev
- name: Install requirements for nba proxy example
working-directory: ./reflex-examples/nba-proxy
run: |
uv pip install -r requirements.txt
- name: Check export --backend-only before init for nba-proxy example
working-directory: ./reflex-examples/nba-proxy
run: |
uv run reflex export --backend-only
- name: Init Website for nba-proxy example
working-directory: ./reflex-examples/nba-proxy
run: |
uv run reflex init --loglevel debug
- name: Run Website and Check for errors
run: |
# Check that npm is home
npm -v
uv run bash scripts/integration.sh ./reflex-examples/nba-proxy dev
reflex-web:
strategy:
fail-fast: false
matrix:
python-version: ["3.11", "3.12"]
env:
REFLEX_WEB_WINDOWS_OVERRIDE: "1"
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: ./.github/actions/setup_build_env
with:
python-version: ${{ matrix.python-version }}
run-uv-sync: true
- name: Clone Reflex Website Repo
uses: actions/checkout@v4
with:
repository: reflex-dev/reflex-web
ref: main
path: reflex-web
- name: Compile pyproject.toml into requirements.txt
working-directory: ./reflex-web
run: |
uv pip compile pyproject.toml --no-annotate --no-header --no-deps --output-file requirements.txt
grep -ivE "reflex " requirements.txt > requirements.txt.tmp && mv requirements.txt.tmp requirements.txt
- name: Install Requirements for reflex-web
working-directory: ./reflex-web
run: uv pip install -r requirements.txt
- name: Init Website for reflex-web
working-directory: ./reflex-web
run: uv run --active --no-sync reflex init
- name: Run Website and Check for errors
run: |
# Check that npm is home
npm -v
uv run --active --no-sync bash scripts/integration.sh ./reflex-web prod
rx-shout-from-template:
strategy:
fail-fast: false
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: ./.github/actions/setup_build_env
with:
python-version: 3.14
run-uv-sync: true
- name: Create app directory
run: mkdir rx-shout-from-template
- name: Init reflex-web from template
run: uv run reflex init --template https://github.com/masenf/rx_shout
working-directory: ./rx-shout-from-template
- name: ignore reflex pin in requirements
run: sed -i -e '/reflex==/d' requirements.txt
working-directory: ./rx-shout-from-template
- name: Install additional dependencies
run: uv pip install -r requirements.txt
working-directory: ./rx-shout-from-template
- name: Run Website and Check for errors
run: |
# Check that npm is home
npm -v
uv run bash scripts/integration.sh ./rx-shout-from-template prod
reflex-web-macos:
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
strategy:
fail-fast: false
matrix:
# Note: py311 version chosen due to available arm64 darwin builds.
python-version: ["3.11", "3.12"]
runs-on: macos-latest
steps:
- uses: actions/checkout@v4
- uses: ./.github/actions/setup_build_env
with:
python-version: ${{ matrix.python-version }}
run-uv-sync: true
- name: Clone Reflex Website Repo
uses: actions/checkout@v4
with:
repository: reflex-dev/reflex-web
ref: main
path: reflex-web
- name: Compile pyproject.toml into requirements.txt
working-directory: ./reflex-web
run: |
uv pip compile pyproject.toml --no-annotate --no-header --no-deps --output-file requirements.txt
grep -ivE "reflex " requirements.txt > requirements.txt.tmp && mv requirements.txt.tmp requirements.txt
- name: Install Requirements for reflex-web
working-directory: ./reflex-web
run: uv pip install -r requirements.txt
- name: Init Website for reflex-web
working-directory: ./reflex-web
run: uv run --active --no-sync reflex init
- name: Run Website and Check for errors
run: |
# Check that npm is home
npm -v
uv run --active --no-sync bash scripts/integration.sh ./reflex-web prod
```
## /.github/workflows/performance.yml
```yml path="/.github/workflows/performance.yml"
name: performance-tests
permissions:
contents: read
on:
push:
branches:
- "main" # or "master"
paths-ignore:
- "**/*.md"
pull_request:
workflow_dispatch:
env:
REFLEX_TELEMETRY_ENABLED: false
NODE_OPTIONS: "--max_old_space_size=8192"
PR_TITLE: ${{ github.event.pull_request.title }}
APP_HARNESS_HEADLESS: 1
PYTHONUNBUFFERED: 1
jobs:
benchmarks:
name: Run benchmarks
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install uv
uses: astral-sh/setup-uv@v6
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: "3.14"
- name: Install dependencies
run: uv sync --all-extras --dev
- name: Run benchmarks
uses: CodSpeedHQ/action@v4
with:
mode: instrumentation
run: uv run pytest -v tests/benchmarks --codspeed
```
## /.github/workflows/pre-commit.yml
```yml path="/.github/workflows/pre-commit.yml"
name: pre-commit
permissions:
contents: read
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.id }}
cancel-in-progress: true
on:
pull_request:
branches: ["main"]
push:
# Note even though this job is called "pre-commit" and runs "pre-commit", this job will run
# also POST-commit on main also! In case there are mishandled merge conflicts / bad auto-resolves
# when merging into main branch.
branches: ["main"]
jobs:
pre-commit:
timeout-minutes: 30
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: ./.github/actions/setup_build_env
with:
python-version: 3.14
run-uv-sync: true
- uses: actions/checkout@v4
with:
clean: false
- run: uv run pre-commit run --all-files --show-diff-on-failure
```
## /.github/workflows/reflex_init_in_docker_test.yml
```yml path="/.github/workflows/reflex_init_in_docker_test.yml"
name: reflex-init-in-docker-test
permissions:
contents: read
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.id }}
cancel-in-progress: true
on:
push:
branches: ["main"]
paths-ignore:
- "**/*.md"
pull_request:
branches: ["main"]
paths-ignore:
- "**/*.md"
jobs:
# TODO we can extend to various starting points (e.g. Ubuntu with node, without node, with unzip, without unzip, etc.)
# Currently starting point is: Ubuntu + unzip, xz-utils, Python suite. No node.
reflex-install-and-init:
timeout-minutes: 30
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- shell: bash
run: |
# Run reflex init in a docker container
# cwd is repo root
docker build -f tests/integration/init-test/Dockerfile -t reflex-init-test tests/integration/init-test
docker run --rm -v $(pwd):/reflex-repo/ reflex-init-test /reflex-repo/tests/integration/init-test/in_docker_test_script.sh
```
## /.github/workflows/unit_tests.yml
```yml path="/.github/workflows/unit_tests.yml"
name: unit-tests
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.id }}
cancel-in-progress: true
on:
push:
branches: ["main"]
paths-ignore:
- "**/*.md"
pull_request:
branches: ["main"]
paths-ignore:
- "**/*.md"
permissions:
contents: read
defaults:
run:
shell: bash
jobs:
unit-tests:
timeout-minutes: 30
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, windows-latest]
python-version: ["3.10", "3.11", "3.12", "3.13", "3.14"]
runs-on: ${{ matrix.os }}
# Service containers to run with `runner-job`
services:
# Label used to access the service container
redis:
image: ${{ matrix.os == 'ubuntu-latest' && 'redis' || '' }}
# Set health checks to wait until redis has started
options: >-
--health-cmd "redis-cli ping"
--health-interval 10s
--health-timeout 5s
--health-retries 5
ports:
# Maps port 6379 on service container to the host
- 6379:6379
steps:
- uses: actions/checkout@v4
- uses: ./.github/actions/setup_build_env
with:
python-version: ${{ matrix.python-version }}
run-uv-sync: true
- name: Run unit tests
run: |
export PYTHONUNBUFFERED=1
uv run pytest tests/units --cov --no-cov-on-fail --cov-report=
- name: Run unit tests w/ redis
if: ${{ matrix.os == 'ubuntu-latest' }}
run: |
export PYTHONUNBUFFERED=1
export REFLEX_REDIS_URL=redis://localhost:6379
uv run pytest tests/units --cov --no-cov-on-fail --cov-report=
- name: Run unit tests w/ redis and OPLOCK_ENABLED
if: ${{ matrix.os == 'ubuntu-latest' }}
run: |
export PYTHONUNBUFFERED=1
export REFLEX_REDIS_URL=redis://localhost:6379
export REFLEX_OPLOCK_ENABLED=true
uv run pytest tests/units --cov --no-cov-on-fail --cov-report=
# Change to explicitly install v1 when reflex-hosting-cli is compatible with v2
- name: Run unit tests w/ pydantic v1
run: |
export PYTHONUNBUFFERED=1
uv pip install "pydantic~=1.10"
uv run pytest tests/units --cov --no-cov-on-fail --cov-report=
- name: Generate coverage report
run: uv run coverage html
unit-tests-macos:
timeout-minutes: 30
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
strategy:
fail-fast: false
matrix:
python-version: ["3.10", "3.11", "3.12", "3.13", "3.14"]
runs-on: macos-latest
steps:
- uses: actions/checkout@v4
- uses: ./.github/actions/setup_build_env
with:
python-version: ${{ matrix.python-version }}
run-uv-sync: true
- name: Run unit tests
run: |
export PYTHONUNBUFFERED=1
uv run pytest tests/units --cov --no-cov-on-fail --cov-report=
- name: Run unit tests w/ pydantic v1
run: |
export PYTHONUNBUFFERED=1
uv pip install "pydantic~=1.10"
uv run pytest tests/units --cov --no-cov-on-fail --cov-report=
```
## /.gitignore
```gitignore path="/.gitignore"
**/.DS_Store
**/*.pyc
assets/external/*
dist/*
examples/
.web
.states
.idea
.vscode
.coverage
.coverage.*
.venv
venv
requirements.txt
.pyi_generator_last_run
.pyi_generator_diff
reflex.db
.codspeed
.env
.env.*
node_modules
package-lock.json
*.pyi
.pre-commit-config.yaml
```
## /.python-version
```python-version path="/.python-version"
3.14
```
## /CODE_OF_CONDUCT.md
# Contributor Covenant Code of Conduct
## Our Pledge
We as members, contributors, and leaders pledge to make participation in our
community a harassment-free experience for everyone, regardless of age, body
size, visible or invisible disability, ethnicity, sex characteristics, gender
identity and expression, level of experience, education, socioeconomic status,
nationality, personal appearance, race, religion, or sexual identity
and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming,
diverse, inclusive, and healthy community.
## Our Standards
Examples of behavior that contributes to a positive environment for our
community include:
- Demonstrating empathy and kindness toward other people
- Being respectful of differing opinions, viewpoints, and experiences
- Giving and gracefully accepting constructive feedback
- Accepting responsibility and apologizing to those affected by our mistakes,
and learning from the experience
- Focusing on what is best not just for us as individuals, but for the
overall community
Examples of unacceptable behavior include:
- The use of sexualized language or imagery, and sexual attention or
advances of any kind
- Trolling, insulting or derogatory comments, and personal or political attacks
- Public or private harassment
- Publishing others' private information, such as a physical or email
address, without their explicit permission
- Other conduct which could reasonably be considered inappropriate in a
professional setting
## Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards of
acceptable behavior and will take appropriate and fair corrective action in
response to any behavior that they deem inappropriate, threatening, offensive,
or harmful.
Community leaders have the right and responsibility to remove, edit, or reject
comments, commits, code, wiki edits, issues, and other contributions that are
not aligned to this Code of Conduct, and will communicate reasons for moderation
decisions when appropriate.
## Scope
This Code of Conduct applies within all community spaces, and also applies when
an individual is officially representing the community in public spaces.
Examples of representing our community include using an official e-mail address,
posting via an official social media account, or acting as an appointed
representative at an online or offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported to the community leaders responsible for enforcement at
opensource@reflex.dev.
All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the
reporter of any incident.
## Enforcement Guidelines
Community leaders will follow these Community Impact Guidelines in determining
the consequences for any action they deem in violation of this Code of Conduct:
### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed
unprofessional or unwelcome in the community.
**Consequence**: A private, written warning from community leaders, providing
clarity around the nature of the violation and an explanation of why the
behavior was inappropriate. A public apology may be requested.
### 2. Warning
**Community Impact**: A violation through a single incident or series
of actions.
**Consequence**: A warning with consequences for continued behavior. No
interaction with the people involved, including unsolicited interaction with
those enforcing the Code of Conduct, for a specified period of time. This
includes avoiding interactions in community spaces as well as external channels
like social media. Violating these terms may lead to a temporary or
permanent ban.
### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including
sustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public
communication with the community for a specified period of time. No public or
private interaction with the people involved, including unsolicited interaction
with those enforcing the Code of Conduct, is allowed during this period.
Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community
standards, including sustained inappropriate behavior, harassment of an
individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within
the community as well as any sort of private interaction with the people.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 2.0, available at
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
Community Impact Guidelines were inspired by [Mozilla's code of conduct
enforcement ladder](https://github.com/mozilla/diversity).
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see the FAQ at
https://www.contributor-covenant.org/faq. Translations are available at
https://www.contributor-covenant.org/translations.
## /CONTRIBUTING.md
# Reflex Contributing Guidelines
For an extensive guide on the different ways to contribute to Reflex see our [Contributing Guide on Notion](https://www.notion.so/reflex-dev/2107ab2bc166497db951b8d742748284?v=f0eaff78fa984b5ab15d204af58907d7).
## Running a Local Build of Reflex
Here is a quick guide on how to run Reflex repo locally so you can start contributing to the project.
**Prerequisites:**
- uv version >= 0.6.0 and add it to your path (see [UV Docs](https://docs.astral.sh/uv/getting-started/installation/) for more info).
**1. Fork this repository:**
Fork this repository by clicking on the `Fork` button on the top right.
**2. Clone Reflex and navigate into the repo:**
```bash
git clone https://github.com/<YOUR-USERNAME>/reflex.git
cd reflex
```
**3. Install your local Reflex build:**
```bash
uv sync
```
**4. Now create an examples folder so you can test the local Python build in this repository.**
- We have the `examples` folder in the `.gitignore`, so your changes in `reflex/examples` won't be reflected in your commit.
```bash
mkdir examples
cd examples
```
**5. Init and Run**
```bash
uv run reflex init
uv run reflex run
```
All the changes you make to the repository will be reflected in your running app.
- We have the examples folder in the .gitignore, so your changes in reflex/examples won't be reflected in your commit.
## 🧪 Testing and QA
Any feature or significant change added should be accompanied with unit tests.
Within the 'test' directory of Reflex you can add to a test file already there or create a new test python file if it doesn't fit into the existing layout.
#### What to unit test?
- Any feature or significant change that has been added.
- Any edge cases or potential problem areas.
- Any interactions between different parts of the code.
## ✅ Making a PR
Once you solve a current issue or improvement to Reflex, you can make a PR, and we will review the changes.
Before submitting, a pull request, ensure the following steps are taken and test passing.
In your `reflex` directory run make sure all the unit tests are still passing using the following command.
This will fail if code coverage is below 70%.
```bash
uv run pytest tests/units --cov --no-cov-on-fail --cov-report=
```
Next make sure all the following tests pass. This ensures that every new change has proper documentation and type checking.
```bash
uv run ruff check .
uv run pyright reflex tests
find reflex tests -name "*.py" -not -path reflex/reflex.py | xargs uv run darglint
```
Finally, run `ruff` to format your code.
```bash
uv run ruff format .
```
Consider installing git pre-commit hooks so Ruff, Pyright, Darglint and `make_pyi` will run automatically before each commit.
```bash
uv run pre-commit install
```
That's it you can now submit your PR. Thanks for contributing to Reflex!
## Editing Templates
To edit the templates in Reflex you can do so in two way.
Change to the basic `blank` template can be done in the `reflex/.templates/apps/blank` directory.
Others templates can be edited in their own repository. For example the `sidebar` template can be found in the [`reflex-sidebar`](https://github.com/reflex-dev/sidebar-template) repository.
## Other Notes
For some pull requests when adding new components you will have to generate a pyi file for the new component. This is done by running the following command in the `reflex` directory.
(Please check in with the team before adding a new component to Reflex we are cautious about adding new components to Reflex's core.)
```bash
uv run python -m reflex.utils.pyi_generator
```
## /MCP_README.md
# Reflex MCP Server
The Reflex MCP Server provides comprehensive access to Reflex framework documentation and component information through the Model Context Protocol (MCP). This server is deployed and ready to use with your MCP-compatible AI tools.
Check the documentation at https://reflex.dev/docs/ai-builder/integrations/mcp-overview
## /README.md
<div align="center">
<img src="https://raw.githubusercontent.com/reflex-dev/reflex/main/docs/images/reflex.svg" alt="Reflex Logo" width="300px">
<hr>
### **✨ Performant, customizable web apps in pure Python. Deploy in seconds. ✨**
[](https://badge.fury.io/py/reflex)

[](https://reflex.dev/docs/getting-started/introduction)
[](https://pepy.tech/projects/reflex)
[](https://discord.gg/T5WSbC2YtQ)
[](https://x.com/getreflex)
</div>
---
[English](https://github.com/reflex-dev/reflex/blob/main/README.md) | [简体中文](https://github.com/reflex-dev/reflex/blob/main/docs/zh/zh_cn/README.md) | [繁體中文](https://github.com/reflex-dev/reflex/blob/main/docs/zh/zh_tw/README.md) | [Türkçe](https://github.com/reflex-dev/reflex/blob/main/docs/tr/README.md) | [हिंदी](https://github.com/reflex-dev/reflex/blob/main/docs/in/README.md) | [Português (Brasil)](https://github.com/reflex-dev/reflex/blob/main/docs/pt/pt_br/README.md) | [Italiano](https://github.com/reflex-dev/reflex/blob/main/docs/it/README.md) | [Español](https://github.com/reflex-dev/reflex/blob/main/docs/es/README.md) | [한국어](https://github.com/reflex-dev/reflex/blob/main/docs/kr/README.md) | [日本語](https://github.com/reflex-dev/reflex/blob/main/docs/ja/README.md) | [Deutsch](https://github.com/reflex-dev/reflex/blob/main/docs/de/README.md) | [Persian (پارسی)](https://github.com/reflex-dev/reflex/blob/main/docs/pe/README.md) | [Tiếng Việt](https://github.com/reflex-dev/reflex/blob/main/docs/vi/README.md)
---
> [!NOTE]
> 🚀 **Try [Reflex Build](https://build.reflex.dev/)** – our AI-powered app builder that generates full-stack Reflex applications in seconds.
---
# Introduction
Reflex is a library to build full-stack web apps in pure Python.
Key features:
- **Pure Python** - Write your app's frontend and backend all in Python, no need to learn Javascript.
- **Full Flexibility** - Reflex is easy to get started with, but can also scale to complex apps.
- **Deploy Instantly** - After building, deploy your app with a [single command](https://reflex.dev/docs/hosting/deploy-quick-start/) or host it on your own server.
See our [architecture page](https://reflex.dev/blog/2024-03-21-reflex-architecture/#the-reflex-architecture) to learn how Reflex works under the hood.
## ⚙️ Installation
**Important:** We strongly recommend using a virtual environment to ensure the `reflex` command is available in your PATH.
## 🥳 Create your first app
### 1. Create the project directory
Replace `my_app_name` with your project name:
```bash
mkdir my_app_name
cd my_app_name
```
### 2. Set up a virtual environment
Create and activate virtual environment
```bash
# On Windows:
python -m venv .venv
.venv\Scripts\activate
# On macOS/Linux:
python3 -m venv .venv
source .venv/bin/activate
```
### 3. Install Reflex
Reflex is available as a pip package (Requires Python 3.10+):
```bash
pip install reflex
```
### 4. Initialize the project
This command initializes a template app in your new directory:
```bash
reflex init
```
### 5. Run the app
You can run this app in development mode:
```bash
reflex run
```
You should see your app running at http://localhost:3000.
Now you can modify the source code in `my_app_name/my_app_name.py`. Reflex has fast refreshes so you can see your changes instantly when you save your code.
### Troubleshooting
If you installed Reflex without a virtual environment and the `reflex` command is not found, you can run commands using: `python3 -m reflex init` and `python3 -m reflex run`
## 🫧 Example App
Let's go over an example: creating an image generation UI around [DALL·E](https://platform.openai.com/docs/guides/images/image-generation?context=node). For simplicity, we just call the [OpenAI API](https://platform.openai.com/docs/api-reference/authentication), but you could replace this with an ML model run locally.
<div align="center">
<img src="https://raw.githubusercontent.com/reflex-dev/reflex/main/docs/images/dalle.gif" alt="A frontend wrapper for DALL·E, shown in the process of generating an image." width="550" />
</div>
Here is the complete code to create this. This is all done in one Python file!
```python
import reflex as rx
import openai
openai_client = openai.OpenAI()
class State(rx.State):
"""The app state."""
prompt = ""
image_url = ""
processing = False
complete = False
def get_image(self):
"""Get the image from the prompt."""
if self.prompt == "":
return rx.window_alert("Prompt Empty")
self.processing, self.complete = True, False
yield
response = openai_client.images.generate(
prompt=self.prompt, n=1, size="1024x1024"
)
self.image_url = response.data[0].url
self.processing, self.complete = False, True
def index():
return rx.center(
rx.vstack(
rx.heading("DALL-E", font_size="1.5em"),
rx.input(
placeholder="Enter a prompt..",
on_blur=State.set_prompt,
width="25em",
),
rx.button(
"Generate Image",
on_click=State.get_image,
width="25em",
loading=State.processing
),
rx.cond(
State.complete,
rx.image(src=State.image_url, width="20em"),
),
align="center",
),
width="100%",
height="100vh",
)
# Add state and page to the app.
app = rx.App()
app.add_page(index, title="Reflex:DALL-E")
```
## Let's break this down.
<div align="center">
<img src="https://raw.githubusercontent.com/reflex-dev/reflex/main/docs/images/dalle_colored_code_example.png" alt="Explaining the differences between backend and frontend parts of the DALL-E app." width="900" />
</div>
### **Reflex UI**
Let's start with the UI.
```python
def index():
return rx.center(
...
)
```
This `index` function defines the frontend of the app.
We use different components such as `center`, `vstack`, `input`, and `button` to build the frontend. Components can be nested within each other
to create complex layouts. And you can use keyword args to style them with the full power of CSS.
Reflex comes with [60+ built-in components](https://reflex.dev/docs/library) to help you get started. We are actively adding more components, and it's easy to [create your own components](https://reflex.dev/docs/wrapping-react/overview/).
### **State**
Reflex represents your UI as a function of your state.
```python
class State(rx.State):
"""The app state."""
prompt = ""
image_url = ""
processing = False
complete = False
```
The state defines all the variables (called vars) in an app that can change and the functions that change them.
Here the state is comprised of a `prompt` and `image_url`. There are also the booleans `processing` and `complete` to indicate when to disable the button (during image generation) and when to show the resulting image.
### **Event Handlers**
```python
def get_image(self):
"""Get the image from the prompt."""
if self.prompt == "":
return rx.window_alert("Prompt Empty")
self.processing, self.complete = True, False
yield
response = openai_client.images.generate(
prompt=self.prompt, n=1, size="1024x1024"
)
self.image_url = response.data[0].url
self.processing, self.complete = False, True
```
Within the state, we define functions called event handlers that change the state vars. Event handlers are the way that we can modify the state in Reflex. They can be called in response to user actions, such as clicking a button or typing in a text box. These actions are called events.
Our DALL·E app has an event handler, `get_image` which gets this image from the OpenAI API. Using `yield` in the middle of an event handler will cause the UI to update. Otherwise the UI will update at the end of the event handler.
### **Routing**
Finally, we define our app.
```python
app = rx.App()
```
We add a page from the root of the app to the index component. We also add a title that will show up in the page preview/browser tab.
```python
app.add_page(index, title="DALL-E")
```
You can create a multi-page app by adding more pages.
## 📑 Resources
<div align="center">
📑 [Docs](https://reflex.dev/docs/getting-started/introduction) | 🗞️ [Blog](https://reflex.dev/blog) | 📱 [Component Library](https://reflex.dev/docs/library) | 🖼️ [Templates](https://reflex.dev/templates/) | 🛸 [Deployment](https://reflex.dev/docs/hosting/deploy-quick-start)
</div>
## ✅ Status
Reflex launched in December 2022 with the name Pynecone.
🚀 Introducing [Reflex Build](https://build.reflex.dev/) — Our AI-Powered Builder
Reflex Build uses AI to generate complete full-stack Python applications. It helps you quickly create, customize, and refine your Reflex apps — from frontend components to backend logic — so you can focus on your ideas instead of boilerplate code. Whether you’re prototyping or scaling, Reflex Build accelerates development by intelligently scaffolding and optimizing your app’s entire stack.
Alongside this, [Reflex Cloud](https://cloud.reflex.dev) launched in 2025 to offer the best hosting experience for your Reflex apps. We’re continuously improving the platform with new features and capabilities.
Reflex has new releases and features coming every week! Make sure to :star: star and :eyes: watch this repository to stay up to date.
## Contributing
We welcome contributions of any size! Below are some good ways to get started in the Reflex community.
- **Join Our Discord**: Our [Discord](https://discord.gg/T5WSbC2YtQ) is the best place to get help on your Reflex project and to discuss how you can contribute.
- **GitHub Discussions**: A great way to talk about features you want added or things that are confusing/need clarification.
- **GitHub Issues**: [Issues](https://github.com/reflex-dev/reflex/issues) are an excellent way to report bugs. Additionally, you can try and solve an existing issue and submit a PR.
We are actively looking for contributors, no matter your skill level or experience. To contribute check out [CONTRIBUTING.md](https://github.com/reflex-dev/reflex/blob/main/CONTRIBUTING.md)
## All Thanks To Our Contributors:
<a href="https://github.com/reflex-dev/reflex/graphs/contributors">
<img src="https://contrib.rocks/image?repo=reflex-dev/reflex" />
</a>
## License
Reflex is open-source and licensed under the [Apache License 2.0](https://raw.githubusercontent.com/reflex-dev/reflex/main/LICENSE).
## /SECURITY.md
# Security Policy
## Supported Versions
| Version | Supported |
| -------- | ------------------ |
| >= 0.7.0 | :white_check_mark: |
## Reporting a Vulnerability
Please report any security vulnerabilities by using: https://github.com/reflex-dev/reflex/security/advisories/new
## /docker-example/README.md
# Reflex Docker Examples
This directory contains several examples of how to deploy Reflex apps using docker.
In all cases, ensure that your `requirements.txt` file is up to date and
includes the `reflex` package.
## `simple-two-port`
The most basic production deployment exposes two HTTP ports and relies on an
existing load balancer to forward the traffic appropriately.
## `simple-one-port`
This deployment exports the frontend statically and serves it via a single HTTP
port using Caddy. This is useful for platforms that only support a single port
or where running a node server in the container is undesirable.
## `production-compose`
This deployment is intended for use with a standalone VPS that is only hosting a
single Reflex app. It provides the entire stack in a single `compose.yaml`
including a webserver, one or more backend instances, redis, and a postgres
database.
## `production-app-platform`
This example deployment is intended for use with App hosting platforms, like
Azure, AWS, or Google Cloud Run. It is the backend of the deployment, which
depends on a separately hosted redis instance and static frontend deployment.
## /docker-example/production-app-platform/.dockerignore
```dockerignore path="/docker-example/production-app-platform/.dockerignore"
.web
.git
__pycache__/*
Dockerfile
uploaded_files
```
## /docker-example/production-app-platform/Dockerfile
``` path="/docker-example/production-app-platform/Dockerfile"
# This docker file is intended to be used with container hosting services
#
# After deploying this image, get the URL pointing to the backend service
# and run API_URL=https://path-to-my-container.example.com reflex export frontend
# then copy the contents of `frontend.zip` to your static file server (github pages, s3, etc).
#
# Azure Static Web App example:
# npx @azure/static-web-apps-cli deploy --env production --app-location .web/build/client
#
# For dynamic routes to function properly, ensure that 404s are redirected to /404 on the
# static file host (for github pages, this works out of the box; remember to create .nojekyll).
#
# For azure static web apps, add `staticwebapp.config.json` to to `.web/build/client` with the following:
# {
# "responseOverrides": {
# "404": {
# "rewrite": "/404.html"
# }
# }
# }
#
# Note: many container hosting platforms require amd64 images, so when building on an M1 Mac
# for example, pass `docker build --platform=linux/amd64 ...`
# Stage 1: init
FROM python:3.13 as init
ARG uv=/root/.local/bin/uv
# Install `uv` for faster package bootstrapping
ADD --chmod=755 https://astral.sh/uv/install.sh /install.sh
RUN /install.sh && rm /install.sh
# Copy local context to `/app` inside container (see .dockerignore)
WORKDIR /app
COPY . .
RUN mkdir -p /app/data /app/uploaded_files
# Create virtualenv which will be copied into final container
ENV VIRTUAL_ENV=/app/.venv
ENV PATH="$VIRTUAL_ENV/bin:$PATH"
RUN $uv venv
# Install app requirements and reflex inside virtualenv
RUN $uv pip install -r requirements.txt
# Deploy templates and prepare app
RUN reflex init
# Stage 2: copy artifacts into slim image
FROM python:3.13-slim
WORKDIR /app
RUN adduser --disabled-password --home /app reflex
COPY --chown=reflex --from=init /app /app
# Install libpq-dev for psycopg (skip if not using postgres).
RUN apt-get update -y && apt-get install -y libpq-dev && rm -rf /var/lib/apt/lists/*
USER reflex
ENV PATH="/app/.venv/bin:$PATH" PYTHONUNBUFFERED=1
# Needed until Reflex properly passes SIGTERM on backend.
STOPSIGNAL SIGKILL
# Always apply migrations before starting the backend.
CMD [ -d alembic ] && reflex db migrate; \
exec reflex run --env prod --backend-only --backend-port ${PORT:-8000}
```
## /docker-example/production-app-platform/README.md
# production-app-platform
This example deployment is intended for use with App hosting platforms, like
Azure, AWS, or Google Cloud Run.
## Architecture
The production deployment consists of a few pieces:
- Backend container - built by `Dockerfile` Runs the Reflex backend
service on port 8000 and is scalable to multiple instances.
- Redis container - A single instance the standard `redis` docker image should
share private networking with the backend
- Static frontend - HTML/CSS/JS files that are hosted via a CDN or static file
server. This is not included in the docker image.
## Deployment
These general steps do not cover the specifics of each platform, but all platforms should
support the concepts described here.
### Vnet
All containers in the deployment should be hooked up to the same virtual private
network so they can access the redis service and optionally the database server.
The vnet should not be exposed to the internet, use an ingress rule to terminate
TLS at the load balancer and forward the traffic to a backend service replica.
### Redis
Deploy a `redis` instance on the vnet.
### Backend
The backend is built by the `Dockerfile` in this directory. When deploying the
backend, be sure to set REFLEX_REDIS_URL=redis://internal-redis-hostname to connect to
the redis service.
### Ingress
Configure the load balancer for the app to forward traffic to port 8000 on the
backend service replicas. Most platforms will generate an ingress hostname
automatically. Make sure when you access the ingress endpoint on `/ping` that it
returns "pong", indicating that the backend is up an available.
### Frontend
The frontend should be hosted on a static file server or CDN.
**Important**: when exporting the frontend, set the API_URL environment variable
to the ingress hostname of the backend service.
If you will host the frontend from a path other than the root, set the
`REFLEX_FRONTEND_PATH` environment variable appropriately when exporting the frontend.
Most static hosts will automatically use the `/404.html` file to handle 404
errors. _This is essential for dynamic routes to work correctly._ Ensure that
missing routes return the `/404.html` content to the user if this is not the
default behavior.
_For Github Pages_: ensure the file `.nojekyll` is present in the root of the repo
to avoid special processing of underscore-prefix directories, like `_next`.
## Platform Notes
The following sections are currently a work in progress and may be incomplete.
### Azure
In the Azure load balancer, per-message deflate is not supported. Add the following
to your `rxconfig.py` to workaround this issue.
```python
import uvicorn.workers
import reflex as rx
class NoWSPerMessageDeflate(uvicorn.workers.UvicornH11Worker):
CONFIG_KWARGS = {
**uvicorn.workers.UvicornH11Worker.CONFIG_KWARGS,
"ws_per_message_deflate": False,
}
config = rx.Config(
app_name="my_app",
gunicorn_worker_class="rxconfig.NoWSPerMessageDeflate",
)
```
#### Persistent Storage
If you need to use a database or upload files, you cannot save them to the
container volume. Use Azure Files and mount it into the container at /app/uploaded_files.
#### Resource Types
- Create a new vnet with 10.0.0.0/16
- Create a new subnet for redis, database, and containers
- Deploy redis as a Container Instances
- Deploy database server as "Azure Database for PostgreSQL"
- Create a new database for the app
- Set db-url as a secret containing the db user/password connection string
- Deploy Storage account for uploaded files
- Enable access from the vnet and container subnet
- Create a new file share
- In the environment, create a new files share (get the storage key)
- Deploy the backend as a Container App
- Create a custom Container App Environment linked up to the same vnet as the redis container.
- Set REFLEX_REDIS_URL and REFLEX_DB_URL environment variables
- Add the volume from the environment
- Add the volume mount to the container
- Deploy the frontend as a Static Web App
## /docker-example/production-compose/.dockerignore
```dockerignore path="/docker-example/production-compose/.dockerignore"
.web
.git
__pycache__/*
Dockerfile
Caddy.Dockerfile
compose.yaml
compose.*.yaml
uploaded_files
```
## /docker-example/production-compose/Caddy.Dockerfile
```Dockerfile path="/docker-example/production-compose/Caddy.Dockerfile"
FROM library/caddy
COPY --from=local/reflex-app /app/.web/build/client /srv
ADD Caddyfile /etc/caddy/Caddyfile
```
## /docker-example/production-compose/Caddyfile
``` path="/docker-example/production-compose/Caddyfile"
{$DOMAIN}
encode gzip
@backend_routes path /_event/* /ping /_upload /_upload/*
handle @backend_routes {
reverse_proxy app:8000
}
root * /srv
route {
try_files {path} {path}/ /404.html
file_server
}
```
## /docker-example/production-compose/Dockerfile
``` path="/docker-example/production-compose/Dockerfile"
# This docker file is intended to be used with docker compose to deploy a production
# instance of a Reflex app.
# Stage 1: init
FROM python:3.13 as init
ARG uv=/root/.local/bin/uv
# Install `uv` for faster package bootstrapping
ADD --chmod=755 https://astral.sh/uv/install.sh /install.sh
RUN /install.sh && rm /install.sh
# Copy local context to `/app` inside container (see .dockerignore)
WORKDIR /app
COPY . .
RUN mkdir -p /app/data /app/uploaded_files
# Create virtualenv which will be copied into final container
ENV VIRTUAL_ENV=/app/.venv
ENV PATH="$VIRTUAL_ENV/bin:$PATH"
RUN $uv venv
# Install app requirements and reflex inside virtualenv
RUN $uv pip install -r requirements.txt
# Deploy templates and prepare app
RUN reflex init
# Export static copy of frontend to /app/.web/build/client
RUN reflex export --frontend-only --no-zip
# Copy static files out of /app to save space in backend image
RUN mv .web/build/client /tmp/client
RUN rm -rf .web && mkdir -p .web/build
RUN mv /tmp/client .web/build/client
# Stage 2: copy artifacts into slim image
FROM python:3.13-slim
WORKDIR /app
RUN adduser --disabled-password --home /app reflex
COPY --chown=reflex --from=init /app /app
# Install libpq-dev for psycopg (skip if not using postgres).
RUN apt-get update -y && apt-get install -y libpq-dev && rm -rf /var/lib/apt/lists/*
USER reflex
ENV PATH="/app/.venv/bin:$PATH" PYTHONUNBUFFERED=1
# Needed until Reflex properly passes SIGTERM on backend.
STOPSIGNAL SIGKILL
# Always apply migrations before starting the backend.
CMD [ -d alembic ] && reflex db migrate; \
exec reflex run --env prod --backend-only
```
## /docker-example/production-compose/README.md
# production-compose
This example production deployment uses automatic TLS with Caddy serving static
files for the frontend and proxying requests to both the frontend and backend.
It is intended for use with a standalone VPS that is only hosting a single
Reflex app.
The production app container (`Dockerfile`), builds and exports the frontend
statically (to be served by Caddy). The resulting image only runs the backend
service.
The `webserver` service, based on `Caddy.Dockerfile`, copies the static frontend
and `Caddyfile` into the container to configure the reverse proxy routes that will
forward requests to the backend service. Caddy will automatically provision TLS
for localhost or the domain specified in the environment variable `DOMAIN`.
This type of deployment should use less memory and be more performant since
nodejs is not required at runtime.
## Customize `Caddyfile` (optional)
If the app uses additional backend API routes, those should be added to the
`@backend_routes` path matcher to ensure they are forwarded to the backend.
## Build Reflex Production Service
During build, set `DOMAIN` environment variable to the domain where the app will
be hosted! (Do not include http or https, it will always use https).
**If `DOMAIN` is not provided, the service will default to `localhost`.**
```bash
DOMAIN=example.com docker compose build
```
This will build both the `app` service from the `prod.Dockerfile` and the `webserver`
service via `Caddy.Dockerfile`.
## Run Reflex Production Service
```bash
DOMAIN=example.com docker compose up
```
The app should be available at the specified domain via HTTPS. Certificate
provisioning will occur automatically and may take a few minutes.
### Data Persistence
Named docker volumes are used to persist the app database (`db-data`),
uploaded_files (`upload-data`), and caddy TLS keys and certificates
(`caddy-data`).
## More Robust Deployment
For a more robust deployment, consider bringing the service up with
`compose.prod.yaml` which includes postgres database and redis cache, allowing
the backend to run with multiple workers and service more requests.
```bash
DOMAIN=example.com docker compose -f compose.yaml -f compose.prod.yaml up -d
```
Postgres uses its own named docker volume for data persistence.
## Admin Tools
When needed, the services in `compose.tools.yaml` can be brought up, providing
graphical database administration (Adminer on http://localhost:8080) and a
redis cache browser (redis-commander on http://localhost:8081). It is not recommended
to deploy these services if they are not in active use.
```bash
DOMAIN=example.com docker compose -f compose.yaml -f compose.prod.yaml -f compose.tools.yaml up -d
```
## /docker-example/production-compose/compose.prod.yaml
```yaml path="/docker-example/production-compose/compose.prod.yaml"
# Use this override file to run the app in prod mode with postgres and redis
# docker compose -f compose.yaml -f compose.prod.yaml up -d
services:
db:
image: postgres
restart: always
environment:
POSTGRES_PASSWORD: secret
volumes:
- postgres-data:/var/lib/postgresql/data
redis:
image: redis
restart: always
app:
environment:
REFLEX_DB_URL: postgresql+psycopg://postgres:secret@db/postgres
REFLEX_REDIS_URL: redis://redis:6379
depends_on:
- db
- redis
volumes:
postgres-data:
```
## /docker-example/production-compose/compose.tools.yaml
```yaml path="/docker-example/production-compose/compose.tools.yaml"
# Use this override file with `compose.prod.yaml` to run admin tools
# for production services.
# docker compose -f compose.yaml -f compose.prod.yaml -f compose.tools.yaml up -d
services:
adminer:
image: adminer
ports:
- 8080:8080
redis-commander:
image: ghcr.io/joeferner/redis-commander:latest
environment:
- REDIS_HOSTS=local:redis:6379
ports:
- "8081:8081"
volumes:
redis-ui-settings:
```
## /docker-example/production-compose/compose.yaml
```yaml path="/docker-example/production-compose/compose.yaml"
# Base compose file production deployment of reflex app with Caddy webserver
# providing TLS termination and reverse proxying.
#
# See `compose.prod.yaml` for more robust and performant deployment option.
#
# During build and run, set environment DOMAIN pointing
# to publicly accessible domain where app will be hosted
services:
app:
image: local/reflex-app
environment:
REFLEX_DB_URL: sqlite:///data/reflex.db
build:
context: .
volumes:
- db-data:/app/data
- upload-data:/app/uploaded_files
restart: always
webserver:
environment:
DOMAIN: ${DOMAIN:-localhost}
ports:
- 443:443
- 80:80 # For acme-challenge via HTTP.
build:
context: .
dockerfile: Caddy.Dockerfile
volumes:
- caddy-data:/root/.caddy
restart: always
depends_on:
- app
volumes:
# SQLite data
db-data:
# Uploaded files
upload-data:
# TLS keys and certificates
caddy-data:
```
## /docker-example/production-one-port/.dockerignore
```dockerignore path="/docker-example/production-one-port/.dockerignore"
.web
!.web/bun.lockb
!.web/package.json
```
## /docker-example/production-one-port/Caddyfile
``` path="/docker-example/production-one-port/Caddyfile"
:{$PORT}
encode gzip
@backend_routes path /_event/* /ping /_upload /_upload/*
handle @backend_routes {
reverse_proxy localhost:8000
}
root * /srv
route {
try_files {path} {path}/ /404.html
file_server
}
```
## /docker-example/production-one-port/Dockerfile
``` path="/docker-example/production-one-port/Dockerfile"
# This Dockerfile is used to deploy a single-container Reflex app instance
# to services like Render, Railway, Heroku, GCP, and others.
# If the service expects a different port, provide it here (f.e Render expects port 10000)
ARG PORT=8080
# Only set for local/direct access. When TLS is used, the API_URL is assumed to be the same as the frontend.
ARG API_URL
# It uses a reverse proxy to serve the frontend statically and proxy to backend
# from a single exposed port, expecting TLS termination to be handled at the
# edge by the given platform.
FROM python:3.13 as builder
RUN mkdir -p /app/.web
RUN python -m venv /app/.venv
ENV PATH="/app/.venv/bin:$PATH"
WORKDIR /app
# Install python app requirements and reflex in the container
COPY requirements.txt .
RUN pip install -r requirements.txt
# Install reflex helper utilities like bun/node
COPY rxconfig.py ./
RUN reflex init
# Install pre-cached frontend dependencies (if exist)
COPY *.web/bun.lockb *.web/package.json .web/
RUN if [ -f .web/bun.lockb ]; then cd .web && ~/.local/share/reflex/bun/bin/bun install --frozen-lockfile; fi
# Copy local context to `/app` inside container (see .dockerignore)
COPY . .
ARG PORT API_URL
# Download other npm dependencies and compile frontend
RUN REFLEX_API_URL=${API_URL:-http://localhost:$PORT} reflex export --loglevel debug --frontend-only --no-zip && mv .web/build/client/* /srv/ && rm -rf .web
# Final image with only necessary files
FROM python:3.13-slim
# Install Caddy and redis server inside image
RUN apt-get update -y && apt-get install -y caddy redis-server && rm -rf /var/lib/apt/lists/*
ARG PORT API_URL
ENV PATH="/app/.venv/bin:$PATH" PORT=$PORT REFLEX_API_URL=${API_URL:-http://localhost:$PORT} REFLEX_REDIS_URL=redis://localhost PYTHONUNBUFFERED=1
WORKDIR /app
COPY --from=builder /app /app
COPY --from=builder /srv /srv
# Needed until Reflex properly passes SIGTERM on backend.
STOPSIGNAL SIGKILL
EXPOSE $PORT
# Apply migrations before starting the backend.
CMD [ -d alembic ] && reflex db migrate; \
caddy start && \
redis-server --daemonize yes && \
exec reflex run --env prod --backend-only
```
## /docker-example/production-one-port/README.md
# production-one-port
This docker deployment runs Reflex in prod mode, exposing a single HTTP port:
- `8080` (`$PORT`) - Caddy server hosting the frontend statically and proxying requests to the backend.
The deployment also runs a local Redis server to store state for each user.
Conceptually it is similar to the `simple-one-port` example except it:
- has layer caching for python, reflex, and node dependencies
- uses multi-stage build to reduce the size of the final image
Using this method may be preferable for deploying in memory constrained
environments, because it serves a static frontend export, rather than running
the Vite server via node.
## Build
```console
docker build -t reflex-production-one-port .
```
## Run
```console
docker run -p 8080:8080 reflex-production-one-port
```
Note that this container has _no persistence_ and will lose all data when
stopped. You can use bind mounts or named volumes to persist the database and
uploaded_files directories as needed.
## Usage
This container should be used with an existing load balancer or reverse proxy to
terminate TLS.
It is also useful for deploying to simple app platforms, such as Render or Heroku.
## /docker-example/simple-one-port/.dockerignore
```dockerignore path="/docker-example/simple-one-port/.dockerignore"
.web
.git
__pycache__/*
Dockerfile
uploaded_files
```
## /docker-example/simple-one-port/Caddyfile
``` path="/docker-example/simple-one-port/Caddyfile"
:{$PORT}
encode gzip
@backend_routes path /_event/* /ping /_upload /_upload/*
handle @backend_routes {
reverse_proxy localhost:8000
}
root * /srv
route {
try_files {path} {path}/ /404.html
file_server
}
```
## /docker-example/simple-one-port/Dockerfile
``` path="/docker-example/simple-one-port/Dockerfile"
# This Dockerfile is used to deploy a single-container Reflex app instance
# to services like Render, Railway, Heroku, GCP, and others.
# It uses a reverse proxy to serve the frontend statically and proxy to backend
# from a single exposed port, expecting TLS termination to be handled at the
# edge by the given platform.
FROM python:3.13
# If the service expects a different port, provide it here (f.e Render expects port 10000)
ARG PORT=8080
# Only set for local/direct access. When TLS is used, the API_URL is assumed to be the same as the frontend.
ARG API_URL
ENV PORT=$PORT REFLEX_API_URL=${API_URL:-http://localhost:$PORT} REFLEX_REDIS_URL=redis://localhost PYTHONUNBUFFERED=1
# Install Caddy and redis server inside image
RUN apt-get update -y && apt-get install -y caddy redis-server && rm -rf /var/lib/apt/lists/*
WORKDIR /app
# Copy local context to `/app` inside container (see .dockerignore)
COPY . .
# Install app requirements and reflex in the container
RUN pip install -r requirements.txt
# Deploy templates and prepare app
RUN reflex init
# Download all npm dependencies and compile frontend
RUN reflex export --frontend-only --no-zip && mv .web/build/client/* /srv/ && rm -rf .web
# Needed until Reflex properly passes SIGTERM on backend.
STOPSIGNAL SIGKILL
EXPOSE $PORT
# Apply migrations before starting the backend.
CMD [ -d alembic ] && reflex db migrate; \
caddy start && \
redis-server --daemonize yes && \
exec reflex run --env prod --backend-only
```
## /docker-example/simple-one-port/README.md
# simple-one-port
This docker deployment runs Reflex in prod mode, exposing a single HTTP port:
- `8080` (`$PORT`) - Caddy server hosting the frontend statically and proxying requests to the backend.
The deployment also runs a local Redis server to store state for each user.
Using this method may be preferable for deploying in memory constrained
environments, because it serves a static frontend export, rather than running
the Vite server via node.
For platforms which only terminate TLS to a single port, this container can be
deployed instead of the `simple-two-port` example.
## Build
```console
docker build -t reflex-simple-one-port .
```
## Run
```console
docker run -p 8080:8080 reflex-simple-one-port
```
Note that this container has _no persistence_ and will lose all data when
stopped. You can use bind mounts or named volumes to persist the database and
uploaded_files directories as needed.
## Usage
This container should be used with an existing load balancer or reverse proxy to
terminate TLS.
It is also useful for deploying to simple app platforms, such as Render or Heroku.
## /docker-example/simple-two-port/.dockerignore
```dockerignore path="/docker-example/simple-two-port/.dockerignore"
.web
.git
__pycache__/*
Dockerfile
uploaded_files
```
## /docker-example/simple-two-port/Dockerfile
``` path="/docker-example/simple-two-port/Dockerfile"
# This Dockerfile is used to deploy a simple single-container Reflex app instance.
FROM python:3.13
RUN apt-get update && apt-get install -y redis-server && rm -rf /var/lib/apt/lists/*
ENV REFLEX_REDIS_URL=redis://localhost PYTHONUNBUFFERED=1
# Copy local context to `/app` inside container (see .dockerignore)
WORKDIR /app
COPY . .
# Install app requirements and reflex in the container
RUN pip install -r requirements.txt
# Deploy templates and prepare app
RUN reflex init
# Download all npm dependencies and compile frontend
RUN reflex export --frontend-only --no-zip
# Needed until Reflex properly passes SIGTERM on backend.
STOPSIGNAL SIGKILL
# Always apply migrations before starting the backend.
CMD [ -d alembic ] && reflex db migrate; \
redis-server --daemonize yes && \
exec reflex run --env prod
```
## /docker-example/simple-two-port/README.md
# simple-two-port
This docker deployment runs Reflex in prod mode, exposing two HTTP ports:
- `3000` - node server using optimized production build
- `8000` - python gunicorn server hosting the Reflex backend
The deployment also runs a local Redis server to store state for each user.
## Build
```console
docker build -t reflex-simple-two-port .
```
## Run
```console
docker run -p 3000:3000 -p 8000:8000 reflex-simple-two-port
```
Note that this container has _no persistence_ and will lose all data when
stopped. You can use bind mounts or named volumes to persist the database and
uploaded_files directories as needed.
## Usage
This container should be used with an existing load balancer or reverse proxy to
route traffic to the appropriate port inside the container.
For example, the following Caddyfile can be used to terminate TLS and forward
traffic to the frontend and backend from outside the container.
```
my-domain.com
encode gzip
@backend_routes path /_event/* /ping /_upload /_upload/*
handle @backend_routes {
reverse_proxy localhost:8000
}
reverse_proxy localhost:3000
```
## /docs/DEBUGGING.md
# Debugging
It is possible to run Reflex apps in dev mode under a debugger.
1. Run Reflex as a module: `python -m reflex run --env dev`
2. Set current working directory to the dir containing `rxconfig.py`
## VSCode
The following launch configuration can be used to interactively debug a Reflex
app with breakpoints.
```json
{
"version": "0.2.0",
"configurations": [
{
"name": "Reflex App",
"type": "python",
"request": "launch",
"module": "reflex",
"args": "run --env dev",
"justMyCode": true,
"cwd": "${fileDirname}/.."
}
]
}
```
## /docs/de/README.md
<div align="center">
<img src="/docs/images/reflex.svg" alt="Reflex Logo" width="300px">
<hr>
### **✨ Performante, anpassbare Web-Apps in purem Python. Bereitstellung in Sekunden. ✨**
[](https://badge.fury.io/py/reflex)

[](https://reflex.dev/docs/getting-started/introduction)
[](https://pepy.tech/projects/reflex)
[](https://discord.gg/T5WSbC2YtQ)
</div>
---
[English](https://github.com/reflex-dev/reflex/blob/main/README.md) | [简体中文](https://github.com/reflex-dev/reflex/blob/main/docs/zh/zh_cn/README.md) | [繁體中文](https://github.com/reflex-dev/reflex/blob/main/docs/zh/zh_tw/README.md) | [Türkçe](https://github.com/reflex-dev/reflex/blob/main/docs/tr/README.md) | [हिंदी](https://github.com/reflex-dev/reflex/blob/main/docs/in/README.md) | [Português (Brasil)](https://github.com/reflex-dev/reflex/blob/main/docs/pt/pt_br/README.md) | [Italiano](https://github.com/reflex-dev/reflex/blob/main/docs/it/README.md) | [Español](https://github.com/reflex-dev/reflex/blob/main/docs/es/README.md) | [한국어](https://github.com/reflex-dev/reflex/blob/main/docs/kr/README.md) | [日本語](https://github.com/reflex-dev/reflex/blob/main/docs/ja/README.md) | [Deutsch](https://github.com/reflex-dev/reflex/blob/main/docs/de/README.md) | [Persian (پارسی)](https://github.com/reflex-dev/reflex/blob/main/docs/pe/README.md) | [Tiếng Việt](https://github.com/reflex-dev/reflex/blob/main/docs/vi/README.md)
---
# Reflex
Reflex ist eine Bibliothek, mit der man Full-Stack-Web-Applikationen in purem Python erstellen kann.
Wesentliche Merkmale:
- **Pures Python** - Schreibe dein Front- und Backend in Python, es gibt also keinen Grund, JavaScript zu lernen.
- **Volle Flexibilität** - Reflex ist einfach zu handhaben, kann aber auch für komplexe Anwendungen skaliert werden.
- **Sofortige Bereitstellung** - Nach dem Erstellen kannst du deine App mit einem [einzigen Befehl](https://reflex.dev/docs/hosting/deploy-quick-start/) bereitstellen oder auf deinem eigenen Server hosten.
Auf unserer [Architektur-Seite](https://reflex.dev/blog/2024-03-21-reflex-architecture/#the-reflex-architecture) erfahren Sie, wie Reflex unter der Haube funktioniert.
## ⚙️ Installation
Öffne ein Terminal und führe den folgenden Befehl aus (benötigt Python 3.10+):
```bash
pip install reflex
```
## 🥳 Erstelle deine erste App
Die Installation von `reflex` installiert auch das `reflex`-Kommandozeilen-Tool.
Teste, ob die Installation erfolgreich war, indem du ein neues Projekt erstellst. (Ersetze `my_app_name` durch deinen Projektnamen):
```bash
mkdir my_app_name
cd my_app_name
reflex init
```
Dieser Befehl initialisiert eine Vorlage in deinem neuen Verzeichnis.
Du kannst diese App im Entwicklungsmodus ausführen:
```bash
reflex run
```
Du solltest deine App unter http://localhost:3000 laufen sehen.
Nun kannst du den Quellcode in `my_app_name/my_app_name.py` ändern. Reflex hat schnelle Aktualisierungen, sodass du deine Änderungen sofort siehst, wenn du deinen Code speicherst.
## 🫧 Beispiel-App
Lass uns ein Beispiel durchgehen: die Erstellung einer Benutzeroberfläche für die Bildgenerierung mit [DALL·E](https://platform.openai.com/docs/guides/images/image-generation?context=node). Zur Vereinfachung rufen wir einfach die [OpenAI-API](https://platform.openai.com/docs/api-reference/authentication) auf, aber du könntest dies auch durch ein lokal ausgeführtes ML-Modell ersetzen.
<div align="center">
<img src="/docs/images/dalle.gif" alt="Eine Benutzeroberfläche für DALL·E, die im Prozess der Bildgenerierung gezeigt wird." width="550" />
</div>
Hier ist der komplette Code, um dies zu erstellen. Das alles wird in einer Python-Datei gemacht!
```python
import reflex as rx
import openai
openai_client = openai.OpenAI()
class State(rx.State):
"""Der Zustand der App."""
prompt = ""
image_url = ""
processing = False
complete = False
def get_image(self):
"""Hole das Bild aus dem Prompt."""
if self.prompt == "":
return rx.window_alert("Prompt Empty")
self.processing, self.complete = True, False
yield
response = openai_client.images.generate(
prompt=self.prompt, n=1, size="1024x1024"
)
self.image_url = response.data[0].url
self.processing, self.complete = False, True
def index():
return rx.center(
rx.vstack(
rx.heading("DALL-E", font_size="1.5em"),
rx.input(
placeholder="Enter a prompt..",
on_blur=State.set_prompt,
width="25em",
),
rx.button(
"Generate Image",
on_click=State.get_image,
width="25em",
loading=State.processing
),
rx.cond(
State.complete,
rx.image(src=State.image_url, width="20em"),
),
align="center",
),
width="100%",
height="100vh",
)
# Füge Zustand und Seite zur App hinzu.
app = rx.App()
app.add_page(index, title="Reflex:DALL-E")
```
## Schauen wir uns das mal genauer an.
<div align="center">
<img src="/docs/images/dalle_colored_code_example.png" alt="Erläuterung der Unterschiede zwischen Backend- und Frontend-Teilen der DALL-E-App." width="900" />
</div>
### **Reflex-UI**
Fangen wir mit der Benutzeroberfläche an.
```python
def index():
return rx.center(
...
)
```
Diese `index`-Funktion definiert das Frontend der App.
Wir verwenden verschiedene Komponenten wie `center`, `vstack`, `input` und `button`, um das Frontend zu erstellen. Komponenten können ineinander verschachtelt werden, um komplexe Layouts zu erstellen. Und du kannst Schlüsselwortargumente verwenden, um sie mit der vollen Kraft von CSS zu stylen.
Reflex wird mit [über 60 eingebauten Komponenten](https://reflex.dev/docs/library) geliefert, die dir den Einstieg erleichtern. Wir fügen aktiv weitere Komponenten hinzu, und es ist einfach, [eigene Komponenten zu erstellen](https://reflex.dev/docs/wrapping-react/overview/).
### **State**
Reflex stellt deine Benutzeroberfläche als Funktion deines Zustands dar.
```python
class State(rx.State):
"""Der Zustand der App."""
prompt = ""
image_url = ""
processing = False
complete = False
```
Der Zustand definiert alle Variablen (genannt Vars) in einer App, die sich ändern können, und die Funktionen, die sie ändern.
Hier besteht der Zustand aus einem `prompt` und einer `image_url`. Es gibt auch die Booleans `processing` und `complete`, um anzuzeigen, wann der Button deaktiviert werden soll (während der Bildgenerierung) und wann das resultierende Bild angezeigt werden soll.
### **Event-Handler**
```python
def get_image(self):
"""Hole das Bild aus dem Prompt."""
if self.prompt == "":
return rx.window_alert("Prompt Empty")
self.processing, self.complete = True, False
yield
response = openai_client.images.generate(
prompt=self.prompt, n=1, size="1024x1024"
)
self.image_url = response.data[0].url
self.processing, self.complete = False, True
```
Innerhalb des Zustands definieren wir Funktionen, die als Event-Handler bezeichnet werden und die Zustand-Variablen ändern. Event-Handler sind die Art und Weise, wie wir den Zustand in Reflex ändern können. Sie können als Reaktion auf Benutzeraktionen aufgerufen werden, z.B. beim Klicken auf eine Schaltfläche oder bei der Eingabe in ein Textfeld. Diese Aktionen werden als Ereignisse bezeichnet.
Unsere DALL-E.-App hat einen Event-Handler, `get_image`, der dieses Bild von der OpenAI-API abruft. Die Verwendung von `yield` in der Mitte eines Event-Handlers führt zu einer Aktualisierung der Benutzeroberfläche. Andernfalls wird die Benutzeroberfläche am Ende des Ereignishandlers aktualisiert.
### **Routing**
Schließlich definieren wir unsere App.
```python
app = rx.App()
```
Wir fügen der Indexkomponente eine Seite aus dem Stammverzeichnis der Anwendung hinzu. Wir fügen auch einen Titel hinzu, der in der Seitenvorschau/Browser-Registerkarte angezeigt wird.
```python
app.add_page(index, title="DALL-E")
```
Du kannst eine mehrseitige App erstellen, indem du weitere Seiten hinzufügst.
## 📑 Ressourcen
<div align="center">
📑 [Docs](https://reflex.dev/docs/getting-started/introduction) | 🗞️ [Blog](https://reflex.dev/blog) | 📱 [Komponentenbibliothek](https://reflex.dev/docs/library) | 🖼️ [Templates](https://reflex.dev/templates/) | 🛸 [Bereitstellung](https://reflex.dev/docs/hosting/deploy-quick-start)
</div>
## ✅ Status
Reflex wurde im Dezember 2022 unter dem Namen Pynecone gestartet.
Ab 2025 wurde [Reflex Cloud](https://cloud.reflex.dev) gestartet, um die beste Hosting-Erfahrung für Reflex-Apps zu bieten. Wir werden es weiterhin entwickeln und mehr Funktionen implementieren.
Reflex hat wöchentliche Veröffentlichungen und neue Features! Stelle sicher, dass du dieses Repository mit einem :star: Stern markierst und :eyes: beobachtest, um auf dem Laufenden zu bleiben.
## Beitragende
Wir begrüßen Beiträge jeder Größe! Hier sind einige gute Möglichkeiten, um in der Reflex-Community zu starten.
- **Tritt unserem Discord bei**: Unser [Discord](https://discord.gg/T5WSbC2YtQ) ist der beste Ort, um Hilfe für dein Reflex-Projekt zu bekommen und zu besprechen, wie du beitragen kannst.
- **GitHub-Diskussionen**: Eine großartige Möglichkeit, über Funktionen zu sprechen, die du hinzugefügt haben möchtest oder Dinge, die verwirrend sind/geklärt werden müssen.
- **GitHub-Issues**: [Issues](https://github.com/reflex-dev/reflex/issues) sind eine ausgezeichnete Möglichkeit, Bugs zu melden. Außerdem kannst du versuchen, ein bestehendes Problem zu lösen und eine PR einzureichen.
Wir suchen aktiv nach Mitwirkenden, unabhängig von deinem Erfahrungslevel oder deiner Erfahrung. Um beizutragen, sieh dir [CONTRIBUTING.md](https://github.com/reflex-dev/reflex/blob/main/CONTRIBUTING.md) an.
## Vielen Dank an unsere Mitwirkenden:
<a href="https://github.com/reflex-dev/reflex/graphs/contributors">
<img src="https://contrib.rocks/image?repo=reflex-dev/reflex" />
</a>
## Lizenz
Reflex ist Open-Source und lizenziert unter der [Apache License 2.0](/LICENSE).
## /docs/es/README.md
<div align="center">
<img src="/docs/images/reflex.svg" alt="Reflex Logo" width="300px">
<hr>
### **✨ Aplicaciones web personalizables y eficaces en Python puro. Despliega tu aplicación en segundos. ✨**
[](https://badge.fury.io/py/reflex)

[](https://reflex.dev/docs/getting-started/introduction)
[](https://pepy.tech/projects/reflex)
[](https://discord.gg/T5WSbC2YtQ)
</div>
---
[English](https://github.com/reflex-dev/reflex/blob/main/README.md) | [简体中文](https://github.com/reflex-dev/reflex/blob/main/docs/zh/zh_cn/README.md) | [繁體中文](https://github.com/reflex-dev/reflex/blob/main/docs/zh/zh_tw/README.md) | [Türkçe](https://github.com/reflex-dev/reflex/blob/main/docs/tr/README.md) | [हिंदी](https://github.com/reflex-dev/reflex/blob/main/docs/in/README.md) | [Português (Brasil)](https://github.com/reflex-dev/reflex/blob/main/docs/pt/pt_br/README.md) | [Italiano](https://github.com/reflex-dev/reflex/blob/main/docs/it/README.md) | [Español](https://github.com/reflex-dev/reflex/blob/main/docs/es/README.md) | [한국어](https://github.com/reflex-dev/reflex/blob/main/docs/kr/README.md) | [日本語](https://github.com/reflex-dev/reflex/blob/main/docs/ja/README.md) | [Deutsch](https://github.com/reflex-dev/reflex/blob/main/docs/de/README.md) | [Persian (پارسی)](https://github.com/reflex-dev/reflex/blob/main/docs/pe/README.md) | [Tiếng Việt](https://github.com/reflex-dev/reflex/blob/main/docs/vi/README.md)
---
# Reflex
Reflex es una biblioteca para construir aplicaciones web full-stack en Python puro.
Características clave:
- **Python puro** - Escribe el frontend y backend de tu aplicación en Python, sin necesidad de aprender JavaScript.
- **Flexibilidad total** - Reflex es fácil para empezar, pero también puede escalar a aplicaciones complejas.
- **Despliegue instantáneo** - Después de construir, despliega tu aplicación con un [solo comando](https://reflex.dev/docs/hosting/deploy-quick-start/) u hospédala en tu propio servidor.
Consulta nuestra [página de arquitectura](https://reflex.dev/blog/2024-03-21-reflex-architecture/#the-reflex-architecture) para aprender cómo funciona Reflex en detalle.
## ⚙️ Instalación
Abra un terminal y ejecute (Requiere Python 3.10+):
```bash
pip install reflex
```
## 🥳 Crea tu primera aplicación
Al instalar `reflex` también se instala la herramienta de línea de comandos `reflex`.
Compruebe que la instalación se ha realizado correctamente creando un nuevo proyecto. (Sustituye `my_app_name` por el nombre de tu proyecto):
```bash
mkdir my_app_name
cd my_app_name
reflex init
```
Este comando inicializa una plantilla en tu nuevo directorio.
Puedes iniciar esta aplicación en modo de desarrollo:
```bash
reflex run
```
Debería ver su aplicación ejecutándose en http://localhost:3000.
Ahora puede modificar el código fuente en `my_app_name/my_app_name.py`. Reflex se actualiza rápidamente para que pueda ver los cambios al instante cuando guarde el código.
## 🫧 Ejemplo de una Aplicación
Veamos un ejemplo: crearemos una UI de generación de imágenes en torno a [DALL·E](https://platform.openai.com/docs/guides/images/image-generation?context=node). Para simplificar, solo llamamos a la [API de OpenAI](https://platform.openai.com/docs/api-reference/authentication), pero podrías reemplazar esto con un modelo ML ejecutado localmente.
<div align="center">
<img src="/docs/images/dalle.gif" alt="Un envoltorio frontend para DALL·E, mostrado en el proceso de generar una imagen." width="550" />
</div>
Aquí está el código completo para crear esto. ¡Todo esto se hace en un archivo de Python!
```python
import reflex as rx
import openai
openai_client = openai.OpenAI()
class State(rx.State):
"""El estado de la aplicación"""
prompt = ""
image_url = ""
processing = False
complete = False
def get_image(self):
"""Obtiene la imagen desde la consulta."""
if self.prompt == "":
return rx.window_alert("Prompt Empty")
self.processing, self.complete = True, False
yield
response = openai_client.images.generate(
prompt=self.prompt, n=1, size="1024x1024"
)
self.image_url = response.data[0].url
self.processing, self.complete = False, True
def index():
return rx.center(
rx.vstack(
rx.heading("DALL-E", font_size="1.5em"),
rx.input(
placeholder="Enter a prompt..",
on_blur=State.set_prompt,
width="25em",
),
rx.button(
"Generate Image",
on_click=State.get_image,
width="25em",
loading=State.processing
),
rx.cond(
State.complete,
rx.image(src=State.image_url, width="20em"),
),
align="center",
),
width="100%",
height="100vh",
)
# Agrega el estado y la pagina a la aplicación
app = rx.App()
app.add_page(index, title="Reflex:DALL-E")
```
## Vamos a analizarlo.
<div align="center">
<img src="/docs/images/dalle_colored_code_example.png" alt="Explicando las diferencias entre las partes del backend y frontend de la aplicación DALL-E." width="900" />
</div>
### **Reflex UI**
Empezemos por la interfaz de usuario (UI).
```python
def index():
return rx.center(
...
)
```
Esta función `index` define el frontend de la aplicación.
Utilizamos diferentes componentes como `center`, `vstack`, `input`, y `button` para construir el frontend. Los componentes pueden anidarse unos dentro de otros para crear diseños complejos. Además, puedes usar argumentos de tipo keyword para darles estilo con toda la potencia de CSS.
Reflex viene con [mas de 60 componentes incorporados](https://reflex.dev/docs/library) para ayudarle a empezar. Estamos añadiendo activamente más componentes y es fácil [crear sus propios componentes](https://reflex.dev/docs/wrapping-react/overview/).
### **Estado**
Reflex representa su UI como una función de su estado (State).
```python
class State(rx.State):
"""El estado de la aplicación"""
prompt = ""
image_url = ""
processing = False
complete = False
```
El estado (State) define todas las variables (llamadas vars) de una aplicación que pueden cambiar y las funciones que las modifican.
Aquí el estado se compone de `prompt` e `image_url`. También están los booleanos `processing` y `complete` para indicar cuando se deshabilite el botón (durante la generación de la imagen) y cuando se muestre la imagen resultante.
### **Manejadores de Evento**
```python
def get_image(self):
"""Obtiene la imagen desde la consulta."""
if self.prompt == "":
return rx.window_alert("Prompt Empty")
self.processing, self.complete = True, False
yield
response = openai_client.images.generate(
prompt=self.prompt, n=1, size="1024x1024"
)
self.image_url = response.data[0].url
self.processing, self.complete = False, True
```
Dentro del estado, definimos funciones llamadas manejadores de eventos que cambian las variables de estado. Los Manejadores de Evento son la manera que podemos modificar el estado en Reflex. Pueden ser activados en respuesta a las acciones del usuario, como hacer clic en un botón o escribir en un cuadro de texto. Estas acciones se llaman eventos.
Nuestra aplicación DALL·E tiene un manipulador de eventos, `get_image` que recibe esta imagen del OpenAI API. El uso de `yield` en medio de un manipulador de eventos hará que la UI se actualice. De lo contrario, la interfaz se actualizará al final del manejador de eventos.
### **Enrutamiento**
Por último, definimos nuestra app.
```python
app = rx.App()
```
Añadimos una página desde la raíz (root) de la aplicación al componente de índice (index). También agregamos un título que se mostrará en la vista previa de la página/pestaña del navegador.
```python
app.add_page(index, title="DALL-E")
```
Puedes crear una aplicación multipágina añadiendo más páginas.
## 📑 Recursos
<div align="center">
📑 [Docs](https://reflex.dev/docs/getting-started/introduction) | 🗞️ [Blog](https://reflex.dev/blog) | 📱 [Librería de componentes](https://reflex.dev/docs/library) | 🖼️ [Templates](https://reflex.dev/templates/) | 🛸 [Despliegue](https://reflex.dev/docs/hosting/deploy-quick-start)
</div>
## ✅ Estado
Reflex se lanzó en diciembre de 2022 con el nombre de Pynecone.
A partir de 2025, [Reflex Cloud](https://cloud.reflex.dev) se ha lanzado para proporcionar la mejor experiencia de alojamiento para aplicaciones Reflex. Continuaremos desarrollándolo e implementando más características.
¡Reflex tiene nuevas versiones y características cada semana! Asegúrate de :star: marcar como favorito y :eyes: seguir este repositorio para mantenerte actualizado.
## Contribuciones
¡Aceptamos contribuciones de cualquier tamaño! A continuación encontrará algunas buenas formas de iniciarse en la comunidad Reflex.
- **Únete a nuestro Discord**: Nuestro [Discord](https://discord.gg/T5WSbC2YtQ) es el mejor lugar para obtener ayuda en su proyecto Reflex y discutir cómo puedes contribuir.
- **Discusiones de GitHub**: Una excelente manera de hablar sobre las características que deseas agregar o las cosas que te resultan confusas o necesitan aclaración.
- **GitHub Issues**: Las incidencias son una forma excelente de informar de errores. Además, puedes intentar resolver un problema existente y enviar un PR.
Buscamos colaboradores, sin importar su nivel o experiencia. Para contribuir consulta [CONTRIBUTING.md](https://github.com/reflex-dev/reflex/blob/main/CONTRIBUTING.md)
## Todo Gracias A Nuestros Contribuidores:
<a href="https://github.com/reflex-dev/reflex/graphs/contributors">
<img src="https://contrib.rocks/image?repo=reflex-dev/reflex" />
</a>
## Licencia
Reflex es de código abierto y está licenciado bajo la [Apache License 2.0](/LICENSE).
## /docs/images/dalle.gif
Binary file available at https://raw.githubusercontent.com/reflex-dev/reflex/refs/heads/main/docs/images/dalle.gif
## /docs/images/dalle_colored_code_example.png
Binary file available at https://raw.githubusercontent.com/reflex-dev/reflex/refs/heads/main/docs/images/dalle_colored_code_example.png
## /docs/images/reflex.png
Binary file available at https://raw.githubusercontent.com/reflex-dev/reflex/refs/heads/main/docs/images/reflex.png
## /docs/images/reflex.svg
```svg path="/docs/images/reflex.svg"
<svg width="56" height="12" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 56 12"><style>path{fill:#110F1F}@media (prefers-color-scheme:dark){path{fill:#fff}}</style><path d="M0 11.6V.4h8.96v4.48H6.72V2.64H2.24v2.24h4.48v2.24H2.24v4.48H0Zm6.72 0V7.12h2.24v4.48H6.72Zm4.48 0V.4h6.72v2.24h-4.48v2.24h4.48v2.24h-4.48v2.24h4.48v2.24H11.2Zm8.96 0V.4h6.72v2.24H22.4v2.24h4.48v2.24H22.4v4.48h-2.24Zm8.96 0V.4h2.24v8.96h4.48v2.24h-6.72Zm8.96 0V.4h6.72v2.24h-4.48v2.24h4.48v2.24h-4.48v2.24h4.48v2.24h-6.72Zm8.96-6.72V.4h2.24v4.48h-2.24Zm6.72 0V.4H56v4.48h-2.24Zm-4.48 2.24V4.88h4.48v2.24h-4.48Zm-2.24 4.48V7.12h2.24v4.48h-2.24Zm6.72 0V7.12H56v4.48h-2.24Z"/></svg>
```
## /docs/images/reflex_dark.svg
```svg path="/docs/images/reflex_dark.svg"
<svg width="56" height="12" viewBox="0 0 56 12" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M0 11.6V0.400024H8.96V4.88002H6.72V2.64002H2.24V4.88002H6.72V7.12002H2.24V11.6H0ZM6.72 11.6V7.12002H8.96V11.6H6.72Z" fill="#110F1F"/>
<path d="M11.2 11.6V0.400024H17.92V2.64002H13.44V4.88002H17.92V7.12002H13.44V9.36002H17.92V11.6H11.2Z" fill="#110F1F"/>
<path d="M20.16 11.6V0.400024H26.88V2.64002H22.4V4.88002H26.88V7.12002H22.4V11.6H20.16Z" fill="#110F1F"/>
<path d="M29.12 11.6V0.400024H31.36V9.36002H35.84V11.6H29.12Z" fill="#110F1F"/>
<path d="M38.08 11.6V0.400024H44.8V2.64002H40.32V4.88002H44.8V7.12002H40.32V9.36002H44.8V11.6H38.08Z" fill="#110F1F"/>
<path d="M47.04 4.88002V0.400024H49.28V4.88002H47.04ZM53.76 4.88002V0.400024H56V4.88002H53.76ZM49.28 7.12002V4.88002H53.76V7.12002H49.28ZM47.04 11.6V7.12002H49.28V11.6H47.04ZM53.76 11.6V7.12002H56V11.6H53.76Z" fill="#110F1F"/>
</svg>
```
## /docs/images/reflex_light.svg
```svg path="/docs/images/reflex_light.svg"
<svg width="56" height="12" viewBox="0 0 56 12" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M0 11.5999V0.399902H8.96V4.8799H6.72V2.6399H2.24V4.8799H6.72V7.1199H2.24V11.5999H0ZM6.72 11.5999V7.1199H8.96V11.5999H6.72Z" fill="white"/>
<path d="M11.2 11.5999V0.399902H17.92V2.6399H13.44V4.8799H17.92V7.1199H13.44V9.3599H17.92V11.5999H11.2Z" fill="white"/>
<path d="M20.16 11.5999V0.399902H26.88V2.6399H22.4V4.8799H26.88V7.1199H22.4V11.5999H20.16Z" fill="white"/>
<path d="M29.12 11.5999V0.399902H31.36V9.3599H35.84V11.5999H29.12Z" fill="white"/>
<path d="M38.08 11.5999V0.399902H44.8V2.6399H40.32V4.8799H44.8V7.1199H40.32V9.3599H44.8V11.5999H38.08Z" fill="white"/>
<path d="M47.04 4.8799V0.399902H49.28V4.8799H47.04ZM53.76 4.8799V0.399902H56V4.8799H53.76ZM49.28 7.1199V4.8799H53.76V7.1199H49.28ZM47.04 11.5999V7.1199H49.28V11.5999H47.04ZM53.76 11.5999V7.1199H56V11.5999H53.76Z" fill="white"/>
</svg>
```
## /docs/in/README.md
<div align="center">
<img src="/docs/images/reflex_dark.svg#gh-light-mode-only" alt="Reflex लोगो" width="300px">
<img src="/docs/images/reflex_light.svg#gh-dark-mode-only" alt="Reflex लोगो" width="300px">
<hr>
### **✨ प्रदर्शनकारी, अनुकूलित वेब ऐप्स, शुद्ध Python में। सेकंडों में तैनात करें। ✨**
[](https://badge.fury.io/py/reflex)

[](https://reflex.dev/docs/getting-started/introduction)
[](https://pepy.tech/projects/reflex)
[](https://discord.gg/T5WSbC2YtQ)
</div>
---
[English](https://github.com/reflex-dev/reflex/blob/main/README.md) | [简体中文](https://github.com/reflex-dev/reflex/blob/main/docs/zh/zh_cn/README.md) | [繁體中文](https://github.com/reflex-dev/reflex/blob/main/docs/zh/zh_tw/README.md) | [Türkçe](https://github.com/reflex-dev/reflex/blob/main/docs/tr/README.md) | [हिंदी](https://github.com/reflex-dev/reflex/blob/main/docs/in/README.md) | [Português (Brasil)](https://github.com/reflex-dev/reflex/blob/main/docs/pt/pt_br/README.md) | [Italiano](https://github.com/reflex-dev/reflex/blob/main/docs/it/README.md) | [Español](https://github.com/reflex-dev/reflex/blob/main/docs/es/README.md) | [한국어](https://github.com/reflex-dev/reflex/blob/main/docs/kr/README.md) | [日本語](https://github.com/reflex-dev/reflex/blob/main/docs/ja/README.md) | [Deutsch](https://github.com/reflex-dev/reflex/blob/main/docs/de/README.md) | [Persian (پارسی)](https://github.com/reflex-dev/reflex/blob/main/docs/pe/README.md) | [Tiếng Việt](https://github.com/reflex-dev/reflex/blob/main/docs/vi/README.md)
# Reflex
Reflex शुद्ध पायथन में पूर्ण-स्टैक वेब ऐप्स बनाने के लिए एक लाइब्रेरी है।
मुख्य विशेषताएँ:
- **शुद्ध पायथन** - अपने ऐप के फ्रंटएंड और बैकएंड को पायथन में लिखें, जावास्क्रिप्ट सीखने की जरूरत नहीं है।
- **पूर्ण लचीलापन** - Reflex के साथ शुरुआत करना आसान है, लेकिन यह जटिल ऐप्स के लिए भी स्केल कर सकता है।
- **तुरंत तैनाती** - बिल्डिंग के बाद, अपने ऐप को [एकल कमांड](https://reflex.dev/docs/hosting/deploy-quick-start/) के साथ तैनात करें या इसे अपने सर्वर पर होस्ट करें।
Reflex के अंदर के कामकाज को जानने के लिए हमारे [आर्किटेक्चर पेज](https://reflex.dev/blog/2024-03-21-reflex-architecture/#the-reflex-architecture) को देखें।
## ⚙️ इंस्टॉलेशन (Installation)
एक टर्मिनल खोलें और चलाएं (Python 3.10+ की आवश्यकता है):
```bash
pip install reflex
```
## 🥳 अपना पहला ऐप बनाएं (Create your first App)
reflex को इंस्टॉल करने से ही reflex कमांड लाइन टूल भी इंस्टॉल हो जाता है।
सुनिश्चित करें कि इंस्टॉलेशन सफल थी, एक नया प्रोजेक्ट बनाकर इसे टेस्ट करें। ('my_app_name' की जगह अपने प्रोजेक्ट का नाम रखें):
```bash
mkdir my_app_name
cd my_app_name
reflex init
```
यह कमांड आपकी नयी डायरेक्टरी में एक टेम्पलेट ऐप को प्रारंभ करता है।
आप इस ऐप को development मोड में चला सकते हैं:
```bash
reflex run
```
आपको http://localhost:3000 पर अपने ऐप को चलते हुए देखना चाहिए।
अब आप my_app_name/my_app_name.py में source कोड को संशोधित कर सकते हैं। Reflex में तेज रिफ्रेश की सुविधा है, इसलिए जब आप अपनी कोड को सहेजते हैं, तो आप अपने बदलावों को तुरंत देख सकते हैं।
## 🫧 उदाहरण ऐप (Example App)
एक उदाहरण पर चलते हैं: [DALL·E](https://platform.openai.com/docs/guides/images/image-generation?context=node) से एक इमेज उत्पन्न करने के लिए UI। सरलता के लिए, हम सिर्फ [OpenAI API](https://platform.openai.com/docs/api-reference/authentication) को बुलाते हैं, लेकिन आप इसे ML मॉडल से बदल सकते हैं locally।
<div align="center">
<img src="/docs/images/dalle.gif" alt="DALL·E के लिए एक फ्रंटएंड रैपर, छवि उत्पन्न करने की प्रक्रिया में दिखाया गया।" width="550" />
</div>
यहाँ पर इसका पूरा कोड है जिससे यह बनाया जा सकता है। यह सब एक ही Python फ़ाइल में किया गया है!
```python
import reflex as rx
import openai
openai_client = openai.OpenAI()
class State(rx.State):
"""The app state."""
prompt = ""
image_url = ""
processing = False
complete = False
def get_image(self):
"""Get the image from the prompt."""
if self.prompt == "":
return rx.window_alert("Prompt Empty")
self.processing, self.complete = True, False
yield
response = openai_client.images.generate(
prompt=self.prompt, n=1, size="1024x1024"
)
self.image_url = response.data[0].url
self.processing, self.complete = False, True
def index():
return rx.center(
rx.vstack(
rx.heading("DALL-E", font_size="1.5em"),
rx.input(
placeholder="Enter a prompt..",
on_blur=State.set_prompt,
width="25em",
),
rx.button(
"Generate Image",
on_click=State.get_image,
width="25em",
loading=State.processing
),
rx.cond(
State.complete,
rx.image(src=State.image_url, width="20em"),
),
align="center",
),
width="100%",
height="100vh",
)
# Add state and page to the app.
app = rx.App()
app.add_page(index, title="Reflex:DALL-E")
```
## इसे समझते हैं।
<div align="center">
<img src="/docs/images/dalle_colored_code_example.png" alt="DALL-E ऐप के बैकएंड और फ्रंटएंड भागों के बीच के अंतर की व्याख्या करता है।" width="900" />
</div>
### **Reflex UI**
हम UI के साथ शुरू करेंगे।
```python
def index():
return rx.center(
...
)
```
यह `index` फ़ंक्शन एप्लिकेशन की फ़्रंटएंड को परिभाषित करता है।
हम फ़्रंटएंड बनाने के लिए `center`, `vstack`, `input`, और `button` जैसे विभिन्न components का उपयोग करते हैं। Components को एक-दूसरे के भीतर डाल सकते हैं विस्तारित लेआउट बनाने के लिए। और आप CSS की पूरी ताक़त के साथ इन्हें स्टाइल करने के लिए कीवर्ड आर्ग्यूमेंट (keyword args) का उपयोग कर सकते हैं।
रिफ़्लेक्स के पास [60+ built-in components](https://reflex.dev/docs/library) हैं जो आपको शुरुआती मदद के लिए हैं। हम बहुत से components जोड़ रहे हैं, और अपने खुद के components बनाना भी आसान है। [create your own components](https://reflex.dev/docs/wrapping-react/overview/)
### **स्टेट (State)**
Reflex आपके UI को आपकी स्टेट (state) के एक फ़ंक्शन के रूप में प्रस्तुत करता है।
```python
class State(rx.State):
"""The app state."""
prompt = ""
image_url = ""
processing = False
complete = False
```
स्टेट (state) ऐप में उन सभी वेरिएबल्स (vars) को परिभाषित करती है जो बदल सकती हैं और उन फ़ंक्शनों को जो उन्हें बदलते हैं।
यहां स्टेट (state) में `prompt` और `image_url` शामिल हैं। प्रगति और छवि दिखाने के लिए `processing` और `complete` बूलियन भी हैं।
### **इवेंट हैंडलर (Event Handlers)**
```python
def get_image(self):
"""Get the image from the prompt."""
if self.prompt == "":
return rx.window_alert("Prompt Empty")
self.processing, self.complete = True, False
yield
response = openai_client.images.generate(
prompt=self.prompt, n=1, size="1024x1024"
)
self.image_url = response.data[0].url
self.processing, self.complete = False, True
```
स्टेट (state) के अंदर, हम इवेंट हैंडलर्स (event handlers) को परिभाषित करते हैं जो स्टेट वेरिएबल्स को बदलते हैं। इवेंट हैंडलर्स (event handlers) से reflex में स्टेट (state) को मॉडिफ़ाय किया जा सकता हैं। इन्हें उपयोगकर्ता क्रियाओं (user actions) के प्रति प्रतिक्रिया (response) के रूप में बुलाया जा सकता है, जैसे कि बटन को क्लिक करना या टेक्स्ट बॉक्स में टाइप करना। इन क्रियाओं को इवेंट्स (events) कहा जाता है।
हमारे DALL·E. ऐप में एक इवेंट हैंडलर `get_image` है जिससे यह OpenAI API से इमेज प्राप्त करता है। इवेंट हैंडलर में `yield` का उपयोग करने कि वजह से UI अपडेट हो जाएगा। अन्यथा UI इवेंट हैंडलर के अंत में अपडेट होगा।
### **रूटिंग (Routing)**
आखिरकार, हम अपने एप्लिकेशन को परिभाषित करते हैं।
```python
app = rx.App()
```
हम अपने एप्लिकेशन के रूट से इंडेक्स कॉम्पोनेंट तक एक पेज को जोड़ते हैं। हम एक शीर्षक भी जोड़ते हैं जो पेज प्रीव्यू/ब्राउज़र टैब में दिखाई देगा।
```python
app.add_page(index, title="DALL-E")
```
आप और पेज जोड़कर एक मल्टी-पेज एप्लिकेशन बना सकते हैं।
## 📑 संसाधन (Resources)
<div align="center">
📑 [दस्तावेज़](https://reflex.dev/docs/getting-started/introduction) | 🗞️ [ब्लॉग](https://reflex.dev/blog) | 📱 [कॉम्पोनेंट लाइब्रेरी](https://reflex.dev/docs/library) | 🖼️ [टेम्पलेट्स](https://reflex.dev/templates/) | 🛸 [तैनाती](https://reflex.dev/docs/hosting/deploy-quick-start)
</div>
## ✅ स्टेटस (Status)
Reflex दिसंबर 2022 में Pynecone नाम से शुरू हुआ।
2025 की शुरुआत से, [Reflex Cloud](https://cloud.reflex.dev) लॉन्च किया गया है जो Reflex ऐप्स के लिए सर्वोत्तम होस्टिंग अनुभव प्रदान करता है। हम इसे विकसित करना और अधिक सुविधाएँ लागू करना जारी रखेंगे।
Reflex में हर सप्ताह नए रिलीज़ और फीचर्स आ रहे हैं! सुनिश्चित करें कि :star: स्टार और :eyes: वॉच इस रेपोजिटरी को अपडेट रहने के लिए।
## (योगदान) Contributing
हम हर तरह के योगदान का स्वागत करते हैं! रिफ्लेक्स कम्यूनिटी में शुरुआत करने के कुछ अच्छे तरीके नीचे दिए गए हैं।
- **Join Our Discord** (डिस्कॉर्ड सर्वर से जुड़ें): हमारा [Discord](https://discord.gg/T5WSbC2YtQ) रिफ्लेक्स प्रोजेक्ट पर सहायता प्राप्त करने और आप कैसे योगदान दे सकते हैं, इस पर चर्चा करने के लिए सबसे अच्छी जगह है।
- **GitHub Discussions** (गिटहब चर्चाएँ): उन सुविधाओं के बारे में बात करने का एक शानदार तरीका जिन्हें आप जोड़ना चाहते हैं या ऐसी चीज़ें जो भ्रमित करने वाली हैं/स्पष्टीकरण की आवश्यकता है।
- **GitHub Issues** (गिटहब समस्याएं): [Issues](https://github.com/reflex-dev/reflex/issues) बग की रिपोर्ट करने का एक शानदार तरीका है। इसके अतिरिक्त, आप किसी मौजूदा समस्या को हल करने का प्रयास कर सकते हैं और एक पीआर सबमिट कर सकते हैं।
हम सक्रिय रूप से योगदानकर्ताओं की तलाश कर रहे हैं, चाहे आपका कौशल स्तर या अनुभव कुछ भी हो। योगदान करने के लिए [CONTRIBUTING.md](https://github.com/reflex-dev/reflex/blob/main/CONTRIBUTING.md) देखें।
## हमारे सभी योगदानकर्ताओं का धन्यवाद:
<a href="https://github.com/reflex-dev/reflex/graphs/contributors">
<img src="https://contrib.rocks/image?repo=reflex-dev/reflex" />
</a>
## लाइसेंस (License)
रिफ्लेक्स ओपन-सोर्स है और [अपाचे लाइसेंस 2.0](/LICENSE) के तहत लाइसेंस प्राप्त है।
## /docs/it/README.md
<div align="center">
<img src="/docs/images/reflex.svg" alt="Reflex Logo" width="300px">
<hr>
### **✨ App web performanti e personalizzabili in puro Python. Distribuisci in pochi secondi. ✨**
[](https://badge.fury.io/py/reflex)

[](https://reflex.dev/docs/getting-started/introduction)
[](https://pepy.tech/projects/reflex)
[](https://discord.gg/T5WSbC2YtQ)
</div>
---
[English](https://github.com/reflex-dev/reflex/blob/main/README.md) | [简体中文](https://github.com/reflex-dev/reflex/blob/main/docs/zh/zh_cn/README.md) | [繁體中文](https://github.com/reflex-dev/reflex/blob/main/docs/zh/zh_tw/README.md) | [Türkçe](https://github.com/reflex-dev/reflex/blob/main/docs/tr/README.md) | [हिंदी](https://github.com/reflex-dev/reflex/blob/main/docs/in/README.md) | [Português (Brasil)](https://github.com/reflex-dev/reflex/blob/main/docs/pt/pt_br/README.md) | [Italiano](https://github.com/reflex-dev/reflex/blob/main/docs/it/README.md) | [Español](https://github.com/reflex-dev/reflex/blob/main/docs/es/README.md) | [한국어](https://github.com/reflex-dev/reflex/blob/main/docs/kr/README.md) | [日本語](https://github.com/reflex-dev/reflex/blob/main/docs/ja/README.md) | [Deutsch](https://github.com/reflex-dev/reflex/blob/main/docs/de/README.md) | [Persian (پارسی)](https://github.com/reflex-dev/reflex/blob/main/docs/pe/README.md) | [Tiếng Việt](https://github.com/reflex-dev/reflex/blob/main/docs/vi/README.md)
---
# Reflex
Reflex è una libreria per sviluppare applicazioni web full-stack in Python puro.
Caratteristiche principali:
- **Python Puro** - Scrivi il frontend e il backend della tua app interamente in Python, senza bisogno di imparare Javascript.
- **Flessibilità Totale** - Reflex è facile da iniziare, ma può anche gestire app complesse.
- **Distribuzione Istantanea** - Dopo lo sviluppo, distribuisci la tua app con un [singolo comando](https://reflex.dev/docs/hosting/deploy-quick-start/) o ospitala sul tuo server.
Consulta la nostra [pagina di architettura](https://reflex.dev/blog/2024-03-21-reflex-architecture/#the-reflex-architecture) per scoprire come funziona Reflex sotto il cofano.
## ⚙️ Installazione
Apri un terminale ed esegui (Richiede Python 3.10+):
```bash
pip install reflex
```
## 🥳 Crea la tua prima app
Installando `reflex` si installa anche lo strumento da riga di comando `reflex`.
Verifica che l'installazione sia stata eseguita correttamente creando un nuovo progetto. (Sostituisci `nome_app` con il nome del tuo progetto):
```bash
mkdir nome_app
cd nome_app
reflex init
```
Questo comando inizializza un'app template nella tua nuova directory.
Puoi eseguire questa app in modalità sviluppo con:
```bash
reflex run
```
Dovresti vedere la tua app in esecuzione su http://localhost:3000.
Ora puoi modificare il codice sorgente in `nome_app/nome_app.py`. Reflex offre aggiornamenti rapidi, così puoi vedere le tue modifiche istantaneamente quando salvi il tuo codice.
## 🫧 Esempio App
Esaminiamo un esempio: creare un'interfaccia utente per la generazione di immagini attorno a [DALL·E](https://platform.openai.com/docs/guides/images/image-generation?context=node). Per semplicità, chiamiamo semplicemente l'[API OpenAI](https://platform.openai.com/docs/api-reference/authentication), ma potresti sostituirla con un modello ML eseguito localmente.
<div align="center">
<img src="/docs/images/dalle.gif" alt="Un wrapper frontend per DALL·E, mostrato nel processo di generazione di un'immagine." width="550" />
</div>
Ecco il codice completo per crearlo. Tutto fatto in un unico file Python!
```python
import reflex as rx
import openai
openai_client = openai.OpenAI()
class State(rx.State):
"""Lo stato dell'app."""
prompt = ""
image_url = ""
processing = False
complete = False
def get_image(self):
"""Ottieni l'immagine dal prompt."""
if self.prompt == "":
return rx.window_alert("Prompt Vuoto")
self.processing, self.complete = True, False
yield
response = openai_client.images.generate(
prompt=self.prompt, n=1, size="1024x1024"
)
self.image_url = response.data[0].url
self.processing, self.complete = False, True
def index():
return rx.center(
rx.vstack(
rx.heading("DALL-E", font_size="1.5em"),
rx.input(
placeholder="Inserisci un prompt..",
on_blur=State.set_prompt,
width="25em",
),
rx.button(
"Genera Immagine",
on_click=State.get_image,
width="25em",
loading=State.processing
),
rx.cond(
State.complete,
rx.image(src=State.image_url, width="20em"),
),
align="center",
),
width="100%",
height="100vh",
)
# Aggiungi stato e pagina all'app.
app = rx.App()
app.add_page(index, title="Reflex:DALL-E")
```
## Analizziamolo.
<div align="center">
<img src="/docs/images/dalle_colored_code_example.png" alt="Spiegazione delle differenze tra le parti backend e frontend dell'app DALL-E." width="900" />
</div>
### **Reflex UI**
Cominciamo con l'UI.
```python
def index():
return rx.center(
...
)
```
Questa funzione `index` definisce il frontend dell'app.
Utilizziamo diversi componenti come `center`, `vstack`, `input`, e `button` per costruire il frontend. I componenti possono essere annidati gli uni negli altri per creare layout complessi. E puoi utilizzare argomenti chiave per stilizzarli con tutta la potenza di CSS.
Reflex offre [più di 60 componenti integrati](https://reflex.dev/docs/library) per aiutarti a iniziare. Stiamo attivamente aggiungendo più componenti ed è facile [creare i tuoi componenti](https://reflex.dev/docs/wrapping-react/overview/).
### **Stato (State)**
Reflex rappresenta la tua UI come una funzione del tuo stato.
```python
class State(rx.State):
"""Lo stato dell'app."""
prompt = ""
image_url = ""
processing = False
complete = False
```
Lo stato definisce tutte le variabili (chiamate vars) in un'app che possono cambiare e le funzioni che le cambiano.
Qui lo stato è composto da un `prompt` e `image_url`. Ci sono anche i booleani `processing` e `complete` per indicare quando disabilitare il pulsante (durante la generazione dell'immagine) e quando mostrare l'immagine risultante.
### **Gestori di Eventi (Event Handlers)**
```python
def get_image(self):
"""Ottieni l'immagine dal prompt."""
if self.prompt == "":
return rx.window_alert("Prompt Vuoto")
self.processing, self.complete = True, False
yield
response = openai_client.images.generate(
prompt=self.prompt, n=1, size="1024x1024"
)
self.image_url = response.data[0].url
self.processing, self.complete = False, True
```
Dentro lo stato, definiamo funzioni chiamate gestori di eventi che cambiano le vars dello stato. I gestori di eventi sono il modo in cui possiamo modificare lo stato in Reflex. Possono essere chiamati in risposta alle azioni dell'utente, come fare clic su un pulsante o digitare in una casella di testo. Queste azioni vengono chiamate eventi.
La nostra app DALL·E ha un gestore di eventi, `get_image` con cui ottiene questa immagine dall'API OpenAI. Utilizzando `yield` nel mezzo di un gestore di eventi farà sì che l'UI venga aggiornata. Altrimenti, l'UI verrà aggiornata alla fine del gestore di eventi.
### **Instradamento (Routing)**
Infine, definiamo la nostra app.
```python
app = rx.App()
```
Aggiungiamo una pagina dalla radice dell'app al componente dell'indice. Aggiungiamo anche un titolo che apparirà nell'anteprima della pagina/scheda del browser.
```python
app.add_page(index, title="DALL-E")
```
Puoi creare un'app multi-pagina aggiungendo altre pagine.
## 📑 Risorse
<div align="center">
📑 [Documentazione](https://reflex.dev/docs/getting-started/introduction) | 🗞️ [Blog](https://reflex.dev/blog) | 📱 [Libreria Componenti](https://reflex.dev/docs/library) | 🖼️ [Templates](https://reflex.dev/templates/) | 🛸 [Distribuzione](https://reflex.dev/docs/hosting/deploy-quick-start)
</div>
## ✅ Stato
Reflex è stato lanciato nel dicembre 2022 con il nome Pynecone.
A partire dal 2025, [Reflex Cloud](https://cloud.reflex.dev) è stato lanciato per fornire la migliore esperienza di hosting per le app Reflex. Continueremo a svilupparlo e implementare più funzionalità.
Reflex ha nuove versioni e funzionalità in arrivo ogni settimana! Assicurati di :star: mettere una stella e :eyes: osservare questa repository per rimanere aggiornato.
## Contribuire
Diamo il benvenuto a contributi di qualsiasi dimensione! Di seguito sono alcuni modi per iniziare nella comunità Reflex.
- **Unisciti al nostro Discord**: Il nostro [Discord](https://discord.gg/T5WSbC2YtQ) è posto migliore per ottenere aiuto sul tuo progetto Reflex e per discutere come puoi contribuire.
- **Discussioni su GitHub**: Un ottimo modo per parlare delle funzionalità che desideri aggiungere o di cose che creano confusione o necessitano chiarimenti.
- **GitHub Issues**: Le [Issues](https://github.com/reflex-dev/reflex/issues) sono un ottimo modo per segnalare bug. Inoltre, puoi provare a risolvere un problema esistente e inviare un PR.
Stiamo attivamente cercando collaboratori, indipendentemente dal tuo livello di abilità o esperienza. Per contribuire, consulta [CONTRIBUTING.md](https://github.com/reflex-dev/reflex/blob/main/CONTRIBUTING.md)
## Un Grazie a Tutti i Nostri Contributori:
<a href="https://github.com/reflex-dev/reflex/graphs/contributors">
<img src="https://contrib.rocks/image?repo=reflex-dev/reflex" />
</a>
## Licenza
Reflex è open-source e rilasciato sotto la [Licenza Apache 2.0](/LICENSE).
## /docs/ja/README.md
<div align="center">
<img src="/docs/images/reflex.svg" alt="Reflex Logo" width="300px">
<hr>
### **✨ 即時デプロイが可能な、Pure Python で作ったパフォーマンスと汎用性が高い Web アプリケーション ✨**
[](https://badge.fury.io/py/reflex)

[](https://reflex.dev/docs/getting-started/introduction)
[](https://pepy.tech/projects/reflex)
[](https://discord.gg/T5WSbC2YtQ)
</div>
---
[English](https://github.com/reflex-dev/reflex/blob/main/README.md) | [简体中文](https://github.com/reflex-dev/reflex/blob/main/docs/zh/zh_cn/README.md) | [繁體中文](https://github.com/reflex-dev/reflex/blob/main/docs/zh/zh_tw/README.md) | [Türkçe](https://github.com/reflex-dev/reflex/blob/main/docs/tr/README.md) | [हिंदी](https://github.com/reflex-dev/reflex/blob/main/docs/in/README.md) | [Português (Brasil)](https://github.com/reflex-dev/reflex/blob/main/docs/pt/pt_br/README.md) | [Italiano](https://github.com/reflex-dev/reflex/blob/main/docs/it/README.md) | [Español](https://github.com/reflex-dev/reflex/blob/main/docs/es/README.md) | [한국어](https://github.com/reflex-dev/reflex/blob/main/docs/kr/README.md) | [日本語](https://github.com/reflex-dev/reflex/blob/main/docs/ja/README.md) | [Deutsch](https://github.com/reflex-dev/reflex/blob/main/docs/de/README.md) | [Persian (پارسی)](https://github.com/reflex-dev/reflex/blob/main/docs/pe/README.md) | [Tiếng Việt](https://github.com/reflex-dev/reflex/blob/main/docs/vi/README.md)
---
# Reflex
Reflex は Python のみでフルスタック Web アプリケーションを作成できるライブラリです。
主な特徴:
- **Pure Python** - Web アプリケーションのフロントエンドとバックエンドを Python のみで実装できるため、Javascript を学ぶ必要がありません。
- **高い柔軟性** - Reflex は簡単に始められて、複雑なアプリケーションまで作成できます。
- **即時デプロイ** - ビルド後、すぐにデプロイが可能です。[単純な CLI コマンド](https://reflex.dev/docs/hosting/deploy-quick-start/)を使ったアプリケーションのデプロイや、自身のサーバーへのホストができます。
Reflex がどのように動作しているかを知るには、[アーキテクチャページ](https://reflex.dev/blog/2024-03-21-reflex-architecture/#the-reflex-architecture)をご覧ください。
## ⚙️ インストール
ターミナルを開いて以下のコマンドを実行してください。(Python 3.10 以上が必要です。):
```bash
pip install reflex
```
## 🥳 最初のアプリケーションを作ろう
`reflex`をインストールすると、`reflex`の CLI ツールが自動でインストールされます。
新しいプロジェクトを作成して、インストールが成功しているかを確認しましょう。(`my_app_name`を自身のプロジェクト名に書き換えて実行ください。):
```bash
mkdir my_app_name
cd my_app_name
reflex init
```
上記のコマンドを実行すると、新しいフォルダにテンプレートアプリを作成します。
下記のコマンドを実行すると、開発モードでアプリを開始します。
```bash
reflex run
```
http://localhost:3000 にアクセスしてアプリの動作を見ることができます。
`my_app_name/my_app_name.py`のソースコードを編集してみましょう!Reflex は fast refresh なので、ソースを保存した直後に変更が Web ページに反映されます。
## 🫧 実装例
実装例を見てみましょう: [DALL·E](https://platform.openai.com/docs/guides/images/image-generation?context=node)を中心とした画像生成 UI を作成しました。説明を簡単にするためにここでは[OpenAI API](https://platform.openai.com/docs/api-reference/authentication)を呼んでいますが、ローカルで動作している機械学習モデルに置き換えることも可能です。
<div align="center">
<img src="/docs/images/dalle.gif" alt="DALL·Eのフロントエンドラッパーです。画像を生成している過程を表示しています。" width="550" />
</div>
画像生成 UI のソースコードの全貌を見てみましょう。下記のように、単一の Python ファイルで作れます!
```python
import reflex as rx
import openai
openai_client = openai.OpenAI()
class State(rx.State):
"""アプリのステート"""
prompt = ""
image_url = ""
processing = False
complete = False
def get_image(self):
"""プロンプトからイメージを取得する"""
if self.prompt == "":
return rx.window_alert("Prompt Empty")
self.processing, self.complete = True, False
yield
response = openai_client.images.generate(
prompt=self.prompt, n=1, size="1024x1024"
)
self.image_url = response.data[0].url
self.processing, self.complete = False, True
def index():
return rx.center(
rx.vstack(
rx.heading("DALL-E", font_size="1.5em"),
rx.input(
placeholder="Enter a prompt..",
on_blur=State.set_prompt,
width="25em",
),
rx.button(
"Generate Image",
on_click=State.get_image,
width="25em",
loading=State.processing
),
rx.cond(
State.complete,
rx.image(src=State.image_url, width="20em"),
),
align="center",
),
width="100%",
height="100vh",
)
# ステートとページをアプリに追加
app = rx.App()
app.add_page(index, title="Reflex:DALL-E")
```
## それぞれの実装を見てみましょう
<div align="center">
<img src="/docs/images/dalle_colored_code_example.png" alt="DALL-E appのフロントエンドとバックエンドのパーツの違いを説明しています。" width="900" />
</div>
### **Reflex UI**
UI から見てみましょう。
```python
def index():
return rx.center(
...
)
```
`index`関数において、アプリのフロントエンドを定義しています。
フロントエンドを実装するにあたり、`center`、`vstack`、`input`、`button`など異なるコンポーネントを使用しています。コンポーネントはお互いにネストが可能であり、複雑なレイアウトを作成できます。また、keyword args を使うことで、CSS の機能をすべて使ったスタイルが可能です。
Reflex は[60 を超える内臓コンポーネント](https://reflex.dev/docs/library)があるため、すぐに始められます。私たちは、積極的にコンポーネントを追加していますが、簡単に[自身のコンポーネントを追加](https://reflex.dev/docs/wrapping-react/overview/)することも可能です。
### **ステート**
Reflex はステートの関数を用いて UI を表示します。
```python
class State(rx.State):
"""アプリのステート"""
prompt = ""
image_url = ""
processing = False
complete = False
```
ステートでは、アプリで変更が可能な全ての変数(vars と呼びます)と、vars の変更が可能な関数を定義します。
この例では、ステートを`prompt`と`image_url`で構成しています。そして、ブール型の`processing`と`complete`を用いて、ボタンを無効にするタイミング(画像生成中)や生成された画像を表示するタイミングを示しています。
### **イベントハンドラ**
```python
def get_image(self):
"""プロンプトからイメージを取得する"""
if self.prompt == "":
return rx.window_alert("Prompt Empty")
self.processing, self.complete = True, False
yield
response = openai_client.images.generate(
prompt=self.prompt, n=1, size="1024x1024"
)
self.image_url = response.data[0].url
self.processing, self.complete = False, True
```
ステートにおいて、ステートの vars を変更できるイベントハンドラ関数を定義しています。イベントハンドラは Reflex において、ステートの vars を変更する方法です。ボタンクリックやテキストボックスの入力など、ユーザのアクションに応じてイベントハンドラが呼ばれます。
DALL·E.アプリには、OpenAI API からイメージを取得する`get_image`関数があります。イベントハンドラの最後で UI の更新がかかるため、関数の途中に`yield`を入れることで先に UI を更新しています。
### **ルーティング**
最後に、アプリを定義します。
```python
app = rx.App()
```
アプリにページを追加し、ドキュメントルートを index コンポーネントにルーティングしています。更に、ページのプレビューやブラウザタブに表示されるタイトルを記載しています。
```python
app.add_page(index, title="DALL-E")
```
ページを追加することで、マルチページアプリケーションを作成できます。
## 📑 リソース
<div align="center">
📑 [Docs](https://reflex.dev/docs/getting-started/introduction) | 🗞️ [Blog](https://reflex.dev/blog) | 📱 [Component Library](https://reflex.dev/docs/library) | 🖼️ [Templates](https://reflex.dev/templates/) | 🛸 [Deployment](https://reflex.dev/docs/hosting/deploy-quick-start)
</div>
## ✅ ステータス
2022 年 12 月に、Reflex は Pynecone という名前でローンチしました。
2025 年から [Reflex Cloud](https://cloud.reflex.dev) がローンチされ、Reflex アプリケーションの最高のホスティング体験を提供しています。私たちは引き続き開発を続け、より多くの機能を実装していきます。
Reflex は毎週、新しいリリースや機能追加を行っています!最新情報を逃さないために、 :star: Star や :eyes: Watch をお願いします。
## コントリビュート
様々なサイズのコントリビュートを歓迎しています!Reflex コミュニティに入るための方法を、いくつかリストアップします。
- **Discord に参加**: [Discord](https://discord.gg/T5WSbC2YtQ)は、Reflex プロジェクトの相談や、コントリビュートについての話し合いをするための、最適な場所です。
- **GitHub Discussions**: GitHub Discussions では、追加したい機能や、複雑で解明が必要な事柄についての議論に適している場所です。
- **GitHub Issues**: [Issues](https://github.com/reflex-dev/reflex/issues)はバグの報告に適している場所です。また、課題を解決した PR のサブミットにチャレンジしていただくことも、可能です。
スキルや経験に関わらず、私たちはコントリビュータを積極的に探しています。コントリビュートするために、[CONTRIBUTING.md](https://github.com/reflex-dev/reflex/blob/main/CONTRIBUTING.md)をご覧ください。
## 私たちのコントリビュータに感謝!:
<a href="https://github.com/reflex-dev/reflex/graphs/contributors">
<img src="https://contrib.rocks/image?repo=reflex-dev/reflex" />
</a>
## ライセンス
Reflex はオープンソースであり、[Apache License 2.0](/LICENSE)に基づいてライセンス供与されます。
## /docs/kr/README.md
<div align="center">
<img src="/docs/images/reflex.svg" alt="Reflex Logo" width="300px">
<hr>
### **✨ 순수 Python으로 고성능 사용자 정의 웹앱을 만들어 보세요. 몇 초만에 배포 가능합니다. ✨**
[](https://badge.fury.io/py/reflex)

[](https://reflex.dev/docs/getting-started/introduction)
[](https://pepy.tech/projects/reflex)
[](https://discord.gg/T5WSbC2YtQ)
</div>
---
[English](https://github.com/reflex-dev/reflex/blob/main/README.md) | [简体中文](https://github.com/reflex-dev/reflex/blob/main/docs/zh/zh_cn/README.md) | [繁體中文](https://github.com/reflex-dev/reflex/blob/main/docs/zh/zh_tw/README.md) | [Türkçe](https://github.com/reflex-dev/reflex/blob/main/docs/tr/README.md) | [हिंदी](https://github.com/reflex-dev/reflex/blob/main/docs/in/README.md) | [Português (Brasil)](https://github.com/reflex-dev/reflex/blob/main/docs/pt/pt_br/README.md) | [Italiano](https://github.com/reflex-dev/reflex/blob/main/docs/it/README.md) | [Español](https://github.com/reflex-dev/reflex/blob/main/docs/es/README.md) | [한국어](https://github.com/reflex-dev/reflex/blob/main/docs/kr/README.md) | [日本語](https://github.com/reflex-dev/reflex/blob/main/docs/ja/README.md) | [Deutsch](https://github.com/reflex-dev/reflex/blob/main/docs/de/README.md) | [Persian (پارسی)](https://github.com/reflex-dev/reflex/blob/main/docs/pe/README.md) | [Tiếng Việt](https://github.com/reflex-dev/reflex/blob/main/docs/vi/README.md)
---
# Reflex
Reflex는 순수 Python으로 풀스택 웹 앱을 구축하기 위한 라이브러리입니다.
주요 기능:
- **순수 Python** - 앱의 프론트엔드와 백엔드를 모두 Python으로 작성하며, Javascript를 배울 필요가 없습니다.
- **완전한 유연성** - Reflex는 시작하기 쉽지만, 복잡한 앱으로도 확장할 수 있습니다.
- **즉시 배포** - 앱을 빌드한 후 [단일 명령어](https://reflex.dev/docs/hosting/deploy-quick-start/)로 배포하거나 자체 서버에서 호스팅할 수 있습니다.
Reflex가 내부적으로 어떻게 작동하는지 알아보려면 [아키텍처 페이지](https://reflex.dev/blog/2024-03-21-reflex-architecture/#the-reflex-architecture)를 참조하세요.
## ⚙️ 설치
터미널을 열고 실행하세요. (Python 3.10+ 필요):
```bash
pip install reflex
```
## 🥳 첫 앱 만들기
`reflex`를 설치하면, `reflex` 명령어 라인 도구도 설치됩니다.
새 프로젝트를 생성하여 설치가 성공적인지 확인합니다. (`my_app_name`을 프로젝트 이름으로 변경합니다.):
```bash
mkdir my_app_name
cd my_app_name
reflex init
```
이 명령어는 새 디렉토리에 템플릿 앱을 초기화합니다.
개발 모드에서 이 앱을 실행할 수 있습니다:
```bash
reflex run
```
http://localhost:3000 에서 앱이 실행 됩니다.
이제 `my_app_name/my_app_name.py`에서 소스코드를 수정할 수 있습니다. Reflex는 빠른 새로고침을 지원하므로 코드를 저장할 때마다 즉시 변경 사항을 볼 수 있습니다.
## 🫧 예시 앱
예시를 살펴보겠습니다: [DALL·E](https://platform.openai.com/docs/guides/images/image-generation?context=node)를 중심으로 이미지 생성 UI를 만들어 보겠습니다. 간단하게 하기 위해 [OpenAI API](https://platform.openai.com/docs/api-reference/authentication)를 호출했지만, 이를 로컬에서 실행되는 ML 모델로 대체할 수 있습니다.
<div align="center">
<img src="/docs/images/dalle.gif" alt="A frontend wrapper for DALL·E, shown in the process of generating an image." width="550" />
</div>
이것이 완성된 코드입니다. 이 모든 것은 하나의 Python 파일에서 이루어집니다!
```python
import reflex as rx
import openai
openai_client = openai.OpenAI()
class State(rx.State):
"""The app state."""
prompt = ""
image_url = ""
processing = False
complete = False
def get_image(self):
"""Get the image from the prompt."""
if self.prompt == "":
return rx.window_alert("Prompt Empty")
self.processing, self.complete = True, False
yield
response = openai_client.images.generate(
prompt=self.prompt, n=1, size="1024x1024"
)
self.image_url = response.data[0].url
self.processing, self.complete = False, True
def index():
return rx.center(
rx.vstack(
rx.heading("DALL-E", font_size="1.5em"),
rx.input(
placeholder="Enter a prompt..",
on_blur=State.set_prompt,
width="25em",
),
rx.button(
"Generate Image",
on_click=State.get_image,
width="25em",
loading=State.processing
),
rx.cond(
State.complete,
rx.image(src=State.image_url, width="20em"),
),
align="center",
),
width="100%",
height="100vh",
)
# Add state and page to the app.
app = rx.App()
app.add_page(index, title="Reflex:DALL-E")
```
## 하나씩 살펴보겠습니다.
<div align="center">
<img src="/docs/images/dalle_colored_code_example.png" alt="Explaining the differences between backend and frontend parts of the DALL-E app." width="900" />
</div>
### **Reflex UI**
UI부터 시작해봅시다.
```python
def index():
return rx.center(
...
)
```
`index` 함수는 앱의 프론트엔드를 정의합니다.
`center`, `vstack`, `input`, `button`과 같은 다양한 컴포넌트를 사용하여 프론트엔드를 구축합니다.
컴포넌트들은 복잡한 레이아웃을 만들기 위해 서로 중첩될 수 있습니다.
그리고 키워드 인자를 사용하여 CSS의 모든 기능을 사용하여 스타일을 지정할 수 있습니다.
Reflex는 시작하기 위한 [60개 이상의 기본 컴포넌트](https://reflex.dev/docs/library)를 제공하고 있습니다. 더 많은 컴포넌트를 추가하고 있으며, [자신만의 컴포넌트를 생성하는 것](https://reflex.dev/docs/wrapping-react/overview/)도 쉽습니다.
### **State**
Reflex는 UI를 State 함수로 표현합니다.
```python
class State(rx.State):
"""The app state."""
prompt = ""
image_url = ""
processing = False
complete = False
```
state는 앱에서 변경될 수 있는 모든 변수(vars로 불림)와 이러한 변수를 변경하는 함수를 정의합니다.
여기서 state는 `prompt`와 `image_url`로 구성됩니다. 또한 `processing`과 `complete`라는 불리언 값이 있습니다. 이 값들은 이미지 생성 중 버튼을 비활성화할 때와, 결과 이미지를 표시할 때를 나타냅니다.
### **Event Handlers**
```python
def get_image(self):
"""Get the image from the prompt."""
if self.prompt == "":
return rx.window_alert("Prompt Empty")
self.processing, self.complete = True, False
yield
response = openai_client.images.generate(
prompt=self.prompt, n=1, size="1024x1024"
)
self.image_url = response.data[0].url
self.processing, self.complete = False, True
```
State 내에서, state vars를 변경하는 이벤트 핸들러라고 불리는 함수를 정의합니다. 이벤트 핸들러는 Reflex에서 state를 변경하는 방법입니다. 버튼을 클릭하거나 텍스트 상자에 입력하는 것과 같이 사용자 동작에 응답하여 호출될 수 있습니다. 이러한 동작을 이벤트라고 합니다.
DALL·E. 앱에는 OpenAI API에서 이미지를 가져오는 `get_image` 이벤트 핸들러가 있습니다. 이벤트 핸들러의 중간에 `yield`를 사용하면 UI가 업데이트됩니다. 그렇지 않으면 UI는 이벤트 핸들러의 끝에서 업데이트됩니다.
### **Routing**
마지막으로, 앱을 정의합니다.
```python
app = rx.App()
```
앱의 루트에서 index 컴포넌트로 페이지를 추가합니다. 또한 페이지 미리보기/브라우저 탭에 표시될 제목도 추가합니다.
```python
app.add_page(index, title="DALL-E")
```
여러 페이지를 추가하여 멀티 페이지 앱을 만들 수 있습니다.
## 📑 자료
<div align="center">
📑 [문서](https://reflex.dev/docs/getting-started/introduction) | 🗞️ [블로그](https://reflex.dev/blog) | 📱 [컴포넌트 라이브러리](https://reflex.dev/docs/library) | 🖼️ [템플릿](https://reflex.dev/templates/) | 🛸 [배포](https://reflex.dev/docs/hosting/deploy-quick-start)
</div>
## ✅ 상태
Reflex는 2022년 12월 Pynecone이라는 이름으로 출시되었습니다.
2025년부터 [Reflex Cloud](https://cloud.reflex.dev)가 출시되어 Reflex 앱을 위한 최상의 호스팅 경험을 제공합니다. 우리는 계속해서 개발하고 더 많은 기능을 구현할 예정입니다.
Reflex는 매주 새로운 릴리즈와 기능을 제공합니다! 최신 정보를 확인하려면 :star: Star와 :eyes: Watch를 눌러 이 저장소를 확인하세요.
## 기여
우리는 모든 기여를 환영합니다! 아래는 Reflex 커뮤니티에 참여하는 좋은 방법입니다.
- **Discord 참여**: 우리의 [Discord](https://discord.gg/T5WSbC2YtQ)는 Reflex 프로젝트에 대한 도움을 받고 기여하는 방법을 논의하는 최고의 장소입니다.
- **GitHub Discussions**: 추가하고 싶은 기능이나 혼란스럽거나 해결이 필요한 것들에 대해 이야기하는 좋은 방법입니다.
- **GitHub Issues**: [Issues](https://github.com/reflex-dev/reflex/issues)는 버그를 보고하는 훌륭한 방법입니다. 또한, 기존의 이슈를 해결하고 PR을 제출할 수 있습니다.
우리는 능력이나 경험에 상관없이 적극적으로 기여자를 찾고 있습니다. 기여하려면 [CONTRIBUTING.md](https://github.com/reflex-dev/reflex/blob/main/CONTRIBUTING.md)를 확인하세요.
## 모든 기여자들에게 감사드립니다:
<a href="https://github.com/reflex-dev/reflex/graphs/contributors">
<img src="https://contrib.rocks/image?repo=reflex-dev/reflex" />
</a>
## License
Reflex는 오픈소스이며 [Apache License 2.0](/LICENSE)로 라이선스가 부여됩니다.
## /docs/pe/README.md
<div align="center">
<img src="/docs/images/reflex.svg" alt="Reflex Logo" width="300px">
<hr>
### **✨ برنامه های تحت وب قابل تنظیم، کارآمد تماما پایتونی که در چند ثانیه مستقر(دپلوی) میشود. ✨**
[](https://badge.fury.io/py/reflex)

[](https://reflex.dev/docs/getting-started/introduction)
[](https://pepy.tech/projects/reflex)
[](https://discord.gg/T5WSbC2YtQ)
</div>
---
[English](https://github.com/reflex-dev/reflex/blob/main/README.md) | [简体中文](https://github.com/reflex-dev/reflex/blob/main/docs/zh/zh_cn/README.md) | [繁體中文](https://github.com/reflex-dev/reflex/blob/main/docs/zh/zh_tw/README.md) | [Türkçe](https://github.com/reflex-dev/reflex/blob/main/docs/tr/README.md) | [हिंदी](https://github.com/reflex-dev/reflex/blob/main/docs/in/README.md) | [Português (Brasil)](https://github.com/reflex-dev/reflex/blob/main/docs/pt/pt_br/README.md) | [Italiano](https://github.com/reflex-dev/reflex/blob/main/docs/it/README.md) | [Español](https://github.com/reflex-dev/reflex/blob/main/docs/es/README.md) | [한국어](https://github.com/reflex-dev/reflex/blob/main/docs/kr/README.md) | [日本語](https://github.com/reflex-dev/reflex/blob/main/docs/ja/README.md) | [Deutsch](https://github.com/reflex-dev/reflex/blob/main/docs/de/README.md) | [Persian (پارسی)](https://github.com/reflex-dev/reflex/blob/main/docs/pe/README.md) | [Tiếng Việt](https://github.com/reflex-dev/reflex/blob/main/docs/vi/README.md)
---
# Reflex - رفلکس
رفلکس(Reflex) یک کتابخانه برای ساخت برنامه های وب فول استک تماما پایتونی است.
ویژگی های کلیدی:
- **تماما پایتونی** - فرانت اند و بک اند برنامه خود را همه در پایتون بنویسید، بدون نیاز به یادگیری جاوا اسکریپت.
- **انعطاف پذیری کامل** - شروع به کار با Reflex آسان است، اما می تواند به برنامه های پیچیده نیز تبدیل شود.
- **دپلوی فوری** - پس از ساخت، برنامه خود را با [یک دستور](https://reflex.dev/docs/hosting/deploy-quick-start/) دپلوی کنید یا آن را روی سرور خود میزبانی کنید.
برای آشنایی با نحوه عملکرد Reflex [صفحه معماری](https://reflex.dev/blog/2024-03-21-reflex-architecture/#the-reflex-architecture) را ببینید.
## ⚙️ Installation - نصب و راه اندازی
یک ترمینال را باز کنید و اجرا کنید (نیازمند Python 3.10+):
```bash
pip install reflex
```
## 🥳 اولین برنامه خود را ایجاد کنید
نصب `reflex` همچنین `reflex` در خط فرمان را نصب میکند.
با ایجاد یک پروژه جدید موفقیت آمیز بودن نصب را تست کنید. (`my_app_name` را با اسم پروژه خودتان جایگزین کنید):
```bash
mkdir my_app_name
cd my_app_name
reflex init
```
این دستور یک برنامه الگو(تمپلیت) را در فهرست(دایرکتوری) جدید شما مقداردهی اولیه می کند
می توانید این برنامه را در حالت توسعه(development) اجرا کنید:
```bash
reflex run
```
باید برنامه خود را در حال اجرا ببینید در http://localhost:3000.
اکنون میتوانید کد منبع را در «my_app_name/my_app_name.py» تغییر دهید. Reflex دارای تازهسازیهای سریعی است، بنابراین میتوانید تغییرات خود را بلافاصله پس از ذخیره کد خود مشاهده کنید.
## 🫧 Example App - برنامه نمونه
بیایید یک مثال بزنیم: ایجاد یک رابط کاربری برای تولید تصویر [DALL·E](https://platform.openai.com/docs/guides/images/image-generation?context=node). برای سادگی، ما فراخوانی میکنیم [OpenAI API](https://platform.openai.com/docs/api-reference/authentication), اما می توانید آن را با یک مدل ML که به صورت محلی اجرا می شود جایگزین کنید.
<div align="center">
<img src="/docs/images/dalle.gif" alt="A frontend wrapper for DALL·E, shown in the process of generating an image." width="550" />
</div>
در اینجا کد کامل برای ایجاد این پروژه آمده است. همه اینها در یک فایل پایتون انجام می شود!
```python
import reflex as rx
import openai
openai_client = openai.OpenAI()
class State(rx.State):
"""The app state."""
prompt = ""
image_url = ""
processing = False
complete = False
def get_image(self):
"""Get the image from the prompt."""
if self.prompt == "":
return rx.window_alert("Prompt Empty")
self.processing, self.complete = True, False
yield
response = openai_client.images.generate(
prompt=self.prompt, n=1, size="1024x1024"
)
self.image_url = response.data[0].url
self.processing, self.complete = False, True
def index():
return rx.center(
rx.vstack(
rx.heading("DALL-E", font_size="1.5em"),
rx.input(
placeholder="Enter a prompt..",
on_blur=State.set_prompt,
width="25em",
),
rx.button(
"Generate Image",
on_click=State.get_image,
width="25em",
loading=State.processing
),
rx.cond(
State.complete,
rx.image(src=State.image_url, width="20em"),
),
align="center",
),
width="100%",
height="100vh",
)
# Add state and page to the app.
app = rx.App()
app.add_page(index, title="Reflex:DALL-E")
```
## بیاید سادش کنیم
<div align="center">
<img src="docs/images/dalle_colored_code_example.png" alt="Explaining the differences between backend and frontend parts of the DALL-E app." width="900" />
</div>
### **Reflex UI - رابط کاربری رفلکس**
بیایید با رابط کاربری شروع کنیم.
```python
def index():
return rx.center(
...
)
```
تابع `index` قسمت فرانت اند برنامه را تعریف می کند.
ما از اجزای مختلفی مثل `center`, `vstack`, `input` و `button` استفاده میکنیم تا فرانت اند را بسازیم. اجزاء را می توان درون یکدیگر قرار داد
برای ایجاد طرح بندی های پیچیده می توانید از args کلمات کلیدی برای استایل دادن به آنها از CSS استفاده کنید.
رفلکس دارای [بیش از 60 جزء](https://reflex.dev/docs/library) برای کمک به شما برای شروع. ما به طور فعال اجزای بیشتری را اضافه می کنیم, و این خیلی آسان است که [اجزا خود را بسازید](https://reflex.dev/docs/wrapping-react/overview/).
### **State - حالت**
رفلکس رابط کاربری شما را به عنوان تابعی از وضعیت شما نشان می دهد.
```python
class State(rx.State):
"""The app state."""
prompt = ""
image_url = ""
processing = False
complete = False
```
حالت تمام متغیرها(variables) (به نام vars) را در یک برنامه که می توانند تغییر دهند و توابعی که آنها را تغییر می دهند تعریف می کند..
در اینجا حالت از یک `prompt` و `image_url` تشکیل شده است. همچنین دو بولی `processing` و `complete` برای نشان دادن زمان غیرفعال کردن دکمه (در طول تولید تصویر) و زمان نمایش تصویر نتیجه وجود دارد.
### **Event Handlers - کنترل کنندگان رویداد**
```python
def get_image(self):
"""Get the image from the prompt."""
if self.prompt == "":
return rx.window_alert("Prompt Empty")
self.processing, self.complete = True, False
yield
response = openai_client.images.generate(
prompt=self.prompt, n=1, size="1024x1024"
)
self.image_url = response.data[0].url
self.processing, self.complete = False, True
```
در داخل حالت، توابعی به نام کنترل کننده رویداد تعریف می کنیم که متغیرهای حالت را تغییر می دهند. کنترل کننده های رویداد راهی هستند که می توانیم وضعیت را در Reflex تغییر دهیم. آنها را می توان در پاسخ به اقدامات کاربر، مانند کلیک کردن روی یک دکمه یا تایپ کردن در یک متن، فراخوانی کرد. به این اعمال وقایع می گویند.
برنامه DALL·E ما دارای یک کنترل کننده رویداد، `get_image` است که این تصویر را از OpenAI API دریافت می کند. استفاده از `yield` در وسط کنترلکننده رویداد باعث بهروزرسانی رابط کاربری میشود. در غیر این صورت رابط کاربری در پایان کنترل کننده رویداد به روز می شود.
### **Routing - مسیریابی**
بالاخره اپلیکیشن خود را تعریف می کنیم.
```python
app = rx.App()
```
ما یک صفحه از root برنامه را به جزء index اضافه می کنیم. ما همچنین عنوانی را اضافه می کنیم که در برگه پیش نمایش/مرورگر صفحه نمایش داده می شود.
```python
app.add_page(index, title="DALL-E")
```
با افزودن صفحات بیشتر می توانید یک برنامه چند صفحه ای ایجاد کنید.
## 📑 Resources - منابع
<div align="center">
📑 [اسناد](https://reflex.dev/docs/getting-started/introduction) | 🗞️ [وبلاگ](https://reflex.dev/blog) | 📱 [کتابخانه جزء](https://reflex.dev/docs/library) | 🖼️ [قالب ها](https://reflex.dev/templates/) | 🛸 [استقرار](https://reflex.dev/docs/hosting/deploy-quick-start)
</div>
## ✅ Status - وضعیت
رفلکس(reflex) در دسامبر 2022 با نام Pynecone راه اندازی شد.
از سال 2025، [Reflex Cloud](https://cloud.reflex.dev) برای فراهم کردن بهترین تجربه میزبانی برای برنامه های Reflex راهاندازی شده است. ما به توسعه آن ادامه خواهیم داد و ویژگیهای بیشتری را پیادهسازی خواهیم کرد.
رفلکس(reflex) هر هفته نسخه ها و ویژگی های جدیدی دارد! مطمئن شوید که :star: ستاره و :eyes: این مخزن را تماشا کنید تا به روز بمانید.
## Contributing - مشارکت کردن
ما از مشارکت در هر اندازه استقبال می کنیم! در زیر چند راه خوب برای شروع در انجمن رفلکس آورده شده است.
- **به Discord ما بپیوندید**: [Discord](https://discord.gg/T5WSbC2YtQ) ما بهترین مکان برای دریافت کمک در مورد پروژه Reflex و بحث در مورد اینکه چگونه می توانید کمک کنید است.
- **بحث های GitHub**: راهی عالی برای صحبت در مورد ویژگی هایی که می خواهید اضافه کنید یا چیزهایی که گیج کننده هستند/نیاز به توضیح دارند.
- **قسمت مشکلات GitHub**: [قسمت مشکلات](https://github.com/reflex-dev/reflex/issues) یک راه عالی برای گزارش اشکال هستند. علاوه بر این، می توانید یک مشکل موجود را حل کنید و یک PR(pull request) ارسال کنید.
ما فعالانه به دنبال مشارکت کنندگان هستیم، فارغ از سطح مهارت یا تجربه شما. برای مشارکت [CONTRIBUTING.md](https://github.com/reflex-dev/reflex/blob/main/CONTRIBUTING.md) را بررسی کنید.
## All Thanks To Our Contributors - با تشکر از همکاران ما:
<a href="https://github.com/reflex-dev/reflex/graphs/contributors">
<img src="https://contrib.rocks/image?repo=reflex-dev/reflex" />
</a>
## License - مجوز
رفلکس متن باز و تحت مجوز [Apache License 2.0](/LICENSE) است.
## /docs/pt/pt_br/README.md
<div align="center">
<img src="/docs/images/reflex.svg" alt="Reflex Logo" width="300px">
<hr>
### **✨ Web apps customizáveis, performáticos, em Python puro. Faça deploy em segundos. ✨**
[](https://badge.fury.io/py/reflex)

[](https://reflex.dev/docs/getting-started/introduction)
[](https://pepy.tech/projects/reflex)
[](https://discord.gg/T5WSbC2YtQ)
</div>
---
[English](https://github.com/reflex-dev/reflex/blob/main/README.md) | [简体中文](https://github.com/reflex-dev/reflex/blob/main/docs/zh/zh_cn/README.md) | [繁體中文](https://github.com/reflex-dev/reflex/blob/main/docs/zh/zh_tw/README.md) | [Türkçe](https://github.com/reflex-dev/reflex/blob/main/docs/tr/README.md) | [हिंदी](https://github.com/reflex-dev/reflex/blob/main/docs/in/README.md) | [Português (Brasil)](https://github.com/reflex-dev/reflex/blob/main/docs/pt/pt_br/README.md) | [Italiano](https://github.com/reflex-dev/reflex/blob/main/docs/it/README.md) | [Español](https://github.com/reflex-dev/reflex/blob/main/docs/es/README.md) | [한국어](https://github.com/reflex-dev/reflex/blob/main/docs/kr/README.md) | [日本語](https://github.com/reflex-dev/reflex/blob/main/docs/ja/README.md) | [Deutsch](https://github.com/reflex-dev/reflex/blob/main/docs/de/README.md) | [Persian (پارسی)](https://github.com/reflex-dev/reflex/blob/main/docs/pe/README.md) | [Tiếng Việt](https://github.com/reflex-dev/reflex/blob/main/docs/vi/README.md)
---
# Reflex
Reflex é uma biblioteca para construir aplicações web full-stack em Python puro.
Principais características:
- **Python Puro** - Escreva o frontend e o backend da sua aplicação inteiramente em Python, sem necessidade de aprender Javascript.
- **Flexibilidade Total** - O Reflex é fácil de começar a usar, mas também pode escalar para aplicações complexas.
- **Deploy Instantâneo** - Após a construção, faça o deploy da sua aplicação com um [único comando](https://reflex.dev/docs/hosting/deploy-quick-start/) ou hospede-a em seu próprio servidor.
Veja nossa [página de arquitetura](https://reflex.dev/blog/2024-03-21-reflex-architecture/#the-reflex-architecture) para aprender como o Reflex funciona internamente.
## ⚙️ Instalação
Abra um terminal e execute (Requer Python 3.10+):
```bash
pip install reflex
```
## 🥳 Crie o seu primeiro app
Instalar `reflex` também instala a ferramenta de linha de comando `reflex`.
Crie um novo projeto para verificar se a instalação foi bem sucedida. (Mude `nome_do_meu_app` com o nome do seu projeto):
```bash
mkdir nome_do_meu_app
cd nome_do_meu_app
reflex init
```
Este comando inicializa um app base no seu novo diretório.
Você pode executar este app em modo desenvolvimento:
```bash
reflex run
```
Você deve conseguir verificar seu app sendo executado em http://localhost:3000.
Agora, você pode modificar o código fonte em `nome_do_meu_app/nome_do_meu_app.py`. O Reflex apresenta recarregamento rápido para que você possa ver suas mudanças instantaneamente quando você salva o seu código.
## 🫧 Exemplo de App
Veja o seguinte exemplo: criar uma interface de criação de imagens por meio do [DALL·E](https://platform.openai.com/docs/guides/images/image-generation?context=node). Para fins de simplicidade, vamos apenas chamar a [API da OpenAI](https://platform.openai.com/docs/api-reference/authentication), mas você pode substituir esta solução por um modelo de ML executado localmente.
<div align="center">
<img src="/docs/images/dalle.gif" alt="Um encapsulador frontend para o DALL-E, mostrado no processo de criação de uma imagem." width="550" />
</div>
Aqui está o código completo para criar este projeto. Isso tudo foi feito apenas em um arquivo Python!
```python
import reflex as rx
import openai
openai_client = openai.OpenAI()
class State(rx.State):
"""Estado da aplicação."""
prompt = ""
image_url = ""
processing = False
complete = False
def get_image(self):
"""Obtenção da imagem a partir do prompt."""
if self.prompt == "":
return rx.window_alert("Prompt Empty")
self.processing, self.complete = True, False
yield
response = openai_client.images.generate(
prompt=self.prompt, n=1, size="1024x1024"
)
self.image_url = response.data[0].url
self.processing, self.complete = False, True
def index():
return rx.center(
rx.vstack(
rx.heading("DALL-E", font_size="1.5em"),
rx.input(
placeholder="Enter a prompt..",
on_blur=State.set_prompt,
width="25em",
),
rx.button(
"Generate Image",
on_click=State.get_image,
width="25em",
loading=State.processing
),
rx.cond(
State.complete,
rx.image(src=State.image_url, width="20em"),
),
align="center",
),
width="100%",
height="100vh",
)
# Adição do estado e da página no app.
app = rx.App()
app.add_page(index, title="Reflex:DALL-E")
```
## Vamos por partes.
<div align="center">
<img src="/docs/images/dalle_colored_code_example.png" alt="Explicando as diferenças entre as partes de backend e frontend do app DALL-E." width="900" />
</div>
### **Reflex UI**
Vamos começar com a UI (Interface de Usuário)
```python
def index():
return rx.center(
...
)
```
Esta função `index` define o frontend do app.
Usamos diferentes componentes, como `center`, `vstack`, `input` e `button`, para construir o frontend. Componentes podem ser aninhados um no do outro
para criar layouts mais complexos. E você pode usar argumentos de chave-valor para estilizá-los com todo o poder do CSS.
O Reflex vem com [60+ componentes nativos](https://reflex.dev/docs/library) para te ajudar a começar. Estamos adicionando ativamente mais componentes, e é fácil [criar seus próprios componentes](https://reflex.dev/docs/wrapping-react/overview/).
### **Estado**
O Reflex representa a sua UI como uma função do seu estado.
```python
class State(rx.State):
"""Estado da aplicação."""
prompt = ""
image_url = ""
processing = False
complete = False
```
O estado define todas as variáveis (chamadas de vars) em um app que podem mudar e as funções que as alteram.
Aqui, o estado é composto por um `prompt` e uma `image_url`. Há também os booleanos `processing` e `complete` para indicar quando desabilitar o botão (durante a geração da imagem) e quando mostrar a imagem resultante.
### **Handlers de Eventos**
```python
def get_image(self):
"""Obtenção da imagem a partir do prompt."""
if self.prompt == "":
return rx.window_alert("Prompt Empty")
self.processing, self.complete = True, False
yield
response = openai_client.images.generate(
prompt=self.prompt, n=1, size="1024x1024"
)
self.image_url = response.data[0].url
self.processing, self.complete = False, True
```
Dentro do estado, são definidas funções chamadas de Handlers de Eventos, que podem mudar as variáveis do estado. Handlers de Eventos são a forma com a qual podemos modificar o estado dentro do Reflex. Eles podem ser chamados como resposta a uma ação do usuário, como o clique de um botão ou a escrita em uma caixa de texto. Estas ações são chamadas de eventos.
Nosso app DALL-E possui um Handler de Evento chamado `get_image`, que obtêm a imagem da API da OpenAI. Usar `yield` no meio de um Handler de Evento causa a atualização da UI do seu app. Caso contrário, a UI seria atualizada no fim da execução de um Handler de Evento.
### **Rotas**
Finalmente, definimos nosso app.
```python
app = rx.App()
```
Adicionamos uma página na raíz do app, apontando para o componente index. Também adicionamos um título que irá aparecer na visualização da página/aba do navegador.
```python
app.add_page(index, title="DALL-E")
```
Você pode criar um app com múltiplas páginas adicionando mais páginas.
## 📑 Recursos
<div align="center">
📑 [Docs](https://reflex.dev/docs/getting-started/introduction) | 🗞️ [Blog](https://reflex.dev/blog) | 📱 [Biblioteca de Componentes](https://reflex.dev/docs/library) | 🖼️ [Templates](https://reflex.dev/templates/) | 🛸 [Deployment](https://reflex.dev/docs/hosting/deploy-quick-start)
</div>
## ✅ Status
O Reflex foi lançado em Dezembro de 2022 com o nome Pynecone.
A partir de 2025, o [Reflex Cloud](https://cloud.reflex.dev) foi lançado para fornecer a melhor experiência de hospedagem para apps Reflex. Continuaremos a desenvolvê-lo e implementar mais recursos.
O Reflex tem novas versões e recursos chegando toda semana! Certifique-se de marcar com :star: estrela e :eyes: observar este repositório para se manter atualizado.
## Contribuições
Nós somos abertos a contribuições de qualquer tamanho! Abaixo, seguem algumas boas formas de começar a contribuir para a comunidade do Reflex.
- **Entre no nosso Discord**: Nosso [Discord](https://discord.gg/T5WSbC2YtQ) é o melhor lugar para conseguir ajuda no seu projeto Reflex e para discutir como você pode contribuir.
- **Discussões no GitHub**: Uma boa forma de conversar sobre funcionalidades que você gostaria de ver ou coisas que ainda estão confusas/exigem ajuda.
- **Issues no GitHub**: [Issues](https://github.com/reflex-dev/reflex/issues) são uma excelente forma de reportar bugs. Além disso, você pode tentar resolver alguma issue existente e enviar um PR.
Estamos ativamente buscando novos contribuidores, não importa o seu nível de habilidade ou experiência. Para contribuir, confira [CONTRIBUTING.md](https://github.com/reflex-dev/reflex/blob/main/CONTRIBUTING.md).
## Todo Agradecimento aos Nossos Contribuidores:
<a href="https://github.com/reflex-dev/reflex/graphs/contributors">
<img src="https://contrib.rocks/image?repo=reflex-dev/reflex" />
</a>
## Licença
O Reflex é de código aberto e licenciado sob a [Apache License 2.0](/LICENSE).
## /docs/tr/README.md
<div align="center">
<img src="/docs/images/reflex.svg" alt="Reflex Logo" width="300px">
<hr>
### **✨ Saf Python'da performanslı, özelleştirilebilir web uygulamaları. Saniyeler içinde dağıtın. ✨**
[](https://badge.fury.io/py/reflex)

[](https://reflex.dev/docs/getting-started/introduction)
[](https://pepy.tech/projects/reflex)
[](https://discord.gg/T5WSbC2YtQ)
</div>
---
[English](https://github.com/reflex-dev/reflex/blob/main/README.md) | [简体中文](https://github.com/reflex-dev/reflex/blob/main/docs/zh/zh_cn/README.md) | [繁體中文](https://github.com/reflex-dev/reflex/blob/main/docs/zh/zh_tw/README.md) | [Türkçe](https://github.com/reflex-dev/reflex/blob/main/docs/tr/README.md) | [हिंदी](https://github.com/reflex-dev/reflex/blob/main/docs/in/README.md) | [Português (Brasil)](https://github.com/reflex-dev/reflex/blob/main/docs/pt/pt_br/README.md) | [Italiano](https://github.com/reflex-dev/reflex/blob/main/docs/it/README.md) | [Español](https://github.com/reflex-dev/reflex/blob/main/docs/es/README.md) | [한국어](https://github.com/reflex-dev/reflex/blob/main/docs/kr/README.md) | [日本語](https://github.com/reflex-dev/reflex/blob/main/docs/ja/README.md) | [Deutsch](https://github.com/reflex-dev/reflex/blob/main/docs/de/README.md) | [Persian (پارسی)](https://github.com/reflex-dev/reflex/blob/main/docs/pe/README.md) | [Tiếng Việt](https://github.com/reflex-dev/reflex/blob/main/docs/vi/README.md)
---
# Reflex
Reflex, saf Python'da tam yığın web uygulamaları oluşturmak için bir kütüphanedir.
Temel özellikler:
- **Saf Python** - Uygulamanızın ön uç ve arka uç kısımlarının tamamını Python'da yazın, Javascript öğrenmenize gerek yok.
- **Tam Esneklik** - Reflex ile başlamak kolaydır, ancak karmaşık uygulamalara da ölçeklenebilir.
- **Anında Dağıtım** - Oluşturduktan sonra, uygulamanızı [tek bir komutla](https://reflex.dev/docs/hosting/deploy-quick-start/) dağıtın veya kendi sunucunuzda barındırın.
Reflex'in perde arkasında nasıl çalıştığını öğrenmek için [mimari sayfamıza](https://reflex.dev/blog/2024-03-21-reflex-architecture/#the-reflex-architecture) göz atın.
## ⚙️ Kurulum
Bir terminal açın ve çalıştırın (Python 3.10+ gerekir):
```bash
pip install reflex
```
## 🥳 İlk Uygulamanı Oluştur
`reflex`'i kurduğunuzda `reflex` komut satırı aracınıda kurmuş olursunuz.
Kurulumun başarılı olduğunu test etmek için yeni bir proje oluşturun. (`my_app_name`'i proje ismiyle değiştirin.):
```bash
mkdir my_app_name
cd my_app_name
reflex init
```
Bu komut ile birlikte yeni oluşturduğunuz dizinde bir şablon uygulaması oluşturur.
Uygulamanızı geliştirme modunda başlatabilirsiniz:
```bash
reflex run
```
Uygulamanızın http://localhost:3000 adresinde çalıştığını görmelisiniz.
Şimdi `my_app_name/my_app_name.py` yolundaki kaynak kodu düzenleyebilirsiniz. Reflex'in hızlı yenileme özelliği vardır, böylece kodunuzu kaydettiğinizde değişikliklerinizi anında görebilirsiniz.
## 🫧 Örnek Uygulama
Bir örnek üzerinden gidelim: [DALL·E](https://platform.openai.com/docs/guides/images/image-generation?context=node) kullanarak bir görüntü oluşturma arayüzü oluşturalım. Basit olması açısından, yalnızca [OpenAI API](https://platform.openai.com/docs/api-reference/authentication)'ını kullanıyoruz, ancak bunu yerel olarak çalıştırılan bir ML modeliyle değiştirebilirsiniz.
<div align="center">
<img src="/docs/images/dalle.gif" alt="A frontend wrapper for DALL·E, shown in the process of generating an image." width="550" />
</div>
İşte bunu oluşturmak için kodun tamamı. Her şey sadece bir Python dosyasıyla hazırlandı!
```python
import reflex as rx
import openai
openai_client = openai.OpenAI()
class State(rx.State):
"""Uygulama durumu."""
prompt = ""
image_url = ""
processing = False
complete = False
def get_image(self):
"""Prompt'tan görüntüyü alın."""
if self.prompt == "":
return rx.window_alert("Prompt Empty")
self.processing, self.complete = True, False
yield
response = openai_client.images.generate(
prompt=self.prompt, n=1, size="1024x1024"
)
self.image_url = response.data[0].url
self.processing, self.complete = False, True
def index():
return rx.center(
rx.vstack(
rx.heading("DALL-E", font_size="1.5em"),
rx.input(
placeholder="Enter a prompt..",
on_blur=State.set_prompt,
width="25em",
),
rx.button(
"Generate Image",
on_click=State.get_image,
width="25em",
loading=State.processing
),
rx.cond(
State.complete,
rx.image(src=State.image_url, width="20em"),
),
align="center",
),
width="100%",
height="100vh",
)
# Sayfa ve durumu uygulamaya ekleyin.
app = rx.App()
app.add_page(index, title="Reflex:DALL-E")
```
## Daha Detaylı İceleyelim
<div align="center">
<img src="/docs/images/dalle_colored_code_example.png" alt="DALL-E uygulamasının arka uç ve ön uç kısımları arasındaki farkları açıklama." width="900" />
</div>
### **Reflex UI**
UI (Kullanıcı Arayüzü) ile başlayalım.
```python
def index():
return rx.center(
...
)
```
Bu `index` fonkisyonu uygulamanın frontend'ini tanımlar.
Frontend'i oluşturmak için `center`, `vstack`, `input`, ve `button` gibi farklı bileşenler kullanıyoruz. Karmaşık düzenler oluşturmak için bileşenleri birbirinin içine yerleştirilebiliriz. Ayrıca bunları CSS'nin tüm gücüyle şekillendirmek için anahtar kelime argümanları kullanabilirsiniz.
Reflex, işinizi kolaylaştırmak için [60'tan fazla dahili bileşen](https://reflex.dev/docs/library) içerir. Aktif olarak yeni bileşen ekliyoruz ve [kendi bileşenlerinizi oluşturmak](https://reflex.dev/docs/wrapping-react/overview/) oldukça kolay.
### **Durum (State)**
Reflex arayüzünüzü durumunuzun bir fonksiyonu olarak temsil eder.
```python
class State(rx.State):
"""Uygulama durumu."""
prompt = ""
image_url = ""
processing = False
complete = False
```
Durum (State), bir uygulamadaki değişebilen tüm değişkenleri (vars olarak adlandırılır) ve bunları değiştiren fonksiyonları tanımlar.
Burada durum `prompt` ve `image_url`inden oluşur. Ayrıca düğmenin ne zaman devre dışı bırakılacağını (görüntü oluşturma sırasında) ve görüntünün ne zaman gösterileceğini belirtmek için `processing` ve `complete` booleanları da vardır.
### **Olay İşleyicileri (Event Handlers)**
```python
def get_image(self):
"""Prompt'tan görüntüyü alın."""
if self.prompt == "":
return rx.window_alert("Prompt Empty")
self.processing, self.complete = True, False
yield
response = openai_client.images.generate(
prompt=self.prompt, n=1, size="1024x1024"
)
self.image_url = response.data[0].url
self.processing, self.complete = False, True
```
Durum içinde, durum değişkenlerini değiştiren olay işleyicileri adı verilen fonksiyonları tanımlarız. Olay işleyicileri, Reflex'te durumu değiştirebilmemizi sağlar. Bir düğmeye tıklamak veya bir metin kutusuna yazı yazmak gibi kullanıcı eylemlerine yanıt olarak çağrılabilirler. Bu eylemlere olay denir.
DALL·E uygulamamız OpenAI API'ından bu görüntüyü almak için `get_image` adlı bir olay işleyicisine sahiptir. Bir olay işleyicisinin ortasında `yield`ın kullanılması UI'ın güncellenmesini sağlar. Aksi takdirde UI olay işleyicisinin sonunda güncellenecektir.
### **Yönlendirme (Routing)**
En sonunda uygulamamızı tanımlıyoruz.
```python
app = rx.App()
```
Uygulamamızın kök dizinine index bileşeninden bir sayfa ekliyoruz. Ayrıca sayfa önizlemesinde/tarayıcı sekmesinde görünecek bir başlık ekliyoruz.
```python
app.add_page(index, title="DALL-E")
```
Daha fazla sayfa ekleyerek çok sayfalı bir uygulama oluşturabilirsiniz.
## 📑 Kaynaklar
<div align="center">
📑 [Docs](https://reflex.dev/docs/getting-started/introduction) | 🗞️ [Blog](https://reflex.dev/blog) | 📱 [Component Library](https://reflex.dev/docs/library) | 🖼️ [Templates](https://reflex.dev/templates/) | 🛸 [Deployment](https://reflex.dev/docs/hosting/deploy-quick-start)
</div>
## ✅ Durum
Reflex, Aralık 2022'de Pynecone adıyla piyasaya sürüldü.
2025'in başından itibaren, Reflex uygulamaları için en iyi barındırma deneyimini sunmak amacıyla [Reflex Cloud](https://cloud.reflex.dev) hizmete girmiştir. Bunu geliştirmeye ve daha fazla özellik eklemeye devam edeceğiz.
Reflex'in her hafta yeni sürümleri ve özellikleri geliyor! Güncel kalmak için bu depoyu :star: yıldızlamayı ve :eyes: izlediğinizden emin olun.
## Katkı
Her boyuttaki katkıları memnuniyetle karşılıyoruz! Aşağıda Reflex topluluğuna adım atmanın bazı yolları mevcut.
- **Discord Kanalımıza Katılın**: [Discord'umuz](https://discord.gg/T5WSbC2YtQ), Reflex projeniz hakkında yardım almak ve nasıl katkıda bulunabileceğinizi tartışmak için en iyi yerdir.
- **GitHub Discussions**: Eklemek istediğiniz özellikler veya kafa karıştırıcı, açıklığa kavuşturulması gereken şeyler hakkında konuşmanın harika bir yolu.
- **GitHub Issues**: [Issues](https://github.com/reflex-dev/reflex/issues) hataları bildirmenin mükemmel bir yoludur. Ayrıca mevcut bir sorunu deneyip çözebilir ve bir PR (Pull Requests) gönderebilirsiniz.
Beceri düzeyiniz veya deneyiminiz ne olursa olsun aktif olarak katkıda bulunacak kişiler arıyoruz. Katkı sağlamak için katkı sağlama rehberimize bakabilirsiniz: [CONTRIBUTING.md](https://github.com/reflex-dev/reflex/blob/main/CONTRIBUTING.md)
## Hepsi Katkıda Bulunanlar Sayesinde:
<a href="https://github.com/reflex-dev/reflex/graphs/contributors">
<img src="https://contrib.rocks/image?repo=reflex-dev/reflex" />
</a>
## Lisans
Reflex açık kaynaklıdır ve [Apache License 2.0](/LICENSE) altında lisanslıdır.
## /docs/vi/README.md
<div align="center">
<img src="/docs/images/reflex.svg" alt="Reflex Logo" width="300px">
<hr>
### **✨ Ứng dụng web hiệu suất cao, tùy chỉnh bằng Python thuần. Deploy trong vài giây. ✨**
[](https://badge.fury.io/py/reflex)

[](https://reflex.dev/docs/getting-started/introduction)
[](https://pepy.tech/projects/reflex)
[](https://discord.gg/T5WSbC2YtQ)
</div>
---
[English](https://github.com/reflex-dev/reflex/blob/main/README.md) | [简体中文](https://github.com/reflex-dev/reflex/blob/main/docs/zh/zh_cn/README.md) | [繁體中文](https://github.com/reflex-dev/reflex/blob/main/docs/zh/zh_tw/README.md) | [Türkçe](https://github.com/reflex-dev/reflex/blob/main/docs/tr/README.md) | [हिंदी](https://github.com/reflex-dev/reflex/blob/main/docs/in/README.md) | [Português (Brasil)](https://github.com/reflex-dev/reflex/blob/main/docs/pt/pt_br/README.md) | [Italiano](https://github.com/reflex-dev/reflex/blob/main/docs/it/README.md) | [Español](https://github.com/reflex-dev/reflex/blob/main/docs/es/README.md) | [한국어](https://github.com/reflex-dev/reflex/blob/main/docs/kr/README.md) | [日本語](https://github.com/reflex-dev/reflex/blob/main/docs/ja/README.md) | [Deutsch](https://github.com/reflex-dev/reflex/blob/main/docs/de/README.md) | [Persian (پارسی)](https://github.com/reflex-dev/reflex/blob/main/docs/pe/README.md) | [Tiếng Việt](https://github.com/reflex-dev/reflex/blob/main/docs/vi/README.md)
---
# Reflex
Reflex là một thư viện để xây dựng ứng dụng web toàn bộ bằng Python thuần.
Các tính năng chính:
- **Python thuần tuý** - Viết toàn bộ ứng dụng cả backend và frontend hoàn toàn bằng Python, không cần học JavaScript.
- **Full Flexibility** - Reflex dễ dàng để bắt đầu, nhưng cũng có thể mở rộng lên các ứng dụng phức tạp.
- **Deploy Instantly** - Sau khi xây dựng ứng dụng, bạn có thể triển khai bằng [một dòng lệnh](https://reflex.dev/docs/hosting/deploy-quick-start/) hoặc triển khai trên server của riêng bạn.
Đọc [bài viết về kiến trúc hệ thống](https://reflex.dev/blog/2024-03-21-reflex-architecture/#the-reflex-architecture) để hiểu rõ các hoạt động của Reflex.
## ⚙️ Cài đặt
Mở cửa sổ lệnh và chạy (Yêu cầu Python phiên bản 3.10+):
```bash
pip install reflex
```
## 🥳 Tạo ứng dụng đầu tiên
Cài đặt `reflex` cũng như cài đặt công cụ dòng lệnh `reflex`.
Kiểm tra việc cài đặt đã thành công hay chưa bằng cách tạo mới một ứng dụng. (Thay `my_app_name` bằng tên ứng dụng của bạn):
```bash
mkdir my_app_name
cd my_app_name
reflex init
```
Lệnh này tạo ra một ứng dụng mẫu trong một thư mục mới.
Bạn có thể chạy ứng dụng ở chế độ phát triển.
```bash
reflex run
```
Bạn có thể xem ứng dụng của bạn ở địa chỉ http://localhost:3000.
Bạn có thể thay đổi mã nguồn ở `my_app_name/my_app_name.py`. Reflex nhanh chóng làm mới và bạn có thể thấy thay đổi trên ứng dụng của bạn ngay lập tức khi bạn lưu file.
## 🫧 Ứng dụng ví dụ
Bắt đầu với ví dụ: tạo một ứng dụng tạo ảnh bằng [DALL·E](https://platform.openai.com/docs/guides/images/image-generation?context=node). Để cho đơn giản, chúng ta sẽ sử dụng [OpenAI API](https://platform.openai.com/docs/api-reference/authentication), nhưng bạn có thể sử dụng model của chính bạn được triển khai trên local.
<div align="center">
<img src="/docs/images/dalle.gif" alt="A frontend wrapper for DALL·E, shown in the process of generating an image." width="550" />
</div>
Đây là toàn bộ đoạn mã để xây dựng ứng dụng trên. Nó được viết hoàn toàn trong một file Python!
```python
import reflex as rx
import openai
openai_client = openai.OpenAI()
class State(rx.State):
"""The app state."""
prompt = ""
image_url = ""
processing = False
complete = False
def get_image(self):
"""Get the image from the prompt."""
if self.prompt == "":
return rx.window_alert("Prompt Empty")
self.processing, self.complete = True, False
yield
response = openai_client.images.generate(
prompt=self.prompt, n=1, size="1024x1024"
)
self.image_url = response.data[0].url
self.processing, self.complete = False, True
def index():
return rx.center(
rx.vstack(
rx.heading("DALL-E", font_size="1.5em"),
rx.input(
placeholder="Enter a prompt..",
on_blur=State.set_prompt,
width="25em",
),
rx.button(
"Generate Image",
on_click=State.get_image,
width="25em",
loading=State.processing
),
rx.cond(
State.complete,
rx.image(src=State.image_url, width="20em"),
),
align="center",
),
width="100%",
height="100vh",
)
# Add state and page to the app.
app = rx.App()
app.add_page(index, title="Reflex:DALL-E")
```
## Hãy phân tích chi tiết.
<div align="center">
<img src="/docs/images/dalle_colored_code_example.png" alt="Explaining the differences between backend and frontend parts of the DALL-E app." width="900" />
</div>
### **Reflex UI**
Bắt đầu với giao diện chính.
```python
def index():
return rx.center(
...
)
```
Hàm `index` định nghĩa phần giao diện chính của ứng dụng.
Chúng tôi sử dụng các component (thành phần) khác nhau như `center`, `vstack`, `input` và `button` để xây dựng giao diện phía trước.
Các component có thể được lồng vào nhau để tạo ra các bố cục phức tạp. Và bạn cũng có thể sử dụng từ khoá `args` để tận dụng đầy đủ sức mạnh của CSS.
Reflex có đến hơn [60 component được xây dựng sẵn](https://reflex.dev/docs/library) để giúp bạn bắt đầu. Chúng ta có thể tạo ra một component mới khá dễ dàng, thao khảo: [xây dựng component của riêng bạn](https://reflex.dev/docs/wrapping-react/overview/).
### **State**
Reflex biểu diễn giao diện bằng các hàm của state (trạng thái).
```python
class State(rx.State):
"""The app state."""
prompt = ""
image_url = ""
processing = False
complete = False
```
Một state định nghĩa các biến (được gọi là vars) có thể thay đổi trong một ứng dụng và cho phép các hàm có thể thay đổi chúng.
Tại đây state được cấu thành từ một `prompt` và `image_url`.
Có cũng những biến boolean `processing` và `complete`
để chỉ ra khi nào tắt nút (trong quá trình tạo hình ảnh)
và khi nào hiển thị hình ảnh kết quả.
### **Event Handlers**
```python
def get_image(self):
"""Get the image from the prompt."""
if self.prompt == "":
return rx.window_alert("Prompt Empty")
self.processing, self.complete = True, False
yield
response = openai_client.images.generate(
prompt=self.prompt, n=1, size="1024x1024"
)
self.image_url = response.data[0].url
self.processing, self.complete = False, True
```
Với các state, chúng ta định nghĩa các hàm có thể thay đổi state vars được gọi là event handlers. Event handler là cách chúng ta có thể thay đổi state trong Reflex. Chúng có thể là phản hồi khi người dùng thao tác, chằng hạn khi nhấn vào nút hoặc khi đang nhập trong text box. Các hành động này được gọi là event.
Ứng dụng DALL·E. của chúng ta có một event handler, `get_image` để lấy hình ảnh từ OpenAI API. Sử dụng từ khoá `yield` in ở giữa event handler để cập nhật giao diện. Hoặc giao diện có thể cập nhật ở cuối event handler.
### **Routing**
Cuối cùng, chúng ta định nghĩa một ứng dụng.
```python
app = rx.App()
```
Chúng ta thêm một trang ở đầu ứng dụng bằng index component. Chúng ta cũng thêm tiêu đề của ứng dụng để hiển thị lên trình duyệt.
```python
app.add_page(index, title="DALL-E")
```
Bạn có thể tạo một ứng dụng nhiều trang bằng cách thêm trang.
## 📑 Tài liệu
<div align="center">
📑 [Docs](https://reflex.dev/docs/getting-started/introduction) | 🗞️ [Blog](https://reflex.dev/blog) | 📱 [Component Library](https://reflex.dev/docs/library) | 🖼️ [Templates](https://reflex.dev/templates/) | 🛸 [Deployment](https://reflex.dev/docs/hosting/deploy-quick-start)
</div>
## ✅ Status
Reflex phát hành vào tháng 12/2022 với tên là Pynecone.
Từ năm 2025, [Reflex Cloud](https://cloud.reflex.dev) đã ra mắt để cung cấp trải nghiệm lưu trữ tốt nhất cho các ứng dụng Reflex. Chúng tôi sẽ tiếp tục phát triển và triển khai thêm nhiều tính năng mới.
Reflex ra phiên bản mới với các tính năng mới hàng tuần! Hãy :star: star và :eyes: watch repo này để thấy các cập nhật mới nhất.
## Contributing
Chúng tôi chào đón mọi đóng góp dù lớn hay nhỏ. Dưới đây là các cách để bắt đầu với cộng đồng Reflex.
- **Discord**: [Discord](https://discord.gg/T5WSbC2YtQ) của chúng tôi là nơi tốt nhất để nhờ sự giúp đỡ và thảo luận các bạn có thể đóng góp.
- **GitHub Discussions**: Là cách tốt nhất để thảo luận về các tính năng mà bạn có thể đóng góp hoặc những điều bạn chưa rõ.
- **GitHub Issues**: [Issues](https://github.com/reflex-dev/reflex/issues) là nơi tốt nhất để thông báo. Ngoài ra bạn có thể sửa chữa các vấn đề bằng cách tạo PR.
Chúng tôi luôn sẵn sàng tìm kiếm các contributor, bất kể kinh nghiệm. Để tham gia đóng góp, xin mời xem
[CONTRIBUTING.md](https://github.com/reflex-dev/reflex/blob/main/CONTRIBUTING.md)
## Xin cảm ơn các Contributors:
<a href="https://github.com/reflex-dev/reflex/graphs/contributors">
<img src="https://contrib.rocks/image?repo=reflex-dev/reflex" />
</a>
## License
Reflex là mã nguồn mở và sử dụng giấy phép [Apache License 2.0](/LICENSE).
## /docs/zh/zh_cn/README.md
<div align="center">
<img src="/docs/images/reflex.svg" alt="Reflex Logo" width="300px">
<hr>
### **✨ 使用 Python 创建高效且可自定义的网页应用程序,几秒钟内即可部署.✨**
[](https://badge.fury.io/py/reflex)

[](https://reflex.dev/docs/getting-started/introduction)
[](https://pepy.tech/projects/reflex)
[](https://discord.gg/T5WSbC2YtQ)
</div>
---
[English](https://github.com/reflex-dev/reflex/blob/main/README.md) | [简体中文](https://github.com/reflex-dev/reflex/blob/main/docs/zh/zh_cn/README.md) | [繁體中文](https://github.com/reflex-dev/reflex/blob/main/docs/zh/zh_tw/README.md) | [Türkçe](https://github.com/reflex-dev/reflex/blob/main/docs/tr/README.md) | [हिंदी](https://github.com/reflex-dev/reflex/blob/main/docs/in/README.md) | [Português (Brasil)](https://github.com/reflex-dev/reflex/blob/main/docs/pt/pt_br/README.md) | [Italiano](https://github.com/reflex-dev/reflex/blob/main/docs/it/README.md) | [Español](https://github.com/reflex-dev/reflex/blob/main/docs/es/README.md) | [한국어](https://github.com/reflex-dev/reflex/blob/main/docs/kr/README.md) | [日本語](https://github.com/reflex-dev/reflex/blob/main/docs/ja/README.md) | [Deutsch](https://github.com/reflex-dev/reflex/blob/main/docs/de/README.md) | [Persian (پارسی)](https://github.com/reflex-dev/reflex/blob/main/docs/pe/README.md) | [Tiếng Việt](https://github.com/reflex-dev/reflex/blob/main/docs/vi/README.md)
---
# Reflex
Reflex 是一个使用纯 Python 构建全栈 web 应用的库。
关键特性:
- **纯 Python** - 前端、后端开发全都使用 Python,不需要学习 Javascript。
- **完整的灵活性** - Reflex 很容易上手, 并且也可以扩展到复杂的应用程序。
- **立即部署** - 构建后,使用[单个命令](https://reflex.dev/docs/hosting/deploy-quick-start/)就能部署应用程序;或者也可以将其托管在您自己的服务器上。
请参阅我们的[架构页](https://reflex.dev/blog/2024-03-21-reflex-architecture/#the-reflex-architecture)了解 Reflex 如何工作。
## ⚙️ 安装
打开一个终端并且运行(要求 Python3.10+):
```bash
pip install reflex
```
## 🥳 创建您的第一个应用程序
安装 Reflex 的同时也会安装 `reflex` 命令行工具.
通过创建一个新项目来测试是否安装成功(请把 my_app_name 替代为您的项目名字):
```bash
mkdir my_app_name
cd my_app_name
reflex init
```
这段命令会在新文件夹初始化一个应用程序模板.
您可以在开发者模式下运行这个应用程序:
```bash
reflex run
```
您可以看到您的应用程序运行在 http://localhost:3000.
现在您可以在以下位置修改代码 `my_app_name/my_app_name.py`,Reflex 拥有快速刷新(fast refresh),所以您可以在保存代码后马上看到更改.
## 🫧 范例
让我们来看一个例子: 创建一个使用 [DALL·E](https://platform.openai.com/docs/guides/images/image-generation?context=node) 进行图像生成的图形界面.为了保持范例简单,我们只使用 OpenAI API,但是您可以将其替换成本地端的 ML 模型.
<div align="center">
<img src="/docs/images/dalle.gif" alt="DALL·E的前端界面, 展示了图片生成的进程" width="550" />
</div>
这是这个范例的完整代码,只需要一个 Python 文件就可以完成!
```python
import reflex as rx
import openai
openai_client = openai.OpenAI()
class State(rx.State):
"""The app state."""
prompt = ""
image_url = ""
processing = False
complete = False
def get_image(self):
"""Get the image from the prompt."""
if self.prompt == "":
return rx.window_alert("Prompt Empty")
self.processing, self.complete = True, False
yield
response = openai_client.images.generate(
prompt=self.prompt, n=1, size="1024x1024"
)
self.image_url = response.data[0].url
self.processing, self.complete = False, True
def index():
return rx.center(
rx.vstack(
rx.heading("DALL-E", font_size="1.5em"),
rx.input(
placeholder="Enter a prompt..",
on_blur=State.set_prompt,
width="25em",
),
rx.button(
"Generate Image",
on_click=State.get_image,
width="25em",
loading=State.processing
),
rx.cond(
State.complete,
rx.image(src=State.image_url, width="20em"),
),
align="center",
),
width="100%",
height="100vh",
)
# Add state and page to the app.
app = rx.App()
app.add_page(index, title="Reflex:DALL-E")
```
## 让我们分解以上步骤.
<div align="center">
<img src="/docs/images/dalle_colored_code_example.png" alt="解释 DALL-E app 的前端和后端部分的区别。" width="900" />
</div>
### **Reflex UI**
让我们从 UI 开始.
```python
def index():
return rx.center(
...
)
```
这个 `index` 函数定义了应用程序的前端.
我们用不同的组件比如 `center`, `vstack`, `input`, 和 `button` 来创建前端, 组件之间可以相互嵌入,来创建复杂的布局.
并且您可以使用关键字参数来使用 CSS 的全部功能.
Reflex 拥有 [60+ 个内置组件](https://reflex.dev/docs/library) 来帮助您开始创建应用程序. 我们正在积极添加组件, 但是您也可以容易的 [创建自己的组件](https://reflex.dev/docs/wrapping-react/overview/).
### **State**
Reflex 用 State 来渲染您的 UI.
```python
class State(rx.State):
"""The app state."""
prompt = ""
image_url = ""
processing = False
complete = False
```
State 定义了所有可能会发生变化的变量(称为 vars)以及能够改变这些变量的函数.
在这个范例中,State 由 `prompt` 和 `image_url` 组成.此外,State 还包含有两个布尔值 `processing` 和 `complete`,用于指示何时显示循环进度指示器和图像.
### **Event Handlers**
```python
def get_image(self):
"""Get the image from the prompt."""
if self.prompt == "":
return rx.window_alert("Prompt Empty")
self.processing, self.complete = True, False
yield
response = openai_client.images.generate(
prompt=self.prompt, n=1, size="1024x1024"
)
self.image_url = response.data[0].url
self.processing, self.complete = False, True
```
在 State 中,我们定义了称为事件处理器(event handlers)的函数,用于改变状态变量(state vars).在 Reflex 中,事件处理器是我们可以修改状态的方式.它们可以作为对用户操作的响应而被调用,例如点击一个按钮或在文本框中输入.这些操作被称为事件.
我们的 DALL·E 应用有一个事件处理器,名为 `get_image`,它用于从 OpenAI API 获取图像.在事件处理器中使用 `yield` 将导致 UI 进行更新.否则,UI 将在事件处理器结束时进行更新.
### **Routing**
最后,定义我们的应用程序.
```python
app = rx.App()
```
我们添加从应用程序根目录到 index 组件的路由.我们还添加了一个在页面预览或浏览器标签中显示的标题.
```python
app.add_page(index, title="DALL-E")
```
您可以通过增加更多页面来创建一个多页面的应用.
## 📑 资源
<div align="center">
📑 [文档](https://reflex.dev/docs/getting-started/introduction) | 🗞️ [日志](https://reflex.dev/blog) | 📱 [组件库](https://reflex.dev/docs/library) | 🖼️ [模板](https://reflex.dev/templates/) | 🛸 [部署](https://reflex.dev/docs/hosting/deploy-quick-start)
</div>
## ✅ Reflex 的状态
Reflex 于 2022 年 12 月以 Pynecone 的名称推出.
从 2025 年开始,[Reflex Cloud](https://cloud.reflex.dev)已经推出,为 Reflex 应用提供最佳的托管体验。我们将继续开发并实现更多功能。
Reflex 每周都有新功能和发布新版本! 确保您按下 :star: 收藏和 :eyes: 关注 这个 仓库来确保知道最新信息.
## 贡献
我们欢迎任何大小的贡献,以下是几个好的方法来加入 Reflex 社群.
- **加入我们的 Discord**: 我们的 [Discord](https://discord.gg/T5WSbC2YtQ) 是帮助您加入 Reflex 项目和讨论或贡献最棒的地方.
- **GitHub Discussions**: 一个来讨论您想要添加的功能或是需要澄清的事情的好地方.
- **GitHub Issues**: [Issues](https://github.com/reflex-dev/reflex/issues)是报告错误的绝佳地方,另外您可以试着解决一些现有 issue 并提交 PR.
我们正在积极寻找贡献者,无关您的技能或经验水平. 若要贡献,请查看[CONTRIBUTING.md](https://github.com/reflex-dev/reflex/blob/main/CONTRIBUTING.md)
## 感谢我们所有的贡献者:
<a href="https://github.com/reflex-dev/reflex/graphs/contributors">
<img src="https://contrib.rocks/image?repo=reflex-dev/reflex" />
</a>
## 授权
Reflex 是一个开源项目,使用 [Apache License 2.0](/LICENSE) 授权.
## /docs/zh/zh_tw/README.md
<div align="center">
<img src="/docs/images/reflex.svg" alt="Reflex Logo" width="300px">
<hr>
**✨ 使用 Python 建立高效且可自訂的網頁應用程式,幾秒鐘內即可部署。✨**
[](https://badge.fury.io/py/reflex)

[](https://reflex.dev/docs/getting-started/introduction)
[](https://pepy.tech/projects/reflex)
[](https://discord.gg/T5WSbC2YtQ)
</div>
---
[English](https://github.com/reflex-dev/reflex/blob/main/README.md) | [简体中文](https://github.com/reflex-dev/reflex/blob/main/docs/zh/zh_cn/README.md) | [繁體中文](https://github.com/reflex-dev/reflex/blob/main/docs/zh/zh_tw/README.md) | [Türkçe](https://github.com/reflex-dev/reflex/blob/main/docs/tr/README.md) | [हिंदी](https://github.com/reflex-dev/reflex/blob/main/docs/in/README.md) | [Português (Brasil)](https://github.com/reflex-dev/reflex/blob/main/docs/pt/pt_br/README.md) | [Italiano](https://github.com/reflex-dev/reflex/blob/main/docs/it/README.md) | [Español](https://github.com/reflex-dev/reflex/blob/main/docs/es/README.md) | [한국어](https://github.com/reflex-dev/reflex/blob/main/docs/kr/README.md) | [日本語](https://github.com/reflex-dev/reflex/blob/main/docs/ja/README.md) | [Deutsch](https://github.com/reflex-dev/reflex/blob/main/docs/de/README.md) | [Persian (پارسی)](https://github.com/reflex-dev/reflex/blob/main/docs/pe/README.md) | [Tiếng Việt](https://github.com/reflex-dev/reflex/blob/main/docs/vi/README.md)
---
# Reflex
Reflex 是一個可以用純 Python 構建全端網頁應用程式的函式庫。
主要特色:
- **純 Python** - 您可以用 Python 撰寫應用程式的前端和後端,無需學習 Javascript。
- **完全靈活性** - Reflex 易於上手,但也可以擴展到複雜的應用程式。
- **立即部署** - 構建後,只需使用[單一指令](https://reflex.dev/docs/hosting/deploy-quick-start/)即可部署您的應用程式,或在您自己的伺服器上託管。
請參閱我們的[架構頁面](https://reflex.dev/blog/2024-03-21-reflex-architecture/#the-reflex-architecture)了解 Reflex 如何在底層運作。
## ⚙️ 安裝
開啟一個終端機並且執行 (需要 Python 3.10+):
```bash
pip install reflex
```
## 🥳 建立你的第一個應用程式
安裝 Reflex 的同時也會安裝 `reflex` 命令行工具。
通過創建一個新專案來測試是否安裝成功。(把 my_app_name 作為新專案名稱):
```bash
mkdir my_app_name
cd my_app_name
reflex init
```
此命令會初始化一個應用程式模板在你的新資料夾中。
你可以在開發者模式運行這個應用程式:
```bash
reflex run
```
你可以看到你的應用程式運行在 http://localhost:3000。
現在在以下位置修改原始碼 `my_app_name/my_app_name.py`,Reflex 擁有快速刷新功能,存儲程式碼後便可立即看到改變。
## 🫧 範例應用程式
讓我們來看一個例子: 建立一個使用 DALL·E 的圖形使用者介面,為了保持範例簡單,我們只呼叫 OpenAI API,而這部份可以置換掉,改為執行成本地端的 ML 模型。
<div align="center">
<img src="/docs/images/dalle.gif" alt="A frontend wrapper for DALL·E, shown in the process of generating an image." width="550" />
</div>
下方為該應用之完整程式碼,這一切都只需要一個 Python 檔案就能作到!
```python
import reflex as rx
import openai
openai_client = openai.OpenAI()
class State(rx.State):
"""應用程式狀態"""
prompt = ""
image_url = ""
processing = False
complete = False
def get_image(self):
"""透過提示詞取得圖片"""
if self.prompt == "":
return rx.window_alert("Prompt Empty")
self.processing, self.complete = True, False
yield
response = openai_client.images.generate(
prompt=self.prompt, n=1, size="1024x1024"
)
self.image_url = response.data[0].url
self.processing, self.complete = False, True
def index():
return rx.center(
rx.vstack(
rx.heading("DALL-E", font_size="1.5em"),
rx.input(
placeholder="Enter a prompt..",
on_blur=State.set_prompt,
width="25em",
),
rx.button(
"Generate Image",
on_click=State.get_image,
width="25em",
loading=State.processing
),
rx.cond(
State.complete,
rx.image(src=State.image_url, width="20em"),
),
align="center",
),
width="100%",
height="100vh",
)
# 把狀態跟頁面添加到應用程式。
app = rx.App()
app.add_page(index, title="Reflex:DALL-E")
```
## 讓我們來拆解一下。
<div align="center">
<img src="/docs/images/dalle_colored_code_example.png" alt="解釋 DALL-E app 的前端和後端部分的區別。" width="900" />
</div>
### **Reflex 使用者介面**
讓我們從使用介面開始。
```python
def index():
return rx.center(
...
)
```
這個 `index` 函式定義了應用程式的前端.
我們用不同的元件像是 `center`, `vstack`, `input`, 和 `button` 來建立前端,元件之間可互相套入以建立出複雜的版面配置。並且您可使用關鍵字引數 _keyword args_ 運行 CSS 全部功能來設計這些元件們的樣式。
Reflex 擁有 [60+ 內建元件](https://reflex.dev/docs/library) 來幫助你開始建立應用程式。我們正積極添加元件,你也可以簡單地 [創建自己所屬的元件](https://reflex.dev/docs/wrapping-react/overview/)。
### **應用程式狀態**
Reflex 使用應用程式狀態中的函式來渲染你的 UI。
```python
class State(rx.State):
"""應用程式狀態"""
prompt = ""
image_url = ""
processing = False
complete = False
```
應用程式狀態定義了應用程式中所有可以更改的變數及變更他們的函式 (稱為 vars)。
這裡的狀態由 `prompt` 和 `image_url`組成, 以及布林變數 `processing` 和 `complete` 來指示何時顯示進度條及圖片。
### **事件處理程序**
```python
def get_image(self):
"""透過提示詞取得圖片"""
if self.prompt == "":
return rx.window_alert("Prompt Empty")
self.processing, self.complete = True, False
yield
response = openai_client.images.generate(
prompt=self.prompt, n=1, size="1024x1024"
)
self.image_url = response.data[0].url
self.processing, self.complete = False, True
```
在應用程式狀態中,我們定義稱之為事件處理程序的函式來改變其 vars. 事件處理程序是我們用來改變 Reflex 應用程式狀態的方法。
當使用者動作被響應時,對應的事件處理程序就會被呼叫。點擊按鈕或是文字框輸入都是使用者動作,它們被稱之為事件。
我們的 DALL·E. 應用程式有一個事件處理程序 `get_image`,它透過 Open AI API 取得圖片。在事件處理程序中使用 `yield` 將讓使用者介面中途更新,若不使用的話,使用介面只能在事件處理程序結束時才更新。
### **路由**
最後,我們定義我們的應用程式 app。
```python
app = rx.App()
```
添加從應用程式根目錄(root of the app) 到 index 元件的路由。 我們也添加了一個標題將會顯示在 預覽/瀏覽 分頁。
```python
app.add_page(index, title="DALL-E")
```
你可以添加更多頁面至路由藉此來建立多頁面應用程式(multi-page app)
## 📑 資源
<div align="center">
📑 [Docs](https://reflex.dev/docs/getting-started/introduction) | 🗞️ [Blog](https://reflex.dev/blog) | 📱 [Component Library](https://reflex.dev/docs/library) | 🖼️ [Templates](https://reflex.dev/templates/) | 🛸 [Deployment](https://reflex.dev/docs/hosting/deploy-quick-start)
</div>
## ✅ 產品狀態
Reflex 在 2022 年 12 月以 Pynecone 的名字推出。
自 2025 年起,[Reflex Cloud](https://cloud.reflex.dev) 已推出,為 Reflex 應用程式提供最佳的託管體驗。我們將繼續開發並實施更多功能。
Reflex 每周都有新功能和釋出新版本! 確保你按下 :star: 和 :eyes: watch 這個 repository 來確保知道最新資訊。
## 貢獻
我們歡迎任何大小的貢獻,以下是一些加入 Reflex 社群的好方法。
- **加入我們的 Discord**: 我們的 [Discord](https://discord.gg/T5WSbC2YtQ) 是獲取 Reflex 專案幫助和討論如何貢獻的最佳地方。
- **GitHub Discussions**: 這是一個討論您想新增的功能或對於一些困惑/需要澄清事項的好方法。
- **GitHub Issues**: 在 [Issues](https://github.com/reflex-dev/reflex/issues) 頁面報告錯誤是一個絕佳的方式。此外,您也可以嘗試解決現有 Issue 並提交 PR。
我們積極尋找貢獻者,不論您的技能水平或經驗如何。要貢獻,請查看 [CONTRIBUTING.md](https://github.com/reflex-dev/reflex/blob/main/CONTRIBUTING.md)
## 感謝所有貢獻者:
<a href="https://github.com/reflex-dev/reflex/graphs/contributors">
<img src="https://contrib.rocks/image?repo=reflex-dev/reflex" />
</a>
## 授權
Reflex 是一個開源專案且使用 [Apache License 2.0](/LICENSE) 授權。
## /pyi_hashes.json
```json path="/pyi_hashes.json"
{
"reflex/__init__.pyi": "b304ed6f7a2fa028a194cad81bd83112",
"reflex/components/__init__.pyi": "ac05995852baa81062ba3d18fbc489fb",
"reflex/components/base/__init__.pyi": "16e47bf19e0d62835a605baa3d039c5a",
"reflex/components/base/app_wrap.pyi": "22e94feaa9fe675bcae51c412f5b67f1",
"reflex/components/base/body.pyi": "e8ab029a730824bab6d4211203609e6a",
"reflex/components/base/document.pyi": "311c53c90a60587a82e760103758a3cf",
"reflex/components/base/error_boundary.pyi": "a678cceea014cb16048647257cd24ba6",
"reflex/components/base/fragment.pyi": "745f1be02c23a0b25d7c52d7423ec76a",
"reflex/components/base/link.pyi": "0bc1d26ee29d8864aed14a12991bd47d",
"reflex/components/base/meta.pyi": "129aecf65ab53f756c4d1cbe1d0b188d",
"reflex/components/base/script.pyi": "e5f506d1d0d6712cb9e597a781eb3941",
"reflex/components/base/strict_mode.pyi": "6b72e16caadf7158ab744a0ab751b010",
"reflex/components/core/__init__.pyi": "007170b97e58bdf28b2aee381d91c0c7",
"reflex/components/core/auto_scroll.pyi": "18068d22aca7244a08cd0c5a897c0950",
"reflex/components/core/banner.pyi": "fd93e7a92961de8524718ad32135c37c",
"reflex/components/core/clipboard.pyi": "a844eb927d9bc2a43f5e88161b258539",
"reflex/components/core/debounce.pyi": "055da7aa890f44fb4d48bd5978f1a874",
"reflex/components/core/helmet.pyi": "43f8497c8fafe51e29dca1dd535d143a",
"reflex/components/core/html.pyi": "86eb9d4c1bb4807547b2950d9a32e9fd",
"reflex/components/core/sticky.pyi": "cb763b986a9b0654d1a3f33440dfcf60",
"reflex/components/core/upload.pyi": "6dc28804a6dddf903e31162e87c1b023",
"reflex/components/core/window_events.pyi": "af33ccec866b9540ee7fbec6dbfbd151",
"reflex/components/datadisplay/__init__.pyi": "52755871369acbfd3a96b46b9a11d32e",
"reflex/components/datadisplay/code.pyi": "b86769987ef4d1cbdddb461be88539fd",
"reflex/components/datadisplay/dataeditor.pyi": "35391d4ba147cf20ce4ac7a782066d61",
"reflex/components/datadisplay/shiki_code_block.pyi": "1d53e75b6be0d3385a342e7b3011babd",
"reflex/components/el/__init__.pyi": "0adfd001a926a2a40aee94f6fa725ecc",
"reflex/components/el/element.pyi": "c5974a92fbc310e42d0f6cfdd13472f4",
"reflex/components/el/elements/__init__.pyi": "29512d7a6b29c6dc5ff68d3b31f26528",
"reflex/components/el/elements/base.pyi": "3f74c7ea573ea29b055b0cd48b040d2c",
"reflex/components/el/elements/forms.pyi": "8b6bb2fbaf4bad828b076e2f7c8444d0",
"reflex/components/el/elements/inline.pyi": "3549cd6ad45217aa6387800911b641c3",
"reflex/components/el/elements/media.pyi": "9b97220aa99783d402b6e278c4069043",
"reflex/components/el/elements/metadata.pyi": "24448004b7aa07f1225028a85bd49fef",
"reflex/components/el/elements/other.pyi": "0c4d5d0b955d8596bf6cf4a48d7decdb",
"reflex/components/el/elements/scripts.pyi": "d33df9f21f7e838376b2b5024beef7c9",
"reflex/components/el/elements/sectioning.pyi": "3c5a7e4caa9c25da0ae788f02466eac4",
"reflex/components/el/elements/tables.pyi": "686eb70ea7d8c4dafb0cc5c284e76184",
"reflex/components/el/elements/typography.pyi": "684e83dde887dba12badd0fb75c87c04",
"reflex/components/gridjs/datatable.pyi": "98a7e1b3f3b60cafcdfcd8879750ee42",
"reflex/components/lucide/icon.pyi": "6026aca0c03c3e6f423ac3d61db1f7b2",
"reflex/components/markdown/markdown.pyi": "2f84254a548e908020949564fc289339",
"reflex/components/moment/moment.pyi": "e1952f1c2c82cef85d91e970d1be64ab",
"reflex/components/plotly/plotly.pyi": "4311a0aae2abcc9226abb6a273f96372",
"reflex/components/radix/__init__.pyi": "5d8e3579912473e563676bfc71f29191",
"reflex/components/radix/primitives/__init__.pyi": "01c388fe7a1f5426a16676404344edf6",
"reflex/components/radix/primitives/accordion.pyi": "19484eca0ad53f538f5db04c09921738",
"reflex/components/radix/primitives/base.pyi": "9ef34884fb6028dc017df5e2db639c81",
"reflex/components/radix/primitives/dialog.pyi": "9ee73362bb59619c482b6b0d07033f37",
"reflex/components/radix/primitives/drawer.pyi": "921e45dfaf5b9131ef27c561c3acca2e",
"reflex/components/radix/primitives/form.pyi": "78055e820703c98c3b838aa889566365",
"reflex/components/radix/primitives/progress.pyi": "c917952d57ddb3e138a40c4005120d5e",
"reflex/components/radix/primitives/slider.pyi": "4ff06f0025d47f166132909b09ab96f8",
"reflex/components/radix/themes/__init__.pyi": "582b4a7ead62b2ae8605e17fa084c063",
"reflex/components/radix/themes/base.pyi": "3e1ccd5ce5fef0b2898025193ee3d069",
"reflex/components/radix/themes/color_mode.pyi": "dda570583355d8c0d8f607be457ba7a1",
"reflex/components/radix/themes/components/__init__.pyi": "efa279ee05479d7bb8a64d49da808d03",
"reflex/components/radix/themes/components/alert_dialog.pyi": "eed422fcc1ff5ccf3dbf6934699bd0b1",
"reflex/components/radix/themes/components/aspect_ratio.pyi": "71de4160d79840561c48b570197a4152",
"reflex/components/radix/themes/components/avatar.pyi": "e40c2f0fda6d2c028d83681a27f3fb96",
"reflex/components/radix/themes/components/badge.pyi": "58fd1a9c5d2f8762e2a0370311731ff5",
"reflex/components/radix/themes/components/button.pyi": "50f0b08ad5d1d1054ab537152f0f5c43",
"reflex/components/radix/themes/components/callout.pyi": "547f2570ffbd10db36b745566e9f1b17",
"reflex/components/radix/themes/components/card.pyi": "f7adb83f7b001a11bdd7fd6791fb3ffb",
"reflex/components/radix/themes/components/checkbox.pyi": "8eabb6887a5d0849a43e086a284814c2",
"reflex/components/radix/themes/components/checkbox_cards.pyi": "1d567fd04b4425abd5cc5aad10108aa9",
"reflex/components/radix/themes/components/checkbox_group.pyi": "8638582a623036f8893a3fa6080f2672",
"reflex/components/radix/themes/components/context_menu.pyi": "b9499d8bdd2c5565621fea5fe7d7a25a",
"reflex/components/radix/themes/components/data_list.pyi": "6f8d9c582e084c23966b992158193b72",
"reflex/components/radix/themes/components/dialog.pyi": "d2615f1a68c80ff930444d054b598c13",
"reflex/components/radix/themes/components/dropdown_menu.pyi": "43f8770c9adf93c73398d68f79048424",
"reflex/components/radix/themes/components/hover_card.pyi": "a96f4433237f9994decf935deff9f269",
"reflex/components/radix/themes/components/icon_button.pyi": "e930911d8ecbe61e5447e61c76a28ab6",
"reflex/components/radix/themes/components/inset.pyi": "bd7a2186b553bd4c86d83ff50c784066",
"reflex/components/radix/themes/components/popover.pyi": "91f8edefeb232cc6d48690b1838144c2",
"reflex/components/radix/themes/components/progress.pyi": "0e59587d5b3c8fe0d0067587f144e5b0",
"reflex/components/radix/themes/components/radio.pyi": "f375aa5ac746679618ea7dad257e3224",
"reflex/components/radix/themes/components/radio_cards.pyi": "9dc34a1ce2a1924eb1f41438ef84e80b",
"reflex/components/radix/themes/components/radio_group.pyi": "173254cf91908bcf6aa4fa21a747e2cf",
"reflex/components/radix/themes/components/scroll_area.pyi": "2e3539b0f6895dda127ee96e9864dbf9",
"reflex/components/radix/themes/components/segmented_control.pyi": "1776f1ad936bae402007802b1ee98906",
"reflex/components/radix/themes/components/select.pyi": "2c7aee592972ff5f05da08154aa981c8",
"reflex/components/radix/themes/components/separator.pyi": "79e550cc10ee455f35d75d0e236fedd2",
"reflex/components/radix/themes/components/skeleton.pyi": "a25d3ceb56f99f736ea463579845c454",
"reflex/components/radix/themes/components/slider.pyi": "305a34c14ca8656ca9267e4c31aaa388",
"reflex/components/radix/themes/components/spinner.pyi": "b7e689e7d75635e379242fd113a1ea9a",
"reflex/components/radix/themes/components/switch.pyi": "f1ba948750a74126cda990e89a3ec7ef",
"reflex/components/radix/themes/components/table.pyi": "eefbbd1904deae3d166fcad28b20fd4a",
"reflex/components/radix/themes/components/tabs.pyi": "a533d2509a6798fe0ab7275b0152519d",
"reflex/components/radix/themes/components/text_area.pyi": "4af55e5d18a5b9d56717bf31b23ea543",
"reflex/components/radix/themes/components/text_field.pyi": "232618b744076db98d861ea1b9eb3192",
"reflex/components/radix/themes/components/tooltip.pyi": "2b8366200ce92ec4784ca3ec4152e676",
"reflex/components/radix/themes/layout/__init__.pyi": "73eefc509a49215b1797b5b5d28d035e",
"reflex/components/radix/themes/layout/base.pyi": "5be31d7dadd23ab544e53762423d123e",
"reflex/components/radix/themes/layout/box.pyi": "dbaed1c50c668805fc7b71d22f878254",
"reflex/components/radix/themes/layout/center.pyi": "17323694217e8ad7611adb683f8d96ce",
"reflex/components/radix/themes/layout/container.pyi": "24222fd7ffa2dc05f709eab6c7b9643c",
"reflex/components/radix/themes/layout/flex.pyi": "0307e9dbe6a5784140121d77c8f67a86",
"reflex/components/radix/themes/layout/grid.pyi": "95c9edb8bdd4e39dc1bd6bc2a8ca0933",
"reflex/components/radix/themes/layout/list.pyi": "049ecf827ef0ba8de2d76dbf7b1c562c",
"reflex/components/radix/themes/layout/section.pyi": "a51952b9b5c8227aa3024373dedcad5d",
"reflex/components/radix/themes/layout/spacer.pyi": "c35accf0f2f742c90a23675ff1fb960d",
"reflex/components/radix/themes/layout/stack.pyi": "271d3315c6196356d3ced759520d4e7d",
"reflex/components/radix/themes/typography/__init__.pyi": "b8ef970530397e9984004961f3aaee62",
"reflex/components/radix/themes/typography/blockquote.pyi": "080c71899532f5dbf4cf143e7a5ad3bf",
"reflex/components/radix/themes/typography/code.pyi": "7ffe785d55979cf8ff97ea040f3e2b64",
"reflex/components/radix/themes/typography/heading.pyi": "0ebb38915cd0521fd59c569e04d288bb",
"reflex/components/radix/themes/typography/link.pyi": "e88c5d880a54548b6808c097ac62505b",
"reflex/components/radix/themes/typography/text.pyi": "50f9ca15a941e4b77ddd12e77aa3c03e",
"reflex/components/react_player/audio.pyi": "9de7d9830534c6ec1f305434c4d8abd8",
"reflex/components/react_player/react_player.pyi": "7a7a29a64a0d127c12c8131abcd012d1",
"reflex/components/react_player/video.pyi": "e946b4915b41326d4e4b39381349d152",
"reflex/components/react_router/dom.pyi": "3042fa630b7e26a7378fe045d7fbf4af",
"reflex/components/recharts/__init__.pyi": "6ee7f1ca2c0912f389ba6f3251a74d99",
"reflex/components/recharts/cartesian.pyi": "cfca4f880239ffaecdf9fb4c7c8caed5",
"reflex/components/recharts/charts.pyi": "013036b9c00ad85a570efdb813c1bc40",
"reflex/components/recharts/general.pyi": "d87ff9b85b2a204be01753690df4fb11",
"reflex/components/recharts/polar.pyi": "ad24bd37c6acc0bc9bd4ac01af3ffe49",
"reflex/components/recharts/recharts.pyi": "c41d19ab67972246c574098929bea7ea",
"reflex/components/sonner/toast.pyi": "3c27bad1aaeb5183eaa6a41e77e8d7f0"
}
```
## /pyproject.toml
```toml path="/pyproject.toml"
[project]
name = "reflex"
version = "0.8.19dev1"
description = "Web apps in pure Python."
license.text = "Apache-2.0"
authors = [
{ name = "Nikhil Rao" },
{ name = "Alek Petuskey" },
{ name = "Masen Furer" },
{ name = "Elijah Ahianyo" },
{ name = "Thomas Brandeho" },
{ name = "Khaleel Al-Adhami" },
]
maintainers = [
{ name = "Masen Furer" },
{ name = "Khaleel Al-Adhami" },
{ email = "maintainers@reflex.dev" },
]
readme = "README.md"
keywords = ["web", "framework"]
requires-python = ">=3.10,<4.0"
dependencies = [
"alembic >=1.15.2,<2.0",
"click >=8.2",
"granian[reload] >=2.5.5",
"httpx >=0.23.3,<1.0",
"packaging >=24.2,<26",
"platformdirs >=4.3.7,<5.0",
"psutil >=7.0.0,<8.0; sys_platform == 'win32'",
"pydantic >=1.10.21,<3.0",
"python-multipart >=0.0.20,<1.0",
"python-socketio >=5.12.0,<6.0",
"redis >=5.2.1,<8.0",
"reflex-hosting-cli >=0.1.58",
"rich >=13,<15",
"sqlmodel >=0.0.27,<0.1",
"starlette >=0.47.0",
"typing_extensions >=4.13.0",
"wrapt >=1.17.0,<3.0",
]
classifiers = [
"Development Status :: 4 - Beta",
"License :: OSI Approved :: Apache Software License",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
"Programming Language :: Python :: 3.13",
"Programming Language :: Python :: 3.14",
]
[project.optional-dependencies]
db = [
"alembic >=1.15.2,<2.0",
"pydantic >=1.10.21,<3.0",
"sqlmodel >=0.0.24,<0.1",
]
monitoring = ["pyleak >=0.1.14,<1.0"]
[project.urls]
homepage = "https://reflex.dev"
repository = "https://github.com/reflex-dev/reflex"
documentation = "https://reflex.dev/docs/getting-started/introduction"
[project.scripts]
reflex = "reflex.reflex:cli"
[dependency-groups]
dev = [
"asynctest",
"darglint",
"dill",
"fastapi",
"hatchling",
"libsass",
"numpy",
"pandas",
"pillow",
"playwright",
"plotly",
"pre-commit",
"psutil",
"psycopg[binary]",
"pyleak >=0.1.14,<1.0",
"pyright",
"pytest-asyncio",
"pytest-benchmark",
"pytest-codspeed",
"pytest-cov",
"pytest-mock",
"pytest-playwright",
"pytest-rerunfailures",
"pytest-split",
"pytest",
"python-dotenv",
"ruff",
"selenium",
"starlette-admin",
"toml",
"uvicorn",
]
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[tool.hatch.build]
include = ["reflex", "scripts/hatch_build.py"]
targets.sdist.artifacts = ["*.pyi"]
targets.wheel.artifacts = ["*.pyi"]
[tool.hatch.build.hooks.custom]
path = "scripts/hatch_build.py"
dependencies = ["plotly", "ruff", "pre_commit", "toml"]
require-runtime-dependencies = true
[tool.pyright]
reportIncompatibleMethodOverride = false
[tool.ruff]
target-version = "py310"
output-format = "concise"
lint.isort.split-on-trailing-comma = false
preview = true
lint.select = ["ALL"]
lint.ignore = [
"A",
"ANN002",
"ANN003",
"ANN2",
"ANN4",
"ARG",
"BLE",
"C901",
"COM",
"CPY001",
"D205",
"DOC202",
"DOC501",
"DOC502",
"DTZ",
"E501",
"F403",
"FBT",
"FIX",
"FURB189",
"FURB140",
"G004",
"ISC003",
"PLC",
"PLR",
"PLW",
"PT011",
"PT012",
"PYI",
"RUF012",
"S",
"SLF",
"SLOT",
"TC",
"TD",
"TRY0",
]
lint.pydocstyle.convention = "google"
lint.flake8-bugbear.extend-immutable-calls = [
"reflex.utils.types.Unset",
"reflex.vars.base.Var.create",
]
[tool.ruff.lint.per-file-ignores]
"__init__.py" = ["F401"]
"tests/*.py" = [
"ANN001",
"D100",
"D103",
"D104",
"INP",
"B018",
"PERF",
"T",
"N",
]
"benchmarks/*.py" = ["ANN001", "D100", "D103", "D104", "B018", "PERF", "T", "N"]
"reflex/.templates/*.py" = ["D100", "D103", "D104"]
"*.pyi" = ["D301", "D415", "D417", "D418", "E742", "N", "PGH"]
"pyi_generator.py" = ["N802"]
"reflex/constants/*.py" = ["N"]
"reflex/.templates/apps/blank/code/*" = ["INP001"]
"*/blank.py" = ["I001"]
[tool.pytest.ini_options]
filterwarnings = "ignore:fields may not start with an underscore:RuntimeWarning"
asyncio_default_fixture_loop_scope = "function"
asyncio_mode = "auto"
[tool.codespell]
skip = "docs/*,*.html,examples/*, *.pyi, poetry.lock, uv.lock"
ignore-words-list = "te, TreeE"
[tool.coverage.run]
source = ["reflex"]
branch = true
omit = [
"*/pyi_generator.py",
"reflex/__main__.py",
"reflex/app_module_for_backend.py",
"reflex/components/chakra/*",
"reflex/experimental/*",
]
[tool.coverage.report]
show_missing = true
# TODO bump back to 79
fail_under = 70
precision = 2
ignore_errors = true
exclude_also = [
"def __repr__",
# Don't complain about missing debug-only code:
"if self.debug",
# Don't complain if tests don't hit defensive assertion code:
"raise AssertionError",
"raise NotImplementedError",
# Regexes for lines to exclude from consideration
"if 0:",
# Don't complain if non-runnable code isn't run:
"if __name__ == .__main__.:",
# Don't complain about abstract methods, they aren't run:
"@(abc.)?abstractmethod",
# Don't complain about overloaded methods:
"@overload",
]
[tool.coverage.html]
directory = "coverage_html_report"
[tool.pre-commit]
fail_fast = true
[[tool.pre-commit.repos]]
repo = "https://github.com/astral-sh/ruff-pre-commit"
rev = "v0.14.2"
hooks = [
{ id = "ruff-format", args = [
"reflex",
"tests",
] },
{ id = "ruff-check", args = [
"--fix",
"--exit-non-zero-on-fix",
], exclude = "^integration/benchmarks/" },
]
[[tool.pre-commit.repos]]
repo = "https://github.com/codespell-project/codespell"
rev = "v2.4.1"
hooks = [
{ id = "codespell", args = [
"reflex",
], additional_dependencies = [
"tomli",
] },
]
# Run pyi check before pyright because pyright can fail if pyi files are wrong.
[[tool.pre-commit.repos]]
repo = "local"
hooks = [
{ id = "update-pyi-files", name = "update-pyi-files", always_run = true, language = "system", require_serial = true, description = "Update pyi files as needed", entry = "python3 scripts/make_pyi.py" },
]
[[tool.pre-commit.repos]]
repo = "https://github.com/RobertCraigie/pyright-python"
rev = "v1.1.407"
hooks = [{ id = "pyright", args = ["reflex", "tests"], language = "system" }]
[[tool.pre-commit.repos]]
repo = "https://github.com/pre-commit/mirrors-prettier"
rev = "f62a70a3a7114896b062de517d72829ea1c884b6"
hooks = [{ id = "prettier", require_serial = true }]
[tool.uv]
required-version = ">=0.7.0"
```
## /reflex/.templates/apps/blank/assets/favicon.ico
Binary file available at https://raw.githubusercontent.com/reflex-dev/reflex/refs/heads/main/reflex/.templates/apps/blank/assets/favicon.ico
## /reflex/.templates/apps/blank/code/__init__.py
```py path="/reflex/.templates/apps/blank/code/__init__.py"
```
## /reflex/.templates/apps/blank/code/blank.py
```py path="/reflex/.templates/apps/blank/code/blank.py"
"""Welcome to Reflex! This file outlines the steps to create a basic app."""
import reflex as rx
from rxconfig import config
class State(rx.State):
"""The app state."""
def index() -> rx.Component:
# Welcome Page (Index)
return rx.container(
rx.color_mode.button(position="top-right"),
rx.vstack(
rx.heading("Welcome to Reflex!", size="9"),
rx.text(
"Get started by editing ",
rx.code(f"{config.app_name}/{config.app_name}.py"),
size="5",
),
rx.link(
rx.button("Check out our docs!"),
href="https://reflex.dev/docs/getting-started/introduction/",
is_external=True,
),
spacing="5",
justify="center",
min_height="85vh",
),
)
app = rx.App()
app.add_page(index)
```
## /reflex/.templates/web/.gitignore
```gitignore path="/reflex/.templates/web/.gitignore"
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
/_static
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# local env files
.env.local
.env.development.local
.env.test.local
.env.production.local
# vercel
.vercel
# DS_Store
.DS_Store
```
## /reflex/.templates/web/app/entry.client.js
```js path="/reflex/.templates/web/app/entry.client.js"
import { startTransition } from "react";
import { hydrateRoot } from "react-dom/client";
import { HydratedRouter } from "react-router/dom";
import { createElement } from "react";
startTransition(() => {
hydrateRoot(document, createElement(HydratedRouter));
});
```
## /reflex/.templates/web/app/routes.js
```js path="/reflex/.templates/web/app/routes.js"
import { route } from "@react-router/dev/routes";
import { flatRoutes } from "@react-router/fs-routes";
export default [
...(await flatRoutes({
ignoredRouteFiles: ["routes/\\[404\\]._index.jsx"],
})),
route("*", "routes/[404]._index.jsx"),
];
```
## /reflex/.templates/web/components/reflex/radix_themes_color_mode_provider.js
```js path="/reflex/.templates/web/components/reflex/radix_themes_color_mode_provider.js"
import { useTheme } from "$/utils/react-theme";
import { createElement, useEffect } from "react";
import { ColorModeContext, defaultColorMode } from "$/utils/context";
export default function RadixThemesColorModeProvider({ children }) {
const { theme, resolvedTheme, setTheme } = useTheme();
const toggleColorMode = () => {
setTheme(resolvedTheme === "light" ? "dark" : "light");
};
const setColorMode = (mode) => {
const allowedModes = ["light", "dark", "system"];
if (!allowedModes.includes(mode)) {
console.error(
`Invalid color mode "${mode}". Defaulting to "${defaultColorMode}".`,
);
mode = defaultColorMode;
}
setTheme(mode);
};
useEffect(() => {
const radixRoot = document.querySelector(
'.radix-themes[data-is-root-theme="true"]',
);
if (radixRoot) {
radixRoot.classList.remove("light", "dark");
radixRoot.classList.add(resolvedTheme);
}
}, [resolvedTheme]);
return createElement(
ColorModeContext.Provider,
{
value: {
rawColorMode: theme,
resolvedColorMode: resolvedTheme,
toggleColorMode,
setColorMode,
},
},
children,
);
}
```
## /reflex/.templates/web/components/shiki/code.js
```js path="/reflex/.templates/web/components/shiki/code.js"
import { useEffect, useState, createElement } from "react";
import { codeToHtml } from "shiki";
/**
* Code component that uses Shiki to convert code to HTML and render it.
*
* @param code - The code to be highlighted.
* @param theme - The theme to be used for highlighting.
* @param language - The language of the code.
* @param transformers - The transformers to be applied to the code.
* @param decorations - The decorations to be applied to the code.
* @param divProps - Additional properties to be passed to the div element.
* @returns The rendered code block.
*/
export function Code({
code,
theme,
language,
transformers,
decorations,
...divProps
}) {
const [codeResult, setCodeResult] = useState("");
useEffect(() => {
async function fetchCode() {
const result = await codeToHtml(code, {
lang: language,
theme,
transformers,
decorations,
});
setCodeResult(result);
}
fetchCode();
}, [code, language, theme, transformers, decorations]);
return createElement("div", {
dangerouslySetInnerHTML: { __html: codeResult },
...divProps,
});
}
```
## /reflex/.templates/web/jsconfig.json
```json path="/reflex/.templates/web/jsconfig.json"
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"$/*": ["*"],
"@/*": ["public/*"]
}
}
}
```
## /reflex/.templates/web/postcss.config.js
```js path="/reflex/.templates/web/postcss.config.js"
export default {
plugins: {
"postcss-import": {},
autoprefixer: {},
},
};
```
## /reflex/.templates/web/react-router.config.js
```js path="/reflex/.templates/web/react-router.config.js"
export default {
future: {
unstable_optimizeDeps: true,
},
ssr: false,
};
```
## /reflex/.templates/web/styles/__reflex_style_reset.css
```css path="/reflex/.templates/web/styles/__reflex_style_reset.css"
@layer __reflex_base {
/*
1. Prevent padding and border from affecting element width. (https://github.com/mozdevs/cssremedy/issues/4)
2. Remove default margins and padding
3. Reset all borders.
*/
*,
::after,
::before,
::backdrop,
::file-selector-button {
box-sizing: border-box; /* 1 */
margin: 0; /* 2 */
padding: 0; /* 2 */
border: 0 solid; /* 3 */
}
/*
1. Use a consistent sensible line-height in all browsers.
2. Prevent adjustments of font size after orientation changes in iOS.
3. Use a more readable tab size.
4. Use the user's configured `sans` font-family by default.
5. Use the user's configured `sans` font-feature-settings by default.
6. Use the user's configured `sans` font-variation-settings by default.
7. Disable tap highlights on iOS.
*/
html,
:host {
line-height: 1.5; /* 1 */
-webkit-text-size-adjust: 100%; /* 2 */
tab-size: 4; /* 3 */
font-family: --theme(
--default-font-family,
ui-sans-serif,
system-ui,
sans-serif,
"Apple Color Emoji",
"Segoe UI Emoji",
"Segoe UI Symbol",
"Noto Color Emoji"
); /* 4 */
font-feature-settings: --theme(
--default-font-feature-settings,
normal
); /* 5 */
font-variation-settings: --theme(
--default-font-variation-settings,
normal
); /* 6 */
-webkit-tap-highlight-color: transparent; /* 7 */
}
/*
1. Add the correct height in Firefox.
2. Correct the inheritance of border color in Firefox. (https://bugzilla.mozilla.org/show_bug.cgi?id=190655)
3. Reset the default border style to a 1px solid border.
*/
hr {
height: 0; /* 1 */
color: inherit; /* 2 */
border-top-width: 1px; /* 3 */
}
/*
Add the correct text decoration in Chrome, Edge, and Safari.
*/
abbr:where([title]) {
-webkit-text-decoration: underline dotted;
text-decoration: underline dotted;
}
/*
Remove the default font size and weight for headings.
*/
h1,
h2,
h3,
h4,
h5,
h6 {
font-size: inherit;
font-weight: inherit;
}
/*
Reset links to optimize for opt-in styling instead of opt-out.
*/
a {
color: inherit;
-webkit-text-decoration: inherit;
text-decoration: inherit;
}
/*
Add the correct font weight in Edge and Safari.
*/
b,
strong {
font-weight: bolder;
}
/*
1. Use the user's configured `mono` font-family by default.
2. Use the user's configured `mono` font-feature-settings by default.
3. Use the user's configured `mono` font-variation-settings by default.
4. Correct the odd `em` font sizing in all browsers.
*/
code,
kbd,
samp,
pre {
font-family: --theme(
--default-mono-font-family,
ui-monospace,
SFMono-Regular,
Menlo,
Monaco,
Consolas,
"Liberation Mono",
"Courier New",
monospace
); /* 1 */
font-feature-settings: --theme(
--default-mono-font-feature-settings,
normal
); /* 2 */
font-variation-settings: --theme(
--default-mono-font-variation-settings,
normal
); /* 3 */
font-size: 1em; /* 4 */
}
/*
Add the correct font size in all browsers.
*/
small {
font-size: 80%;
}
/*
Prevent `sub` and `sup` elements from affecting the line height in all browsers.
*/
sub,
sup {
font-size: 75%;
line-height: 0;
position: relative;
vertical-align: baseline;
}
sub {
bottom: -0.25em;
}
sup {
top: -0.5em;
}
/*
1. Remove text indentation from table contents in Chrome and Safari. (https://bugs.chromium.org/p/chromium/issues/detail?id=999088, https://bugs.webkit.org/show_bug.cgi?id=201297)
2. Correct table border color inheritance in all Chrome and Safari. (https://bugs.chromium.org/p/chromium/issues/detail?id=935729, https://bugs.webkit.org/show_bug.cgi?id=195016)
3. Remove gaps between table borders by default.
*/
table {
text-indent: 0; /* 1 */
border-color: inherit; /* 2 */
border-collapse: collapse; /* 3 */
}
/*
Use the modern Firefox focus style for all focusable elements.
*/
:-moz-focusring {
outline: auto;
}
/*
Add the correct vertical alignment in Chrome and Firefox.
*/
progress {
vertical-align: baseline;
}
/*
Add the correct display in Chrome and Safari.
*/
summary {
display: list-item;
}
/*
Make lists unstyled by default.
*/
ol,
ul,
menu {
list-style: none;
}
/*
1. Make replaced elements `display: block` by default. (https://github.com/mozdevs/cssremedy/issues/14)
2. Add `vertical-align: middle` to align replaced elements more sensibly by default. (https://github.com/jensimmons/cssremedy/issues/14#issuecomment-634934210)
This can trigger a poorly considered lint error in some tools but is included by design.
*/
img,
svg,
video,
canvas,
audio,
iframe,
embed,
object {
display: block; /* 1 */
vertical-align: middle; /* 2 */
}
/*
Constrain images and videos to the parent width and preserve their intrinsic aspect ratio. (https://github.com/mozdevs/cssremedy/issues/14)
*/
img,
video {
max-width: 100%;
height: auto;
}
/*
1. Inherit font styles in all browsers.
2. Remove border radius in all browsers.
3. Remove background color in all browsers.
4. Ensure consistent opacity for disabled states in all browsers.
*/
button,
input,
select,
optgroup,
textarea,
::file-selector-button {
font: inherit; /* 1 */
font-feature-settings: inherit; /* 1 */
font-variation-settings: inherit; /* 1 */
letter-spacing: inherit; /* 1 */
color: inherit; /* 1 */
border-radius: 0; /* 2 */
background-color: transparent; /* 3 */
opacity: 1; /* 4 */
}
/*
Restore default font weight.
*/
:where(select:is([multiple], [size])) optgroup {
font-weight: bolder;
}
/*
Restore indentation.
*/
:where(select:is([multiple], [size])) optgroup option {
padding-inline-start: 20px;
}
/*
Restore space after button.
*/
::file-selector-button {
margin-inline-end: 4px;
}
/*
Reset the default placeholder opacity in Firefox. (https://github.com/tailwindlabs/tailwindcss/issues/3300)
*/
::placeholder {
opacity: 1;
}
/*
Set the default placeholder color to a semi-transparent version of the current text color in browsers that do not
crash when using `color-mix(…)` with `currentcolor`. (https://github.com/tailwindlabs/tailwindcss/issues/17194)
*/
@supports (not (-webkit-appearance: -apple-pay-button)) /* Not Safari */ or
(contain-intrinsic-size: 1px) /* Safari 17+ */ {
::placeholder {
color: color-mix(in oklab, currentcolor 50%, transparent);
}
}
/*
Prevent resizing textareas horizontally by default.
*/
textarea {
resize: vertical;
}
/*
Remove the inner padding in Chrome and Safari on macOS.
*/
::-webkit-search-decoration {
-webkit-appearance: none;
}
/*
1. Ensure date/time inputs have the same height when empty in iOS Safari.
2. Ensure text alignment can be changed on date/time inputs in iOS Safari.
*/
::-webkit-date-and-time-value {
min-height: 1lh; /* 1 */
text-align: inherit; /* 2 */
}
/*
Prevent height from changing on date/time inputs in macOS Safari when the input is set to `display: block`.
*/
::-webkit-datetime-edit {
display: inline-flex;
}
/*
Remove excess padding from pseudo-elements in date/time inputs to ensure consistent height across browsers.
*/
::-webkit-datetime-edit-fields-wrapper {
padding: 0;
}
::-webkit-datetime-edit,
::-webkit-datetime-edit-year-field,
::-webkit-datetime-edit-month-field,
::-webkit-datetime-edit-day-field,
::-webkit-datetime-edit-hour-field,
::-webkit-datetime-edit-minute-field,
::-webkit-datetime-edit-second-field,
::-webkit-datetime-edit-millisecond-field,
::-webkit-datetime-edit-meridiem-field {
padding-block: 0;
}
/*
Remove the additional `:invalid` styles in Firefox. (https://github.com/mozilla/gecko-dev/blob/2f9eacd9d3d995c937b4251a5557d95d494c9be1/layout/style/res/forms.css#L728-L737)
*/
:-moz-ui-invalid {
box-shadow: none;
}
/*
Correct the inability to style the border radius in iOS Safari.
*/
button,
input:where([type="button"], [type="reset"], [type="submit"]),
::file-selector-button {
appearance: button;
}
/*
Correct the cursor style of increment and decrement buttons in Safari.
*/
::-webkit-inner-spin-button,
::-webkit-outer-spin-button {
height: auto;
}
/*
Make elements with the HTML hidden attribute stay hidden by default.
*/
[hidden]:where(:not([hidden="until-found"])) {
display: none !important;
}
}
```
## /reflex/.templates/web/utils/helpers/dataeditor.js
```js path="/reflex/.templates/web/utils/helpers/dataeditor.js"
import { GridCellKind } from "@glideapps/glide-data-grid";
export function getDEColumn(columns, col) {
let c = columns[col];
c.pos = col;
return c;
}
export function getDERow(data, row) {
return data[row];
}
export function locateCell(row, column) {
if (Array.isArray(row)) {
return row[column.pos];
} else {
return row[column.id];
}
}
export function formatCell(value, column) {
const editable = column.editable ?? true;
switch (column.type) {
case "int":
case "float":
return {
kind: GridCellKind.Number,
data: value,
displayData: value + "",
readonly: !editable,
allowOverlay: editable,
};
case "datetime":
// value = moment format?
case "str":
return {
kind: GridCellKind.Text,
data: value,
displayData: value,
readonly: !editable,
allowOverlay: editable,
};
case "bool":
return {
kind: GridCellKind.Boolean,
data: value,
readonly: !editable,
};
default:
console.log(
"Warning: column.type is undefined for column.title=" + column.title,
);
return {
kind: GridCellKind.Text,
data: value,
displayData: column.type,
};
}
}
export function formatDataEditorCells(col, row, columns, data) {
if (row < data.length && col < columns.length) {
const column = getDEColumn(columns, col);
const rowData = getDERow(data, row);
const cellData = locateCell(rowData, column);
return formatCell(cellData, column);
}
return { kind: GridCellKind.Loading };
}
```
## /reflex/.templates/web/utils/helpers/debounce.js
```js path="/reflex/.templates/web/utils/helpers/debounce.js"
const debounce_timeout_id = {};
/**
* Generic debounce helper
*
* @param {string} name - the name of the event to debounce
* @param {function} func - the function to call after debouncing
* @param {number} delay - the time in milliseconds to wait before calling the function
*/
export default function debounce(name, func, delay) {
const key = `${name}__${delay}`;
clearTimeout(debounce_timeout_id[key]);
debounce_timeout_id[key] = setTimeout(() => {
func();
delete debounce_timeout_id[key];
}, delay);
}
```
## /reflex/.templates/web/utils/helpers/paste.js
```js path="/reflex/.templates/web/utils/helpers/paste.js"
import { useEffect } from "react";
const handle_paste_data = (clipboardData) =>
new Promise((resolve, reject) => {
const pasted_data = [];
const n_items = clipboardData.items.length;
const extract_data = (item) => {
const type = item.type;
if (item.kind === "string") {
item.getAsString((data) => {
pasted_data.push([type, data]);
if (pasted_data.length === n_items) {
resolve(pasted_data);
}
});
} else if (item.kind === "file") {
const file = item.getAsFile();
const reader = new FileReader();
reader.onload = (e) => {
pasted_data.push([type, e.target.result]);
if (pasted_data.length === n_items) {
resolve(pasted_data);
}
};
if (type.indexOf("text/") === 0) {
reader.readAsText(file);
} else {
reader.readAsDataURL(file);
}
}
};
for (const item of clipboardData.items) {
extract_data(item);
}
});
export default function usePasteHandler(target_ids, event_actions, on_paste) {
return useEffect(() => {
const handle_paste = (_ev) => {
event_actions.preventDefault && _ev.preventDefault();
event_actions.stopPropagation && _ev.stopPropagation();
handle_paste_data(_ev.clipboardData).then(on_paste);
};
const targets = target_ids
.map((id) => document.getElementById(id))
.filter((element) => !!element);
if (target_ids.length === 0) {
targets.push(document);
}
targets.forEach((target) =>
target.addEventListener("paste", handle_paste, false),
);
return () => {
targets.forEach((target) =>
target.removeEventListener("paste", handle_paste, false),
);
};
});
}
```
## /reflex/.templates/web/utils/helpers/range.js
```js path="/reflex/.templates/web/utils/helpers/range.js"
/**
* Simulate the python range() builtin function.
* inspired by https://dev.to/guyariely/using-python-range-in-javascript-337p
*
* If needed outside of an iterator context, use `Array.from(range(10))` or
* spread syntax `[...range(10)]` to get an array.
*
* @param {number} start: the start or end of the range.
* @param {number} stop: the end of the range.
* @param {number} step: the step of the range.
* @returns {object} an object with a Symbol.iterator method over the range
*/
export default function range(start, stop, step) {
return {
[Symbol.iterator]() {
if (stop === undefined) {
stop = start;
start = 0;
}
if (step === undefined) {
step = 1;
}
let i = start - step;
return {
next() {
i += step;
if ((step > 0 && i < stop) || (step < 0 && i > stop)) {
return {
value: i,
done: false,
};
}
return {
value: undefined,
done: true,
};
},
};
},
};
}
```
## /reflex/.templates/web/utils/helpers/throttle.js
```js path="/reflex/.templates/web/utils/helpers/throttle.js"
const in_throttle = {};
/**
* Generic throttle helper
*
* @param {string} name - the name of the event to throttle
* @param {number} limit - time in milliseconds between events
* @returns true if the event is allowed to execute, false if it is throttled
*/
export default function throttle(name, limit) {
const key = `${name}__${limit}`;
if (!in_throttle[key]) {
in_throttle[key] = true;
setTimeout(() => {
delete in_throttle[key];
}, limit);
// function was not throttled, so allow execution
return true;
}
return false;
}
```
## /reflex/.templates/web/utils/helpers/upload.js
```js path="/reflex/.templates/web/utils/helpers/upload.js"
import JSON5 from "json5";
import env from "$/env.json";
/**
* Upload files to the server.
*
* @param state The state to apply the delta to.
* @param handler The handler to use.
* @param upload_id The upload id to use.
* @param on_upload_progress The function to call on upload progress.
* @param socket the websocket connection
* @param extra_headers Extra headers to send with the request.
* @param refs The refs object to store the abort controller in.
* @param getBackendURL Function to get the backend URL.
* @param getToken Function to get the Reflex token.
*
* @returns The response from posting to the UPLOADURL endpoint.
*/
export const uploadFiles = async (
handler,
files,
upload_id,
on_upload_progress,
extra_headers,
socket,
refs,
getBackendURL,
getToken,
) => {
// return if there's no file to upload
if (files === undefined || files.length === 0) {
return false;
}
const upload_ref_name = `__upload_controllers_${upload_id}`;
if (refs[upload_ref_name]) {
console.log("Upload already in progress for ", upload_id);
return false;
}
// Track how many partial updates have been processed for this upload.
let resp_idx = 0;
const eventHandler = (progressEvent) => {
const event_callbacks = socket._callbacks.$event;
// Whenever called, responseText will contain the entire response so far.
const chunks = progressEvent.event.target.responseText.trim().split("\n");
// So only process _new_ chunks beyond resp_idx.
chunks.slice(resp_idx).map((chunk_json) => {
try {
const chunk = JSON5.parse(chunk_json);
event_callbacks.map((f, ix) => {
f(chunk)
.then(() => {
if (ix === event_callbacks.length - 1) {
// Mark this chunk as processed.
resp_idx += 1;
}
})
.catch((e) => {
if (progressEvent.progress === 1) {
// Chunk may be incomplete, so only report errors when full response is available.
console.log("Error processing chunk", chunk, e);
}
return;
});
});
} catch (e) {
if (progressEvent.progress === 1) {
console.log("Error parsing chunk", chunk_json, e);
}
return;
}
});
};
const controller = new AbortController();
const formdata = new FormData();
// Add the token and handler to the file name.
files.forEach((file) => {
formdata.append("files", file, file.path || file.name);
});
// Send the file to the server.
refs[upload_ref_name] = controller;
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
// Set up event handlers
xhr.onload = function () {
if (xhr.status >= 200 && xhr.status < 300) {
resolve({
data: xhr.responseText,
status: xhr.status,
statusText: xhr.statusText,
headers: {
get: (name) => xhr.getResponseHeader(name),
},
});
} else {
reject(new Error(`HTTP error! status: ${xhr.status}`));
}
};
xhr.onerror = function () {
reject(new Error("Network error"));
};
xhr.onabort = function () {
reject(new Error("Upload aborted"));
};
// Handle upload progress
if (on_upload_progress) {
xhr.upload.onprogress = function (event) {
if (event.lengthComputable) {
const progressEvent = {
loaded: event.loaded,
total: event.total,
progress: event.loaded / event.total,
};
on_upload_progress(progressEvent);
}
};
}
// Handle download progress with streaming response parsing
xhr.onprogress = function (event) {
if (eventHandler) {
const progressEvent = {
event: {
target: {
responseText: xhr.responseText,
},
},
progress: event.lengthComputable ? event.loaded / event.total : 0,
};
eventHandler(progressEvent);
}
};
// Handle abort controller
controller.signal.addEventListener("abort", () => {
xhr.abort();
});
// Configure and send request
xhr.open("POST", getBackendURL(env.UPLOAD));
xhr.setRequestHeader("Reflex-Client-Token", getToken());
xhr.setRequestHeader("Reflex-Event-Handler", handler);
for (const [key, value] of Object.entries(extra_headers || {})) {
xhr.setRequestHeader(key, value);
}
try {
xhr.send(formdata);
} catch (error) {
reject(error);
}
})
.catch((error) => {
console.log("Upload error:", error.message);
return false;
})
.finally(() => {
delete refs[upload_ref_name];
});
};
```
## /reflex/.templates/web/utils/react-theme.js
```js path="/reflex/.templates/web/utils/react-theme.js"
import {
createContext,
useContext,
useState,
useEffect,
createElement,
useRef,
useMemo,
} from "react";
import { isDevMode, defaultColorMode } from "$/utils/context";
const ThemeContext = createContext({
theme: defaultColorMode,
resolvedTheme: defaultColorMode !== "system" ? defaultColorMode : "light",
setTheme: () => {},
});
export function ThemeProvider({ children, defaultTheme = "system" }) {
const [theme, setTheme] = useState(defaultTheme);
const [systemTheme, setSystemTheme] = useState(
defaultTheme !== "system" ? defaultTheme : "light",
);
const [isInitialized, setIsInitialized] = useState(false);
const firstRender = useRef(true);
useEffect(() => {
if (!firstRender.current) {
return;
}
firstRender.current = false;
if (isDevMode) {
const lastCompiledTheme = localStorage.getItem("last_compiled_theme");
if (lastCompiledTheme !== defaultColorMode) {
// on app startup, make sure the application color mode is persisted correctly.
localStorage.setItem("last_compiled_theme", defaultColorMode);
setIsInitialized(true);
return;
}
}
// Load saved theme from localStorage
const savedTheme = localStorage.getItem("theme") || defaultTheme;
setTheme(savedTheme);
setIsInitialized(true);
});
const resolvedTheme = useMemo(
() => (theme === "system" ? systemTheme : theme),
[theme, systemTheme],
);
useEffect(() => {
// Set up media query for system preference detection
const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");
// Listen for system preference changes
const handleChange = () => {
setSystemTheme(mediaQuery.matches ? "dark" : "light");
};
handleChange();
mediaQuery.addEventListener("change", handleChange);
return () => {
mediaQuery.removeEventListener("change", handleChange);
};
});
// Save theme to localStorage whenever it changes
// Skip saving only if theme key already exists and we haven't initialized yet
useEffect(() => {
const existingTheme = localStorage.getItem("theme");
if (!isInitialized && existingTheme !== null) return;
localStorage.setItem("theme", theme);
}, [theme]);
useEffect(() => {
if (!isInitialized) return;
const root = window.document.documentElement;
root.classList.remove("light", "dark");
root.classList.add(resolvedTheme);
root.style.colorScheme = resolvedTheme;
}, [resolvedTheme, isInitialized]);
return createElement(
ThemeContext.Provider,
{ value: { theme, resolvedTheme, setTheme } },
children,
);
}
export function useTheme() {
return useContext(ThemeContext);
}
```
## /reflex/.templates/web/vite-plugin-safari-cachebust.js
```js path="/reflex/.templates/web/vite-plugin-safari-cachebust.js"
/* vite-plugin-safari-cachebust.js
*
* Rewrite modulepreload <link> tags and ESM imports to include a cache-busting
* query parameter for Safari browser.
*
* https://github.com/remix-run/react-router/issues/12761
*
* The issue seems to be Safari over-aggressive caching of ESM imports (and modulepreload)
* which does not respect the cache-control headers sent by the server. This approach
* allows hot reload to work in Safari when adding routes or changing dependencies.
*
* No equivalent transformation is needed for production builds, as the
* output already contains the file hash in the name.
*/
/**
* @typedef {import('vite').Plugin} Plugin
* @typedef {import('vite').ViteDevServer} ViteDevServer
* @typedef {import('http').IncomingMessage} IncomingMessage
* @typedef {import('http').ServerResponse} ServerResponse
* @typedef {import('connect').NextHandleFunction} NextHandleFunction
*/
const pluginName = "vite-plugin-safari-cachebust";
/**
* Creates a Vite plugin that adds cache-busting for Safari browsers
* @returns {Plugin} The Vite plugin
*/
export default function safariCacheBustPlugin() {
return {
name: pluginName,
/**
* Configure the dev server with the Safari middleware
* @param {ViteDevServer} server - The Vite dev server instance
*/
configureServer(server) {
server.middlewares.use(createSafariMiddleware());
},
};
}
/**
* Determines if the user agent is Safari
* @param {string} ua - The user agent string
* @returns {boolean} True if the browser is Safari
*/
function isSafari(ua) {
return /Safari/.test(ua) && !/Chrome/.test(ua);
}
/**
* Creates a middleware that adds cache-busting for Safari browsers
* @returns {NextHandleFunction} The middleware function
*/
function createSafariMiddleware() {
// Set when a log message for rewriting n links has been emitted.
let _have_logged_n = -1;
/**
* Rewrites module import links in HTML content with cache-busting parameters
* @param {string} html - The HTML content to process
* @returns {string} The processed HTML content
*/
function rewriteModuleImports(html) {
const currentTimestamp = new Date().getTime();
const parts = html.split(/(<link\s+rel="modulepreload"[^>]*>)/g);
/** @type {[string, string][]} */
const replacements = parts
.map((chunk) => {
const match = chunk.match(
/<link\s+rel="modulepreload"\s+href="([^"]+)"(.*?)\/?>/,
);
if (!match) return;
const [fullMatch, href, rest] = match;
if (/^(https?:)?\/\//.test(href)) return;
try {
const newHref = href.includes("?")
? `${href}&__reflex_ts=${currentTimestamp}`
: `${href}?__reflex_ts=${currentTimestamp}`;
return [href, newHref];
} catch {
// no worries;
}
})
.filter(Boolean);
if (replacements.length && _have_logged_n !== replacements.length) {
_have_logged_n = replacements.length;
console.debug(
`[${pluginName}] Rewrote ${replacements.length} modulepreload links with __reflex_ts param.`,
);
}
return replacements.reduce((accumulator, [target, replacement]) => {
return accumulator.split(target).join(replacement);
}, html);
}
/**
* Middleware function to handle Safari cache busting
* @param {IncomingMessage} req - The incoming request
* @param {ServerResponse} res - The server response
* @param {(err?: any) => void} next - The next middleware function
* @returns {void}
*/
return function safariCacheBustMiddleware(req, res, next) {
const ua = req.headers["user-agent"] || "";
// Remove our special cache bust query param to avoid affecting lower middleware layers.
if (
req.url &&
(req.url.includes("?__reflex_ts=") || req.url.includes("&__reflex_ts="))
) {
req.url = req.url.replace(/(\?|&)__reflex_ts=\d+/, "");
return next();
}
// Only apply this middleware for Safari browsers.
if (!isSafari(ua)) return next();
// Only transform requests that want HTML.
const header_accept = req.headers["accept"] || "";
if (
typeof header_accept !== "string" ||
!header_accept.includes("text/html")
) {
return next();
}
let buffer = "";
const _end = res.end.bind(res);
res.setHeader("x-modified-by", "vite-plugin-safari-cachebust");
/**
* Overridden write method to collect chunks
* @param {any} chunk - The chunk to write
* @param {...any} args - Additional arguments
* @returns {boolean} Result of the write operation
*/
res.write = function (chunk, ...args) {
buffer += chunk instanceof Buffer ? chunk.toString("utf-8") : chunk;
return true;
};
/**
* Overridden end method to process and send the final response
* @param {any} chunk - The final chunk to write
* @param {...any} args - Additional arguments
* @returns {ServerResponse<IncomingMessage>} The server response
*/
res.end = function (chunk, ...args) {
if (chunk) {
buffer += chunk instanceof Buffer ? chunk.toString("utf-8") : chunk;
}
buffer = rewriteModuleImports(buffer);
return _end(buffer, ...args);
};
return next();
};
}
```
## /reflex/__main__.py
```py path="/reflex/__main__.py"
"""reflex package invocation entry point."""
from .reflex import cli
if __name__ == "__main__":
cli()
```
## /reflex/admin.py
```py path="/reflex/admin.py"
"""The Reflex Admin Dashboard."""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from starlette_admin.base import BaseAdmin as Admin
@dataclass
class AdminDash:
"""Data used to build the admin dashboard."""
models: list = field(default_factory=list)
view_overrides: dict = field(default_factory=dict)
admin: Admin | None = None
```
## /reflex/app_mixins/__init__.py
```py path="/reflex/app_mixins/__init__.py"
"""Reflex AppMixins package."""
from .lifespan import LifespanMixin
from .middleware import MiddlewareMixin
from .mixin import AppMixin
```
## /reflex/app_mixins/mixin.py
```py path="/reflex/app_mixins/mixin.py"
"""Default mixin for all app mixins."""
import dataclasses
@dataclasses.dataclass
class AppMixin:
"""Define the base class for all app mixins."""
def _init_mixin(self):
"""Initialize the mixin.
Any App mixin can override this method to perform any initialization.
"""
```
## /reflex/compiler/__init__.py
```py path="/reflex/compiler/__init__.py"
"""The Reflex compiler."""
```
## /reflex/components/__init__.py
```py path="/reflex/components/__init__.py"
"""Import all the components."""
from __future__ import annotations
from reflex.utils import lazy_loader
_SUBMODULES: set[str] = {
"lucide",
"core",
"datadisplay",
"gridjs",
"markdown",
"moment",
"plotly",
"radix",
"react_player",
"react_router",
"sonner",
"el",
"base",
"recharts",
}
_SUBMOD_ATTRS: dict[str, list[str]] = {
"component": [
"Component",
"NoSSRComponent",
],
}
__getattr__, __dir__, __all__ = lazy_loader.attach(
__name__,
submodules=_SUBMODULES,
submod_attrs=_SUBMOD_ATTRS,
)
```
## /reflex/components/base/__init__.py
```py path="/reflex/components/base/__init__.py"
"""Base components."""
from __future__ import annotations
from reflex.utils import lazy_loader
_SUBMODULES: set[str] = {"app_wrap", "bare"}
_SUBMOD_ATTRS: dict[str, list[str]] = {
"body": ["Body"],
"document": ["Scripts", "Outlet", "ScrollRestoration", "Links", "Meta"],
"fragment": [
"Fragment",
"fragment",
],
"error_boundary": [
"ErrorBoundary",
"error_boundary",
],
"link": ["RawLink", "ScriptTag"],
"meta": ["Description", "Image", "Meta", "Title"],
"script": ["Script", "script"],
}
__getattr__, __dir__, __all__ = lazy_loader.attach(
__name__,
submodules=_SUBMODULES,
submod_attrs=_SUBMOD_ATTRS,
)
```
## /reflex/components/base/app_wrap.py
```py path="/reflex/components/base/app_wrap.py"
"""Top-level component that wraps the entire app."""
from reflex.components.base.fragment import Fragment
from reflex.components.component import Component
from reflex.vars.base import Var
class AppWrap(Fragment):
"""Top-level component that wraps the entire app."""
@classmethod
def create(cls) -> Component:
"""Create a new AppWrap component.
Returns:
A new AppWrap component containing {children}.
"""
return super().create(Var(_js_expr="children"))
```
The content has been capped at 50000 tokens. The user could consider applying other filters to refine the result. The better and more specific the context, the better the LLM can follow instructions. If the context seems verbose, the user can refine the filter using uithub. Thank you for using https://uithub.com - Perfect LLM context for any GitHub repo.