* cache order of imports that create BaseState subclasses
* Track which pages create State subclasses during evaluation
These need to be replayed on the backend to ensure state alignment.
* Clean up: use constants, remove unused code
Handle closing files with contextmanager
* Expose app.add_all_routes_endpoint for flexgen
* Include .web/backend directory in backend.zip when exporting
* components deserve to be first class props
* default back to {}
* smarter yield
* how much does caching help?
* only hit the slower path on _are_fields_known
* remove the cache thingy
* cache the inner _get_component_prop_names
* oops
* dang it darglint
* refactor things a bit
* fix events
* give option to only use main thread
* change default to main thread
* fix comment
* default to None, as 0 would raise a ValueError
Co-authored-by: Masen Furer <m_github@0x26.net>
* add warning about passing 0
* move executor to config
---------
Co-authored-by: Masen Furer <m_github@0x26.net>
* import var perf improvements
* use tuples over iterator
* the only thing that matters
* maybe tuple map is faster than tuple list comprehension
* do it in one list comprehension
* standarize filename from upload
* all my friends hate fast api upload file
* make deprecated filename private
* lstrip the "/"
Co-authored-by: Masen Furer <m_github@0x26.net>
---------
Co-authored-by: Masen Furer <m_github@0x26.net>
* adjust setter to include type annotation
* apparently this discovered some bugs
* remove some pyright ignores
* add str to int/float conversion
* dang it darglint
* handle port better
* setting port via envvar is possible again
* change default deploy_url and api_url
* fix for review
* update docstring
* type new envvar as optional
* [ENG-4647] Fix env_file handling
* Import dotenv.load_dotenv early to avoid ImportError while loading
rxconfig.py
* Read ENV_FILE from the environment explicitly.
fix#4803
* Config.Config: use_enum_values = False
Save enum fields as the enum object rather than the value.
* raise error when passing a str(var)
* make it faster
* fix typo
* fix tests
* mocker consistency
Co-authored-by: Thomas Brandého <thomas.brandeho@gmail.com>
* ditto
Co-authored-by: Thomas Brandého <thomas.brandeho@gmail.com>
---------
Co-authored-by: Thomas Brandého <thomas.brandeho@gmail.com>
* move overlays to _app.js
* fix unit tests
* fix dynamic imports app
* fix unit cases once again
* clear custom compoent cache between app harness tests
* Sticky tweaks: only show in prod mode
Only display the sticky badge in prod mode.
Display the mini-badge for mobile and tablet; full badge only displayed at
desktop width.
* Remove localhost checking
* fix bun path handling and add a test
* fix flags
* fix tests
* fix unit tests and mock object
* fix units test again
* revert some changes for now
* remove unused test
* allow gunicorn worker to be disabled
* allow gunicorn worker to be disabled
* rewrite the command
---------
Co-authored-by: Khaleel Al-Adhami <khaleel.aladhami@gmail.com>
* Add path_ops.update_directory_tree:
Copy missing and newer files from src to dest
* add console.timing context
Log debug messages with timing for different processes.
* Update assets tree as app._compile step.
If the assets change between hot reload, then update them before reloading (in
case a CSS file was added or something).
* Add timing for other app._compile events
* Only copy assets if assets exist
* Fix docstring for update_directory_tree
* increase nested type checking for component var types
* handle mapping as dict in type hint
* fix weird cases of using _isinstance instead of isinstance
* test out nested=0
* move union below
* don't use _instance for simple unions
* add a config variable to add extra overlay components
* add integration test
* Apply suggestions from code review
---------
Co-authored-by: Masen Furer <m_github@0x26.net>
* move benchmarks and add some more
* change key and paths
* parametrize tests
* more specific ignore
* rename fixture
* remove previous file
* add tests for _compile_stateful_components
* remove base_state from event types
* pyi that guy
* unpack is new
* woops
* use type alias type to remove ambiguity of where types go
* use same thing with LAMBDA_OR_STATE
* do it for event type
* add the watermark class
* remove shortcut exposing badge publicly for now
* Rename as "sticky" because "watermark" has a negative connotation
* Add config `show_built_with_reflex`
This config option is available for authenticated users on various plan tiers
* py3.11 compatible f-string
* sticky badge inherit from A instead of using on_click/redirect
* fix integration test
* Move export checking logic to reflex CLI
* rx.logo: make it accessible to screen readers
Add role="img" aria_label="Reflex" and title="Reflex".
* Hide the built with reflex badge for localhost
* Revert "fix integration test"
This reverts commit a978684d70.
* experimental: do not show warning for internal imports
Only show experimental feature warnings when accessing the names through the
rx._x namespace.
If reflex internally imports the names via deep imports, then this bypasses the
warning to avoid showing it to users that have no control over how the
framework uses experimental features.
* add help link for show_built_with_reflex option
* pre-commit fixes
---------
Co-authored-by: Masen Furer <m_github@0x26.net>
* improve rx.Field ObjectVar typing for sqlalchemy and dataclasses
* enable parametrized objectvar tests for sqlamodel and dataclass
* improve typing for ObjectVars in ArrayVars
* ruffing
* drop duplicate objectvar import
* remove redundant overload
* allow optional hints in rx.Field annotations to resolve to the correct var type
* disable react strict mode for event loop
* oops
* pyi oui
* separate socket connection from event loop
* prettier state.js
* disable react strict mode
* didn't work sadge
* socket connect/disconnect depends on new isBackendDisabled state
* only start the event loop when the socket is set or we're not stateful
* Always drain the queue unless backend is disabled
---------
Co-authored-by: Masen Furer <m_github@0x26.net>
* WiP
* Save the var from get_var_name
* flatten StateManagerRedis.get_state algorithm
simplify fetching of states and avoid repeatedly fetching the same state
* Get all the states in a single redis round-trip
* update docstrings in StateManagerRedis
* Move computed var dep tracking to separate module
* Fix pre-commit issues
* ComputedVar.add_dependency: explicitly dependency declaration
Allow var dependencies to be added at runtime, for example, when defining a
ComponentState that depends on vars that cannot be known statically.
Fix more pyright issues.
* Fix/ignore more pyright issues from recent merge
* handle cleaning out _potentially_dirty_states on reload
* ignore accessed attributes missing on state class
these might be added dynamically later in which case we recompute the
dependency tracking dicts... if not, they'll blow up anyway at runtime.
* fix playwright tests, which insist on running an asyncio loop
---------
Co-authored-by: Khaleel Al-Adhami <khaleel.aladhami@gmail.com>
* add backend disabled dialog
* pyi that guy
* pyi the other guy
* extend test_connection_banner to also test the cloud banner
* oops, need asyncio _inside_ the app
* Update reflex/components/core/banner.py
Co-authored-by: Masen Furer <m_github@0x26.net>
* use universal cookies
* fix pre-commit
* revert universal cookie 🍪
---------
Co-authored-by: Masen Furer <m_github@0x26.net>
* add codspeed
* add codspeed to dev deps
* poetry.lock: relock deps, no update
* add poetry run
* only compile components
* at least have something
* fix hash
* dang it darglint
* uwu
* test sorting algorithms
* test sort
* sad
* revert that guy
* add test_evaluate
* it's ruff out there
* delete test_sort
---------
Co-authored-by: Masen Furer <m_github@0x26.net>
* Handle python `range` passed to rx.Var.create
Fix the range function to use Math.ceil to handle jagged steps.
Update test cases.
* Set ToVarOperation.__qualname__ for better repr
* add more type annotations through the code
* add typing in reflex/utils
* misc typing
* more typings
* state typing
* keep typing
* typing init and utils
* more typing for components
* fix attempt for 3.9
* need more __future
* more typings
* type event plz
* type model
* type vars/base.py
* enable 'ANN001' for reflex folder (ignore tests and benchmarks)
* fix pyi
* add missing annotations
* use more precise error when ignoring
* rename private fields with leading underscore in App
* fix constants API
* fix public API for some attributes of App()
* fix conflicts properly 🙈
* remove extra private
---------
Co-authored-by: Masen Furer <m_github@0x26.net>
Co-authored-by: Khaleel Al-Adhami <khaleel.aladhami@gmail.com>
* Fix setting default color mode in dev mode
Without this, the last_compiled_timestamp local storage never gets set because
it's always `null` until it gets set.
* test_client_storage: also pop `theme` key from next-themes
* relock backend deps
* bump frontend library versions
* go back to react 18.3
* revert to react 18.3.1 (as it was before)
* reflex-web keep reflex from current revision, rather than main
* relock backend deps (again)
* don't check ag-grid version on main repo
* config_path is passed via `extra` to avoid pyright error when None
* bump next again
---------
Co-authored-by: Lendemor <thomas.brandeho@gmail.com>
* remove deprecated features and support for py3.9
* remove other deprecated stuff
* update lock file
* fix units tests
* relock poetry
* fix _replace for computed_var
* fix some merge typo
* fix typing of deploy args
* fix benchmarks.yml versions
* console.error instead of raising Exception
* fix tests
* ignore lambdas when resolving annotations
* simplify redirect logic in event.py
* more fixes
* fix unit tests again
* give back default annotations for lambdas
* fix signature check for on_submit
* remove useless stuff
* update pyi
* readd the getattr
* raise if log_level is wrong type
* silly goose, loglevel is a subclass of str
* i don't believe this code
* add guard
---------
Co-authored-by: Khaleel Al-Adhami <khaleel.aladhami@gmail.com>
* make object var handle all mapping instead of just dict
* unbreak ci
* get it right pyright
* create generic variable for field
* add support for typeddict (to some degree)
* import from extensions
Obviously we still have to evaluate the pages to make sure we know about all
states, but not saving them to `App.pages` dict reduces high-line memory usage
for backend-only process from ~900Mb to ~530Mb on reflex-web.
* Allow custom app module in rxconfig
* what was that pyscopg mess?
* fix another mess
* get this working with relative imports and hot reload
* typing to named tuple
* minor refactor
* revert redis knobs positions
* fix pyright except 1
* fix pyright hopefully
* use the resolved module path
* testing workflow
* move nba-proxy job to counter job
* just cast the type
* fix tests for python 3.9
* darglint
* CR Suggestions for #4556 (#4644)
* reload_dirs: search up from app_module for last directory containing __init__
* Change custom app_module to use an import string
* preserve sys.path entries added while loading rxconfig.py
---------
Co-authored-by: Masen Furer <m_github@0x26.net>
* Show file and line number in deprecation warnings
* Exclude modules/packages by import
Less bespoke method of considering some packages to be part of the framework
and passed over when finding user code.
* [ENG-4351] Add mapping for lucide icons
For icon names that don't auto-translate to the correct lucide tag name,
provide manual override.
Fix#4621
* account for new mapping in unit tests
Instead of potentially defining `_LANGUAGE` constant twice in a component,
simply pass the language prop directly to the hook generator function.
If no language is passed, then it defaults to `_LANGUAGE`, which continues to
work for markdown component_map use case.
* unbreak link _hover
* add a test to catch the error
* change tmp path for harness
* add () to fixture
* add spacer to avoid initial hover
* only install chromium browser for faster ci
---------
Co-authored-by: Lendemor <thomas.brandeho@gmail.com>
* Enable automatic retry on redis errors
ExponentialBackoff 3x retry for BusyLoadingError, ConnectionError, and TimeoutError
* retry on any redis error
* Use default single-retry for any RedisError
Using the default Retry means that async and sync clients get the appropriate type of Retry
* use position in vardata to mark internal hooks
* update all render to use position
* use macros for rendering
* reduce number of iterations over hooks during rendering
* cleanup code and add typing
* add __future__
* use new macros to render component maps in markdown
* remove calls to _get_all_hooks_internal
* fix typo
* forgot to replace this
* unnecessary expand in utils.py
DeprecationWarning: Default non-cached rx.var has been deprecated in version
0.6.8 the default value will be `@rx.var(cache=True)` in a future release. To
retain uncached var, explicitly pass `@rx.var(cache=False)`. It will be
completely removed in 0.7.0
* [ENG-2157] [Refix] Allow `rx.download` to resolve `rx.get_upload_url`
Update the special case in a way that works with the new Var system and its
unstoppable determination to concatenate strings instead of using template
string
This has been broken since 0.6.0, so a regression test was added to avoid
future inadvertant breakage.
Fix#2812 (again)
* use safer indirect eval
* Proxy backend requests on '/' to the frontend
If the optional extra `proxy` is installed, then the backend can handle all
requests by proxy unrecognized routes to the frontend nextjs server.
* Update lock file
* pre-commit fu
* AppHarness: set config frontend_port and backend_port
* integration: frontend port and backend port should return the same content
with proxying enabled by default in dev mode, both frontend and backend ports
on / should return the same content.
* Retry up to 100 times when proxying to frontend
* Reduce retry attempts to 25
Fix log level passing to subprocess
* scripts/wait_for_listening_port: primarily check HTTP responses
if the port is up or not, we don't really care... the HTTP request needs to
work and not return errors
* aiohttp is an optional dep
* adapt integration.sh for --backend-only (counter integration test)
* woops
* windows WTF?
* scratching my head 🎄
* double WTF windows
* Fix remaining integration tests
The default behavior for EventSpec is to treat the spec as a partial, wherein
if additional unfilled arguments are available, and the event trigger wants to
pass additional arguments, they will be applied positionally.
However, it never makes sense to fill in `callback` with an event trigger arg.
Therefore, if the callback is not provided initially, set it to None explicitly
so that some invalid value cannot be added later.
* BaseState.get_var_value helper to get a value from a Var
When given a state Var or a LiteralVar, retrieve the actual value associated
with the Var.
For state Vars, the returned value is directly tied to the associated state and
can be modified.
Modifying LiteralVar values or ComputedVar values will have no useful effect.
* Use Var[VAR_TYPE] annotation to take advantage of generics
This requires rx.Field to pass typing where used.
* Add case where get_var_value gets something that's not a var
* [ENG-4083] Track internal changes in dataclass instances
Create a dynamic subclass of MutableProxy with `__dataclass_fields__` set
according to the dataclass being wrapped.
* support dataclasses.asdict on MutableProxy instances
The ability to convert `EventType` arguments into `EventChain` is crucial for
wrapping JS libraries that need to pass event handlers via hooks or
other non-component centric interfaces.
Improve typing such that wrapped components accepting `EventType` arguments can
be directly converted to `EventChain` / `EventChainVar` to be rendered as JS
code.
* fix memoized event trigger order
* allow to declare deps in event signature for memoized event triggers
* clean up the code to pass tests
* handle position of hooks
* clean up code
* revert test changes
* add future annotations
* remove non-necessary stuff
* reuse data_callback name if already set during first call to add_hooks
* remove HookVar and use Var with VarData instead
* remove test change
* readd removed line
* fix order of stmt for cleaner code
* fix typing
* something broke during the merge I guess
* remove hack and pass proper const for position
* oops, bad syntax in jinja
* use "hook_position" instead of "hook_positions"
match the name of the enum
---------
Co-authored-by: Masen Furer <m_github@0x26.net>
* add datetime var operations
* add future annotations
* add LiteralDatetimeVar
* remove methods that don't apply
* fix serialization
* add unit and integrations test
* oops, forgot to commit that important change
* Include step attribute in input
* Remove `step` prop from TextField
it is inherited from Input, and does not need to be redefined
---------
Co-authored-by: Masen Furer <m_github@0x26.net>
* Use empty string for None values in `rx.input` and `rx.el.input`
* fix tests
* fix pyi scripts
* use nullish coalescing operator
* fix unit tests
* use ternary operator so old browsers and dynamic components tests pass
* address comment on doing this only for optionals
* Fix tests
* pyright!
* fix comments
* Throw warnings when Redis lock is held for more than the allowed threshold
* initial tests
* fix tests and address comments
* fix tests fr, and use pydantic validators
* darglint fix
* increase lock expiration in tests to 2500
* remove print statement
---------
Co-authored-by: Khaleel Al-Adhami <khaleel.aladhami@gmail.com>
* [ENG-4165] Consider default and default_factory for state vars
When determining whether a state var should be marked as optional, check that
it is missing both default and default_factory and is not required.
Fix#4471
* add test for default factory with rx.foreach (#4515)
---------
Co-authored-by: benedikt-bartscher <31854409+benedikt-bartscher@users.noreply.github.com>
* Avoid double JSON encode/decode for socket.io
socket.io (python and js) already has a built in mechanism for JSON encoding
and decoding messages over the websocket. To use it, we pass a custom `json`
namespace which uses `format.json_dumps` (leveraging reflex serializers) to encode the
messages. This avoids sending a JSON-encoded string of JSON over the wire, and
reduces the number of serialization/deserialization passes over the message
data.
The side benefit is that debugging websocket messages in browser tools displays
the parsed JSON hierarchy and is much easier to work with.
* JSON5.parse in on_upload_progress handler responses
* use `macos-latest` runner
macos-12 is deprecated and the jobs don't start anymore, so see if we can run
fine on latest.
* unit_tests.yml: use python versions with arm64 builds
* add eradicate rules for commented out code
* remove output change
* fix pyi messed up indent
* fix pyi again
* fix layout docstring
* fix pyi_generator to remove commented out props from docs
* fix pyi_generator and regenerate some pyi
* fix double strip
* update all pyi
* try to fix stuff in pyi_gen
* whatever
* remove that maybe? i don't know
* fix that shit?
* fix more shit, idk
* better not see you ever again, extra line
* fix: handle default_factory in get_attribute_access_type, add tests for sqla dataclasses
* only test classes which have default_factory + add test for no default
* add test for color mode (initial and toggle)
* add css check
* add page reload in the tests
* update test to catch the appearance regression
* don't render the appearance prop of rx.theme
* Reuse the sqlalchemy engine once it's created
* Implement `rx.asession` for async database support
Requires setting `async_db_url` to the same database as `db_url`, except using
an async driver; this will vary by database.
* resolve the url first, so the key into _ENGINE is correct
* Ping db connections before returning them from pool
Move connect engine kwargs to a separate function
* the param is `echo`
* sanity check that config db_url and async_db_url are the same
throw a warning if the part following the `://` differs between these two
* create_async_engine: use sqlalchemy async API
update types
* redact ASYNC_DB_URL similarly to DB_URL when overridden in config
* update rx.asession docstring
* use async_sessionmaker
* Redact sensitive env vars instead of hiding them
* Add production-one-port example
A more complex version of simple-one-port that facilitates better layer caching
to shorten build times and multi-stage build to reduce final image size.
Harder to understand, but ultimately nicer to use.
* fix Caddyfile format to avoid complaints
* docker-examples: bump all base images to python:3.13
* rx.upload must include _var_data from props
str-casting the dropzone arguments removed any VarData they depended on, like
the state context.
update test_upload to include passing a prop from a state var
* Handle large payload delta from upload event handler
Fix update chunk chaining logic; try/catch wasn't catching errors from the
async inner function.
* Unit test updates
* test_client_storage: simulate backend state expiry
* [HOS-333] Send a "reload" message to the frontend after state expiry
1. a state instance expires on the backing store
2. frontend attempts to process an event against the expired token and gets a
fresh instance of the state without router_data set
3. backend sends a "reload" message on the websocket containing the event and
immediately stops processing
4. in response to the "reload" message, frontend sends
[hydrate, update client storage, on_load, <previous_event>]
This allows the frontend and backend to re-syncronize on the state of the app
before continuing to process regular events.
If the event in (2) is a special hydrate event, then it is processed normally
by the middleware and the "reload" logic is skipped since this indicates an
initial load or a browser refresh.
* unit tests working with redis
On py3.9 and py3.10, `dict[str, str]` and other typing forms are kinda
considered classes, but they still fail when doing `issubclass`, so
specifically exclude generic aliases before calling issubclass.
Fix#4424
Bonus fix: support upcasting of pydantic v1 and v2 models
* wip rx._x.asset improvements
* only add symlink if it doesn't already exist
* minor improvements, add more tests
* use deprecated Generator for python3.8 support
* improve docstring
* only allow explicit shared, only validate local assets if not backend_only
* fix darglint
* allow setting backend only env to false.
* use new is_backend_only in assets
* ruffing
* Move to `rx.asset`, retain old API in `rx._x.asset`
---------
Co-authored-by: Masen Furer <m_github@0x26.net>
* [ENG-3953] Support pydantic BaseModel (v1 and v2) as state var
Provide serializers and mutable proxy tracking for pydantic models directly.
* conditionally define v2 serializer
Co-authored-by: Khaleel Al-Adhami <khaleel.aladhami@gmail.com>
* Add `MutableProxy._is_mutable_value` to avoid duplicate logic
* Conditionally import BaseModel to handle older pydantic v1 versions
* pre-commit fu
---------
Co-authored-by: Khaleel Al-Adhami <khaleel.aladhami@gmail.com>
* Rework Init workflow
* minor format
* refactor
* add comments
* fix pyright alongside some improvements
* add demolink for blank template
* fix darglint
* Add more templates and keep template name in kebab case
* revert getting other templates since we'll use the submodules approach
* remove debug statement
* Improvements based on standup comments
* Add redirect logic
* changes based on new flow
---------
Co-authored-by: Masen Furer <m_github@0x26.net>
When an event/event spec is marked as "temporal", it will not be queued unless
the backend is up. This can be used to prevent periodic events (like from
`rx.moment`) from queueing up while the backend is down, and then stampeding
when the backend comes up and the queue is drained. It can be used to avoid
processing many periodic events at once when the app is only expecting to
process such an event every so often.
* Handle Var passed to `rx.toast`
If the user provides a `Var` for `message` then apply it as `props["title"]` to
avoid a var operations error.
* remove unnecessary parentheses
* remove weird hacks
* get it right pyright
---------
Co-authored-by: Khaleel Al-Adhami <khaleel.aladhami@gmail.com>
In some cases, a routing failure can cause the failure to be cached. When the
router has a cached failure, pushing such a route will never call
routeChangeComplete, and thus on_load event will never be fired for that route.
Purposely clearing the error from the router allows the page to properly load
on subsequent attempts without refreshing the app.
The `rich` module should be set to `None`, indicating that rich should not be used.
Setting it to `False` worked before, but recently added code in typer fails
when checking `if rich is not None`.
ref: https://github.com/fastapi/typer/pull/847
* add typing to function vars
* import ParamSpec from typing_extensions
* remove ellipsis as they are not supported in 3.9
* try importing everything from extensions
* special case 3.9
* don't use Any from extensions
* get typevar from extensions
Because of some dodgy logic in Base.get_value and State.dict / State.get_delta
when the value of some state var X happened to be the name of another var in
the state Y, then the value for X would be returned as the value of Y.
wat.
Fixes#4369
* Temporarily downpin @radix-ui/themes <3.1.5
A visual/style regression was introduced in @radix-ui/themes 3.1.5
as described in radix-ui/themes#627 which reflex needs to avoid.
* Get expected radix library version from component
* Astral 0.5.0 path change
https://github.com/astral-sh/uv/releases
Use XDG (i.e. ~/.local/bin) instead of the Cargo home directory in the installer
* Fix path in production-app-platform example
---------
Co-authored-by: Masen Furer <m_github@0x26.net>
These are useful for typing purposes and should be exposed at the top level to
avoid requiring deep imports from subpackages that we may need to change later.
* Codeblock cleanup in markdown
* Initial approach to getting this working with rx.memo and reflex web
* abstract the map var logic
* the tests are not valid + pyright fix
* darglint fix
* Add unit tests plus mix components
* pyi run
* rebase on main
* fix darglint
* testing different OS
* revert
* This should fix it. Right?
* Fix tests
* minor fn signature fix
* use ArgsFunctionOperation
* use destructured args and pass the tests
* fix remaining unit tests
* fix pyi files
* rebase on main
* move language regex on codeblock to markdown
* fix tests
---------
Co-authored-by: Khaleel Al-Adhami <khaleel.aladhami@gmail.com>
* allow for event handlers to ignore args
* use a constant
* dang it darglint
* forgor
* keep the tests but move them to valid place
* add metainfo to keyevent
* format code
* fix pyi files
* generate all prefixes of event types
* change format rule
* fix and test bug in config env loading
* streamline env var interpretation with @adhami3310
* improve error messages, fix invalid value for TELEMETRY_ENABLED
* just a small hint
* ruffing
* fix typo from review
* refactor - ruff broke the imports..
* cleanup imports
* more
* add internal and enum env var support
* ruff cleanup
* more global imports
* revert telemetry, it lives in rx.Config
* minor fixes/cleanup
* i missed some refs
* fix darglint
* reload config is internal
* fix EnvVar name
* add test for EnvVar + minor typing improvement
* bool tests
* was this broken?
* retain old behavior
* migrate APP_HARNESS_HEADLESS to new env var system
* migrate more APP_HARNESS env vars to new config system
* migrate SCREENSHOT_DIR to new env var system
* refactor EnvVar.get to be a method
* readd deleted functions and deprecate them
* improve EnvVar api, cleanup RELOAD_CONFIG question
* move is_prod_mode back to where it was
* improve object var symantics
* add case for serializers
* check against serializer with to = dict
* add tests
* fix typing issues
* remove default value
* older version of python doesn't have assert type
* add base to rx field cases
* get it from typing_extension
* Refactor initialize_gitignore to support list type for files_to_ignore and improve current ignore handling. Dont sort the gitignore file.
* more consistent list comprehension var
* raise error when get package manager is not found
* add escape hatch
* handle installing frontend packages more gracefully
* fix no return
* dang it darglint
* [ENG-1104] patch `json.dumps` to handle `__wrapped__` objects
Unwrap proxied objects if the default serializer doesn't work.
* pre-commit fixup
* Skip default fallback logic when `cls` is specified
`cls` will provide its own default serialization mechanism, passing a `cls`
Encoder class is now also a way to opt-out of our patching shenanigans and just
use your own code.
This will work, provided the library doing the JSON encoding isn't also using
their own custom class.
* Override JSONEncoder.default instead of json.dumps
Many libraries (like httpx, used by openai), will use `from json import dumps`,
and if they do that before `reflex.state` gets imported, then they will get the
original dumps function instead of our patched one.
To workaround this, monkeypatch the `JSONEncoder.default` function instead.
This is also nicer behavior for custom subclasses of JSONEncoder; if someone
wants to opt-out of our monkeypatching, they can simply not call
`super().default(o)` in their subclass, which by default only raises a
TypeError.
---------
Co-authored-by: Nikhil Rao <nikhil@reflex.dev>
* type check for event handler if spec arg are typed
* fix the typecheck logic
* rearrange logic pieces
* add try except
* add try except around compare
* change form and improve type checking
* print key instead
* dang it darglint
* change wording
* add basic test to cover it
* add a slightly more complicated test
* challenge it a bit by doing small capital list
* add multiple argspec
* fix slider event order
* i hate 3.9
* add note for UnionType
* move function to types
* add a test for type hint is subclass
* make on submit dict str any
* add testing for dict cases
* add check against any
* accept dict str str
* bruh i used i twice
* escape strings and print actual error message
* disable the error and print deprecation warning instead
* disable tests
* fix doc message
---------
Co-authored-by: Khaleel Al-Adhami <khaleel.aladhami@gmail.com>
* Shiki codeblock support decorations
* add decorations to useEffect
* fix pyright
* validate decorations dict
* Fix exception message plus unit tests
* possible test fix
* fix pyright
* possible tests fix
* cast decorations before creating codeblock
* `plain` is not a valid theme
* pyi fix
* address PR comment
* component as literal vars
* fix pyi
* use render
* fix pyi
* only render once
* add type ignore
* fix upload default value
* remove testcases if you don't pass them
* improve behavior
* fix render
* that's not how icon buttons work
* upgrade to next js 15 and remove babel and enable turbo
* upload is a silly guy
* woops
* how did this work before
* set env variable
* lower it even more
* lower it even more
* lower it even more
* only do literals as component vars
* add existing path subclass for env checks
* use the power of dataclasses
* use metaclass
* fake the class name
* use annotated
* use flag instead of dict
* dang it darglint
* cleanups
These props are NOT event triggers themselves, but rather they are props that
expect a list or dict of event handlers.
Additional fix for calling an `@rx.event` decorated event handler with no
arguments.
* make vardata merge not use classmethod
* add clarifying comment
* use simple cases for small values
* add possible None
* allow zero values to be given to var data
* dang it darglint
* upgrade to next 15
* relock poetry file
* test options
* skip windows on reflex-web
* bump min node version
* add turbo for dev command
* remove turbo flag
* basic functionality
* reorder page evaluation
* Fix benchmark tests (#3822)
* Upper bound for reflex-chakra dependency (#3824)
* Upper bound for reflex-chakra dependency
We have to make a breaking change in reflex-chakra, and it will happen in 0.6.0, so ensure that reflex 0.5.10 never installs the breaking version of reflex-chakra.
* Relock deps
* Add comments to DataList components (#3827)
* fix: Adding missing comments to the data list
* fix: Ran make pyi
* fully migrate vars into new system (#3743)
* fully migrate vars into new system
* i hate rufffff (no i don't)
* fix silly pright issues (except colormode and state)
* remove all instances of Var.create
* create immutable callable var and get rid of more base vars
* implement hash for all functions
* get reflex-web to compile
* get it to compile reflex-web successfully
* fix tests
* fix pyi
* use override from typing_extension
* put plotly inside of a catch
* dicts are unusable sadly
* fix silly mistake
* overload equals to special case immutable var
* improve test_cond
* solve more CI issues, down to 94 failures
* down to 20 errors
* down to 13 errors
* pass all testcases
* fix pyright issues
* reorder things
* use get origin more
* use fixed_type logic
* various optimizations
* go back to passing test cases
* use less boilerplate
* remove unnecessary print message
* remove weird comment
* add test for html issue
* add type ignore
* fix another silly issue
* override get all var data for var operations call
* make integration tests pass
* fix immutable call var
* better logic for finding parent class
* use even better logic for finding state wrt computedvar
* only choose the ones that are defined in the same module
* small dict to large dict
* [REF-3591] Remove chakra-related files from immutable vars PR (#3821)
* Add comments to html metadata component (#3731)
* fix: add verification for path /404 (#3723)
Co-authored-by: coolstorm <manas.gupta@fampay.in>
* Use the new state name when setting `is_hydrated` to false (#3738)
* Use `._is_mutable()` to account for parent state proxy (#3739)
When a parent state proxy is set, also allow child StateProxy._self_mutable to
override the parent's `_is_mutable()`.
* bump to 0.5.9 (#3746)
* add message when installing requirements.txt is needed for chosen template during init (#3750)
* #3752 bugfix add domain for XAxis (#3764)
* fix appharness app_source typing (#3777)
* fix import clash between connectionToaster and hooks.useState (#3749)
* use different registry when in china, fixes#3700 (#3702)
* do not reload compilation if using local app in AppHarness (#3790)
* do not reload if using local app
* Update reflex/testing.py
Co-authored-by: Masen Furer <m_github@0x26.net>
---------
Co-authored-by: Masen Furer <m_github@0x26.net>
* Bump memory on relevant actions (#3781)
Co-authored-by: Alek Petuskey <alekpetuskey@Aleks-MacBook-Pro.local>
* [REF-3334] Validate Toast Props (#3793)
* [REF-3536][REF-3537][REF-3541] Move chakra components into its repo(reflex-chakra) (#3798)
* fix get_uuid_string_var (#3795)
* minor State cleanup (#3768)
* Fix code wrap in markdown (#3755)
---------
Co-authored-by: Alek Petuskey <alek@pynecone.io>
Co-authored-by: Manas Gupta <53006261+Manas1820@users.noreply.github.com>
Co-authored-by: coolstorm <manas.gupta@fampay.in>
Co-authored-by: Thomas Brandého <thomas.brandeho@gmail.com>
Co-authored-by: Shubhankar Dimri <dimrishubhi@gmail.com>
Co-authored-by: benedikt-bartscher <31854409+benedikt-bartscher@users.noreply.github.com>
Co-authored-by: Khaleel Al-Adhami <khaleel.aladhami@gmail.com>
Co-authored-by: Alek Petuskey <alekpetuskey@Aleks-MacBook-Pro.local>
Co-authored-by: Elijah Ahianyo <elijahahianyo@gmail.com>
* pyproject.toml: bump to 0.6.0a1
* pyproject.toml: depend on reflex-chakra>=0.6.0a
New Var system support in reflex-chakra 0.6.0a1
* poetry.lock: relock dependencies
* integration: bump listening timeout to 1200 seconds
* integration: bump listening timeout to 1800 seconds
* Use cached_var_no_lock to avoid ImmutableVar deadlocks (#3835)
* Use cached_var_no_lock to avoid ImmutableVar deadlocks
ImmutableVar subclasses will always return the same value for a _var_name or
_get_all_var_data so there is no need to use a per-class lock to protect a
cached attribute on an instance, and doing so actually is observed to cause
deadlocks when a particular _cached_var_name creates new LiteralVar instances
and attempts to serialize them.
* remove unused module global
---------
Co-authored-by: Masen Furer <m_github@0x26.net>
Co-authored-by: Alek Petuskey <alek@pynecone.io>
Co-authored-by: Manas Gupta <53006261+Manas1820@users.noreply.github.com>
Co-authored-by: coolstorm <manas.gupta@fampay.in>
Co-authored-by: Thomas Brandého <thomas.brandeho@gmail.com>
Co-authored-by: Shubhankar Dimri <dimrishubhi@gmail.com>
Co-authored-by: benedikt-bartscher <31854409+benedikt-bartscher@users.noreply.github.com>
Co-authored-by: Alek Petuskey <alekpetuskey@Aleks-MacBook-Pro.local>
Co-authored-by: Elijah Ahianyo <elijahahianyo@gmail.com>
* guess_type: if the type is optional, treat it like it's "not None" (#3839)
* guess_type: if the type is optional, treat it like it's "not None"
When guessing the type for an Optional annotation, the Optional was already
being stripped off, but this value was being ignored, except for error
messages. So actually use the Optional-stripped value.
* Strip Optional when casting Var .to
* Fix double-quoting of defaultColorMode (#3840)
If the user provided an `appearance` or `color_mode` value to `rx.theme`, then
the resulting value ended up being double-double-quoted in the resulting JS
output.
Instead remove the quotes from the context.js.jinja2 and always pass appearance
as a Var.
* basic functionality
* run pyright
* fully migrate vars into new system (#3743)
* fully migrate vars into new system
* i hate rufffff (no i don't)
* fix silly pright issues (except colormode and state)
* remove all instances of Var.create
* create immutable callable var and get rid of more base vars
* implement hash for all functions
* get reflex-web to compile
* get it to compile reflex-web successfully
* fix tests
* fix pyi
* use override from typing_extension
* put plotly inside of a catch
* dicts are unusable sadly
* fix silly mistake
* overload equals to special case immutable var
* improve test_cond
* solve more CI issues, down to 94 failures
* down to 20 errors
* down to 13 errors
* pass all testcases
* fix pyright issues
* reorder things
* use get origin more
* use fixed_type logic
* various optimizations
* go back to passing test cases
* use less boilerplate
* remove unnecessary print message
* remove weird comment
* add test for html issue
* add type ignore
* fix another silly issue
* override get all var data for var operations call
* make integration tests pass
* fix immutable call var
* better logic for finding parent class
* use even better logic for finding state wrt computedvar
* only choose the ones that are defined in the same module
* small dict to large dict
* [REF-3591] Remove chakra-related files from immutable vars PR (#3821)
* Add comments to html metadata component (#3731)
* fix: add verification for path /404 (#3723)
Co-authored-by: coolstorm <manas.gupta@fampay.in>
* Use the new state name when setting `is_hydrated` to false (#3738)
* Use `._is_mutable()` to account for parent state proxy (#3739)
When a parent state proxy is set, also allow child StateProxy._self_mutable to
override the parent's `_is_mutable()`.
* bump to 0.5.9 (#3746)
* add message when installing requirements.txt is needed for chosen template during init (#3750)
* #3752 bugfix add domain for XAxis (#3764)
* fix appharness app_source typing (#3777)
* fix import clash between connectionToaster and hooks.useState (#3749)
* use different registry when in china, fixes#3700 (#3702)
* do not reload compilation if using local app in AppHarness (#3790)
* do not reload if using local app
* Update reflex/testing.py
Co-authored-by: Masen Furer <m_github@0x26.net>
---------
Co-authored-by: Masen Furer <m_github@0x26.net>
* Bump memory on relevant actions (#3781)
Co-authored-by: Alek Petuskey <alekpetuskey@Aleks-MacBook-Pro.local>
* [REF-3334] Validate Toast Props (#3793)
* [REF-3536][REF-3537][REF-3541] Move chakra components into its repo(reflex-chakra) (#3798)
* fix get_uuid_string_var (#3795)
* minor State cleanup (#3768)
* Fix code wrap in markdown (#3755)
---------
Co-authored-by: Alek Petuskey <alek@pynecone.io>
Co-authored-by: Manas Gupta <53006261+Manas1820@users.noreply.github.com>
Co-authored-by: coolstorm <manas.gupta@fampay.in>
Co-authored-by: Thomas Brandého <thomas.brandeho@gmail.com>
Co-authored-by: Shubhankar Dimri <dimrishubhi@gmail.com>
Co-authored-by: benedikt-bartscher <31854409+benedikt-bartscher@users.noreply.github.com>
Co-authored-by: Khaleel Al-Adhami <khaleel.aladhami@gmail.com>
Co-authored-by: Alek Petuskey <alekpetuskey@Aleks-MacBook-Pro.local>
Co-authored-by: Elijah Ahianyo <elijahahianyo@gmail.com>
* pyproject.toml: bump to 0.6.0a1
* pyproject.toml: depend on reflex-chakra>=0.6.0a
New Var system support in reflex-chakra 0.6.0a1
* poetry.lock: relock dependencies
* integration: bump listening timeout to 1200 seconds
* integration: bump listening timeout to 1800 seconds
* Use cached_var_no_lock to avoid ImmutableVar deadlocks (#3835)
* Use cached_var_no_lock to avoid ImmutableVar deadlocks
ImmutableVar subclasses will always return the same value for a _var_name or
_get_all_var_data so there is no need to use a per-class lock to protect a
cached attribute on an instance, and doing so actually is observed to cause
deadlocks when a particular _cached_var_name creates new LiteralVar instances
and attempts to serialize them.
* remove unused module global
---------
Co-authored-by: Masen Furer <m_github@0x26.net>
Co-authored-by: Alek Petuskey <alek@pynecone.io>
Co-authored-by: Manas Gupta <53006261+Manas1820@users.noreply.github.com>
Co-authored-by: coolstorm <manas.gupta@fampay.in>
Co-authored-by: Thomas Brandého <thomas.brandeho@gmail.com>
Co-authored-by: Shubhankar Dimri <dimrishubhi@gmail.com>
Co-authored-by: benedikt-bartscher <31854409+benedikt-bartscher@users.noreply.github.com>
Co-authored-by: Alek Petuskey <alekpetuskey@Aleks-MacBook-Pro.local>
Co-authored-by: Elijah Ahianyo <elijahahianyo@gmail.com>
* basic functionality
* reorder page evaluation
* fully migrate vars into new system (#3743)
* fully migrate vars into new system
* i hate rufffff (no i don't)
* fix silly pright issues (except colormode and state)
* remove all instances of Var.create
* create immutable callable var and get rid of more base vars
* implement hash for all functions
* get reflex-web to compile
* get it to compile reflex-web successfully
* fix tests
* fix pyi
* use override from typing_extension
* put plotly inside of a catch
* dicts are unusable sadly
* fix silly mistake
* overload equals to special case immutable var
* improve test_cond
* solve more CI issues, down to 94 failures
* down to 20 errors
* down to 13 errors
* pass all testcases
* fix pyright issues
* reorder things
* use get origin more
* use fixed_type logic
* various optimizations
* go back to passing test cases
* use less boilerplate
* remove unnecessary print message
* remove weird comment
* add test for html issue
* add type ignore
* fix another silly issue
* override get all var data for var operations call
* make integration tests pass
* fix immutable call var
* better logic for finding parent class
* use even better logic for finding state wrt computedvar
* only choose the ones that are defined in the same module
* small dict to large dict
* [REF-3591] Remove chakra-related files from immutable vars PR (#3821)
* Add comments to html metadata component (#3731)
* fix: add verification for path /404 (#3723)
Co-authored-by: coolstorm <manas.gupta@fampay.in>
* Use the new state name when setting `is_hydrated` to false (#3738)
* Use `._is_mutable()` to account for parent state proxy (#3739)
When a parent state proxy is set, also allow child StateProxy._self_mutable to
override the parent's `_is_mutable()`.
* bump to 0.5.9 (#3746)
* add message when installing requirements.txt is needed for chosen template during init (#3750)
* #3752 bugfix add domain for XAxis (#3764)
* fix appharness app_source typing (#3777)
* fix import clash between connectionToaster and hooks.useState (#3749)
* use different registry when in china, fixes#3700 (#3702)
* do not reload compilation if using local app in AppHarness (#3790)
* do not reload if using local app
* Update reflex/testing.py
Co-authored-by: Masen Furer <m_github@0x26.net>
---------
Co-authored-by: Masen Furer <m_github@0x26.net>
* Bump memory on relevant actions (#3781)
Co-authored-by: Alek Petuskey <alekpetuskey@Aleks-MacBook-Pro.local>
* [REF-3334] Validate Toast Props (#3793)
* [REF-3536][REF-3537][REF-3541] Move chakra components into its repo(reflex-chakra) (#3798)
* fix get_uuid_string_var (#3795)
* minor State cleanup (#3768)
* Fix code wrap in markdown (#3755)
---------
Co-authored-by: Alek Petuskey <alek@pynecone.io>
Co-authored-by: Manas Gupta <53006261+Manas1820@users.noreply.github.com>
Co-authored-by: coolstorm <manas.gupta@fampay.in>
Co-authored-by: Thomas Brandého <thomas.brandeho@gmail.com>
Co-authored-by: Shubhankar Dimri <dimrishubhi@gmail.com>
Co-authored-by: benedikt-bartscher <31854409+benedikt-bartscher@users.noreply.github.com>
Co-authored-by: Khaleel Al-Adhami <khaleel.aladhami@gmail.com>
Co-authored-by: Alek Petuskey <alekpetuskey@Aleks-MacBook-Pro.local>
Co-authored-by: Elijah Ahianyo <elijahahianyo@gmail.com>
* pyproject.toml: bump to 0.6.0a1
* pyproject.toml: depend on reflex-chakra>=0.6.0a
New Var system support in reflex-chakra 0.6.0a1
* poetry.lock: relock dependencies
* integration: bump listening timeout to 1200 seconds
* integration: bump listening timeout to 1800 seconds
* Use cached_var_no_lock to avoid ImmutableVar deadlocks (#3835)
* Use cached_var_no_lock to avoid ImmutableVar deadlocks
ImmutableVar subclasses will always return the same value for a _var_name or
_get_all_var_data so there is no need to use a per-class lock to protect a
cached attribute on an instance, and doing so actually is observed to cause
deadlocks when a particular _cached_var_name creates new LiteralVar instances
and attempts to serialize them.
* remove unused module global
---------
Co-authored-by: Masen Furer <m_github@0x26.net>
Co-authored-by: Alek Petuskey <alek@pynecone.io>
Co-authored-by: Manas Gupta <53006261+Manas1820@users.noreply.github.com>
Co-authored-by: coolstorm <manas.gupta@fampay.in>
Co-authored-by: Thomas Brandého <thomas.brandeho@gmail.com>
Co-authored-by: Shubhankar Dimri <dimrishubhi@gmail.com>
Co-authored-by: benedikt-bartscher <31854409+benedikt-bartscher@users.noreply.github.com>
Co-authored-by: Alek Petuskey <alekpetuskey@Aleks-MacBook-Pro.local>
Co-authored-by: Elijah Ahianyo <elijahahianyo@gmail.com>
* guess_type: if the type is optional, treat it like it's "not None" (#3839)
* guess_type: if the type is optional, treat it like it's "not None"
When guessing the type for an Optional annotation, the Optional was already
being stripped off, but this value was being ignored, except for error
messages. So actually use the Optional-stripped value.
* Strip Optional when casting Var .to
* run format
* use original mp
* evaluate page regardless
* use old typing
* dangit pydantic
* i have two braincells and they are NOT collaborating
* adjust testcases
* always add the upload endpoint
* retrieve upload but after evaluate component
* check against none
Co-authored-by: Masen Furer <m_github@0x26.net>
* make it var
* fix page title
* don't change style.py
* fix counter
* remove duplicated logic
---------
Co-authored-by: Elijah Ahianyo <elijahahianyo@gmail.com>
Co-authored-by: Masen Furer <m_github@0x26.net>
Co-authored-by: elvis kahoro <elvis@reflex.dev>
Co-authored-by: Alek Petuskey <alek@pynecone.io>
Co-authored-by: Manas Gupta <53006261+Manas1820@users.noreply.github.com>
Co-authored-by: coolstorm <manas.gupta@fampay.in>
Co-authored-by: Thomas Brandého <thomas.brandeho@gmail.com>
Co-authored-by: Shubhankar Dimri <dimrishubhi@gmail.com>
Co-authored-by: benedikt-bartscher <31854409+benedikt-bartscher@users.noreply.github.com>
Co-authored-by: Alek Petuskey <alekpetuskey@Aleks-MacBook-Pro.local>
* [ENG-3970] When normal pickle fails, try dill
If dill is not installed, suggest that the user `pip install` it.
Fix#4147
* re-lock depenedencies
* Include original pickle error message for better debugging
When the pickling throws a warning and dill is not installed, include the
original pickle error.
Add a test case for an object that even dill cannot pickle to ensure error path
is hit as expected.
* py3.9 compatibility
* test for stateless apps
* add playwright to dev dependencies
* fix docstring
* fix install of playwright in CI
* fix install again
* add allowed license
* add retry on running integrations step
* another attempt to fix licensing issue
* update timeout duration for retry
* fix timeout workflows
* remove dep changes
* remove outdated diff
* fix scope in new test and workflow for appharness
* run playwright tests last
* use $ syntax
* missing test case change
* try being a little smart
* improve merge imports logic
* add public as well
* oops missed that one
* last one there
* debounce: handle custom code from child component
Include _get_all_hooks when rendering the child element, instead of just
internal hooks.
* textarea: handle special behaviors during `create`
Move special behavior handling to `create` classmethod to allow carrying of
added props when wrapped in debounce, which does not call `_render` on the
child component.
* fix and test bug in config env loading
* streamline env var interpretation with @adhami3310
* improve error messages, fix invalid value for TELEMETRY_ENABLED
* just a small hint
* ruffing
* fix typo from review
If a non-root state was serialized, but its substates were not, then these
would not be populated when reloading the pickled state, because only substates
from the root were being populated with fresh versions.
Now, capture the substates from all fresh states and apply them to the
deserialized state for each substate to ensure that the entire state tree has
all substates instantiated after deserializing, even substates that were never
serialized originally.
* add on progress typing to react player
* fix pyi file
* have the pyi here as well
* more pyi changes
* fix imports
* run pyi
* for some reason it want event on three lines no clue why
* simplify case for when type is in the same module
* run pyi
* remove last missing type for datadisplay
* Shiki Code block Experimental
* refactor
* update code
* remove console.log
* add transformers to namespace
* some validations
* fix components paths
* fix ruff
* add a high-level component
* fix mapping
* fix mapping
* python 3.9+
* see if this fixes the tests
* fix pyi and annotations
* minimal update of theme and language map
* add hack for reflex-web/flexdown
* unit test file commit
* [ENG-3895] [ENG-3896] Update styling for shiki code block
* strip transformer triggers
* minor refactor
* linter
* fix pyright
* pyi fix
* add unit tests
* sneaky pyright ignore
* the transformer trigger regex should remove the language comment character
* minor refactor
* fix silly mistake
* component mapping in markdown should use the first child for codeblock
* use ternary operator in numbers.py, move code block args to class for docs discoverability
* precommit
* pyright fix
* remove id on copy button animation
* pyright fix for real
* pyi fix
* pyi fix fr
* check if svg exists
* copy event chain
* do a concatenation instead of first child
* added comment
---------
Co-authored-by: Carlos <cutillascarlos@gmail.com>
* make var system expandable
* use old syntax
* remove newer features
* that's a weird error
* remove unnecessary error message
* remove hacky getattr as it's no longer necessary
* improve color handling
* get it right pyright
* dang it darglint
* fix prototype to string
* don't try twice
* adjust test case
* add test for var alpha
* change place of type ignore
* fix json
* add name to custom var operation
* don't delete that you silly
* change logic
* remove extra word
* move all environment variables to the same place
* reorder things around
* move more variables to environment
* remove cyclical imports
* forgot default value for field
* for some reason type hints aren't being interpreted
* put the field type *before* not after
* make it get
* move a bit more
* add more fields
* move reflex dir
* add return
* put things somewhere else
* add custom error
It's easy to mis-spell `rx.var(cached=True)` instead of `rx.var(cache=True)`,
and in 0.6.3, this doesn't actual raise an error... the bad value is silently
discarded and the var is NOT marked as being cached.
All generic types present in a Union must be parametrized on 3.11.0 if any
other generic types in the union are parametrized.
This appears to be a bug in 3.11.0, as the behavior is not observed in 3.11.1
or 3.10; fixing here as this is technically more correct anyway and avoids a
crash.
* [ENG-3954] Treat ArrayVar.foreach index as int
* foreach: convert return value to a Var
When the value returned from the foreach is not hashable (mutable type), then
it will raise an exception if it is not first converted to a LiteralVar.
* Arbitrary arg access two levels deep for untyped handler
Provide drop-in compatibility with existing component wrapping code
that was accessing attributes on the default handler arg type.
* py3.9 compat
* LiteralEventChainVar becomes an ArgsFunctionOperation
Instead of using the ArgsFunctionOperation to create the string representation
of the _js_expr, make the identity of the var an ArgsFunctionOperation so the
_args_names and _return_expr remain accessible.
Rely on the default behavior of ArgsFunctionOperation to create the
_cached_var_name / _js_expr value.
This allows the compat shim in `format_event_chain` to remain functional, as it
does special handling for ArgsFunctionOperation to retain the previous behavior
of that function (this was a regression introduced in 0.6.2).
* _var_type is EventChain; fix parent class order
* Re-fix LiteralEventChainVar inheritence list w/ comment
* [ENG-3942] LiteralEventVar becomes VarCallOperation
instead of using `.call` when constructing the `_js_expr`, have the identity of
a LiteralEventVar as a VarCallOperation to take advantage of the _var_data
carrying.
* add event overlords
* EventCallback descriptor always returns EventSpec from class
Relax actual `__get__` definition to support the multitude of overloads
* test case for event related vars carrying _var_data
---------
Co-authored-by: Khaleel Al-Adhami <khaleel.aladhami@gmail.com>
* Support aria and data props
* Fix busted docstring
* Ignore special_attributes logic for defined props
* simplify special attribute checking logic
avoid special cases in the special case handling code 🙄
* add type hinting to events
* fix pyi
* make it a list
* add on change
* dang it darglintz
* add future annotations
* add try except becuse i hate this
* add check for class
* aaaa
* sometimes you need to make hard decisions
* ono
* i hate unions
* add rx event
* move stuff around
* maybe
* special case osmething
* i don't need no test
* remove stray print
Co-authored-by: Masen Furer <m_github@0x26.net>
* remove another stray print
Co-authored-by: Masen Furer <m_github@0x26.net>
* add rx event
---------
Co-authored-by: Masen Furer <m_github@0x26.net>
* unionize base var fields types
* add tests
* fix union types for vars (#4152)
* remove 3.11 special casing
* special case on version
* fix old versions of python
---------
Co-authored-by: Masen Furer <m_github@0x26.net>
* Handle rx.State subclasses defined in function
* create a new container module: `reflex.istate.dynamic` to save references to
dynamically generated substates.
* for substates with `<locals>` in the name, copy these to the container module
and update the name to avoid duplication.
* add test for "poor man" ComponentState
Fix#4128
* test_state: disable local def handling for dupe-detection test
* Track the original module and name for type hint evaluation
Also use the original name when checking for the "mangled name" pattern when
doing undeclared Var assignment checking.
In rx.call_script scenario, the EventChain must call `queueEvents` and
`processEvent` instead of `addEvents`, because the former are in scope in the
call_script eval environment where `addEvents` is not.
This is an escape hatch for certain wrapping scenarios.
* update workflow
* skip more in unit tests
* try something else to prevent adding macos job to pool
* exclude too much
* fix units-text with macOS excluded
* also drop macOS job in integration tests
* readd macos job separately to only run on merge
* First use environment variable as npm registry
* use NPM_CONFIG_REGISTRY as env variable
---------
Co-authored-by: 류형주/인공지능팀 <hyungju.ryu@ahnlab.com>
* Avoid fetching substates multiple times
In the presence of computed vars, substates may be cached more than once.
* Consolidate logic in StateManagerRedis.get_state
* Suppress StateSchemaMismatchError and create a new state instance.
If the serialized state's schema does not match the current corresponding state
schema, then we have to create a new instance.
* add workflow to check dependencies on release branch
* rename action to follow convention of other actions
* update workflow
* bump poetry version
* relock deps
* update check to ignore pyright and ruff
* oops, you saw nothing
* split dep check in two job
* fix frontend dep check
* fix stuff
* hmm yeah
* nope nope nope
* sigh
* bump js versions for some packages
* fix some warnings in tests
* fix tests
* try some options
* try to set asyncio policy
* debug dep check
* fix attempt for backend dep
* clean up output for backend check
* run bun outdated on reflex-web to catch most of the packages
* fix python version
* fix python version
* add missing env
* fix bun command
* fix workdir of frontend check
* update packages version
* up-pin plotly.js version
* add debug ouput
* clean frontend dep check output
* fix output
* fix async tests for redis
* relock poetry.lock
* Non-async functions do not need pytest_asyncio.fixture
* test_state: close StateManagerRedis connection in test to avoid warning
---------
Co-authored-by: Masen Furer <m_github@0x26.net>
* Only serialize base vars
* Never serialize router/router_data in substates
* Hash the schema to reduce serialized size
* lru_cache the schema to avoid recomputing it
* Get default for backend var defined in mixin
If the backend var is defined in a mixin class, it won't appear in
`cls.__dict__`, but the value is still retrievable via `getattr` on `cls`.
Prefer to use the actual defined default before using
`Var.get_default_value()`.
If `Var.get_default_value()` fails, set the default to `None` such that the
backend var still gets recognized as a backend var when it is used on `self`.
----
Update test_component_state to include backend vars
Extra coverage for backend vars with and without defaults, defined in a
ComponentState/mixin class.
* fix integration test
* Simplify StateManagerDisk implementation
* Act more like the memory state manager and only track the root state in self.states
* .load_state always loads a single state or returns None
* .populate_states is the new entry point in loading from disk and it only occurs
when the root state is not known
* much fast
* StateManagerDisk now acts much more like StateManagerMemory
Treat StateManagerDisk like StateManagerMemory for AppHarness
* Handle root_state deserialized from disk
In this case, we need to initialize the whole state tree, so any non-persistent
states will still get default values, whereas on-disk states will overwrite the
defaults.
* Cache root_state under client_token for StateManagerMemory compatibility
Mainly this just makes it easier for us to write tests that work against either
Disk or Memory state managers.
* bundle chakra in window for CSR
* remove repeated chakra ui reference
* use dynamically generated libraries
* remove js from it
* include emotion react for dynamic components
* make code more readable
Co-authored-by: Thomas Brandého <thomas.brandeho@gmail.com>
* jsx yea
* what
---------
Co-authored-by: Thomas Brandého <thomas.brandeho@gmail.com>
* Add additional test cases for rx.call_script
Include internal vars inside an f-string to be properly rendered on the backend
and frontend.
* [ENG-3870] rx.call_script with f-string var produces incorrect code
Avoid casting javascript code with embedded Var as LiteralStringVar
There are two cases that need to be handled:
1. The javascript code contains Vars with VarData, these can only be evaluated
in the component context, since they may use hooks. Vars with VarData cannot be
used from the backend. In this case, we cast the given code as a raw js
expression and include the extracted VarData.
2. The javascript code has no VarData. In this case, we pass the code as the
raw js expression and cast to a python str to get a js literal string to eval.
* use VarData.__bool__ instead of `is None`
* use pathlib as much as possible
* fixstuff
* break locally to unbreak in CI 🤷
* add type on env
* debug attempt 1
* debugged
* oops, there is the actual fix
* fix 3.9 compat
* Track backend-only vars that are declared without a default value
Without this provision, declared backend vars can be accidentally shared among
all states if a mutable value is assigned to the class attribute.
* add test case for no default backend var
* Handle bool cast for optional NumberVar
If the _var_type is optional, then also check that the value is not None
* boolify the result of `and_operation`
* flip order to be more semantically pure
---------
Co-authored-by: Khaleel Al-Adhami <khaleel.aladhami@gmail.com>
* remove format_state and override behavior for bare
* pass the test cases
* only do one level of dicting dataclasses
* remove dict and replace list with set
* delete unnecessary serialize calls
* remove serialize for mutable proxy
* dang it darglint
* EventFnArgMismatch fix to support defaults args
* fixing type hint and docstring raises
* enforce stronger type checking
* unwrap var annotations :(
---------
Co-authored-by: Khaleel Al-Adhami <khaleel.aladhami@gmail.com>
* Update markdown component map to use new rx.code_block.theme enum
* change var to theme
* give the types some attention instead of ignoring them
---------
Co-authored-by: Khaleel Al-Adhami <khaleel.aladhami@gmail.com>
* lift node version restraint to allow more recent version if already installed
* add node test for latest version
* change python version
* use purple for debug logs
* update workflow
* add playwright dev dependency
* update workflow
* change test
* oops
* improve test
* update test
* fix tests
* mv units tests to a subfolder
* reorganize tests
* fix install
* update test_state
* revert node changes and only keep new tests organization
* move integration tests in tests/integration
* fix integration workflow
* fix dockerfile workflow
* fix dockerfile workflow 2
* fix shared_state
* allow classname to be state vars
* simplify join with all literal string vars
* add test case and avoid concat var operation if it's not necessary
* remove silly print statement
* simplify case where there's no var
* don't automatically do class name str to literal var
* can run with granian by setting REFLEX_USE_GRANIAN var
* granian also useable for prod mode
* adjust reload paths for granian
* move uvicorn / granian logic to their own function
* fix prod mode
* Revert "ruff formatting to unbreak `main` CI (#3964)"
This reverts commit f9be184b86.
* Revert "bump python>=3.10 for 0.6.0 (#3956)"
This reverts commit fe1833c5e1.
* drop python3.8 support
* relock dependencies
* Raise warning when < py310 is used
* Move python version check to reflex version check function
Avoid spammy deprecation warnings by only emitting warning once per project,
per reflex version, per reinit.
* Remove other references to python3.8
* [WiP] Support UI components returned from a computed var
* Get rid of nasty react hooks warning
* include @babel/standalone in the base to avoid CDN
* put window variables behind an object
* use jsx
* implement the thing
* cleanup dead test code (#3909)
* override dict in propsbase to use camelCase (#3910)
* override dict in propsbase to use camelCase
* fix underscore in dict
* dang it darglint
* [REF-3562][REF-3563] Replace chakra usage (#3872)
* [ENG-3717] [flexgen] Initialize app from refactored code (#3918)
* Remove Pydantic from some classes (#3907)
* half of the way there
* add dataclass support
* Forbid Computed var shadowing (#3843)
* get it right pyright
* fix unit tests
* rip out more pydantic
* fix weird issues with merge_imports
* add missing docstring
* make special props a list instead of a set
* fix moment pyi
* actually ignore the runtime error
* it's ruff out there
---------
Co-authored-by: benedikt-bartscher <31854409+benedikt-bartscher@users.noreply.github.com>
* Merging
* fixss
* fix field_name
* always import react
* move func to file
* do some weird things
* it's really ruff out there
* add docs
* how does this work
* dang it darglint
* fix the silly
* don't remove computed guy
* silly goose, don't ignore var types :D
* update code
* put f string on one line
* make it deprecated instead of outright killing it
* i hate it
* add imports from react
* assert it has evalReactComponent
* do things ig
* move get field to global context
* ooops
---------
Co-authored-by: Khaleel Al-Adhami <khaleel.aladhami@gmail.com>
Co-authored-by: benedikt-bartscher <31854409+benedikt-bartscher@users.noreply.github.com>
Co-authored-by: Elijah Ahianyo <elijahahianyo@gmail.com>
* add few test cases for bool
* use parametrize
* use a tuple of strings
Co-authored-by: Masen Furer <m_github@0x26.net>
---------
Co-authored-by: Masen Furer <m_github@0x26.net>
* state: update inherited_vars and tracking dicts when adding vars
Ensure that dynamically added vars are accounted for in dependency and
inheritence tree to avoid unrenderable or stale data.
* Regression test for dynamic route args and inherited_vars
* [flexgen] Initialize app from refactored code
Use the new /api/gen/{hash}/refactored endpoint to get refactored reflex code.
* Use _js_expr instead of _var_name
* delete most references to varr
* [REF-3562][REF-3563] Replace chakra usage (#3872)
* only one mention of var
* delete vars.py why not
* remove reflex.vars
* rename immutable var to var
* rename ivars to vars
* add vars back smh
* ruff
* no more create_safe
* reorder deprecated
* remove raises
* remove all Var.create
* move to new api
* fix unit tests
* fix pyi hopefully
* sort literals
* fix event handler issues
* update poetry
* fix silly issues i'm very silly
* add var_operation_return
* rename immutable to not immutable
* add str type
* it's ruff out there
---------
Co-authored-by: Elijah Ahianyo <elijahahianyo@gmail.com>
* half of the way there
* add dataclass support
* Forbid Computed var shadowing (#3843)
* get it right pyright
* fix unit tests
* rip out more pydantic
* fix weird issues with merge_imports
* add missing docstring
* make special props a list instead of a set
* fix moment pyi
* actually ignore the runtime error
* it's ruff out there
---------
Co-authored-by: benedikt-bartscher <31854409+benedikt-bartscher@users.noreply.github.com>
* fix dynamic route vars silently shadow all other vars
* add test
* fix: allow multiple dynamic routes with the same arg
* add test for multiple dynamic args with the same name
* avoid side-effects with DynamicState tests
* fix dynamic route integration test which shadowed a var
* fix darglint
* refactor to DynamicRouteVar
* old typing stuff again
* from typing_extensions import Self
try to keep typing backward compatible with older releases we support
* Raise a specific exception when encountering dynamic route arg shadowing
---------
Co-authored-by: Masen Furer <m_github@0x26.net>
* fix: Adding type propagation to ToStringOperation.
* fix: Better naming.
* fix: Added test that fails without the fix.
* Update reflex/ivars/base.py
Co-authored-by: Masen Furer <m_github@0x26.net>
* Retain mutability inside `async with self` block (#3884)
When emitting a state update, restore `_self_mutable` to the value it had
previously so that `yield` in the middle of `async with self` does not result
in an immutable StateProxy.
Fix#3869
* Include child imports in markdown component_map (#3883)
If a component in the markdown component_map contains children components, use
`_get_all_imports` to recursively enumerate them.
Fix#3880
* [REF-3570] Remove deprecated REDIS_URL syntax (#3892)
* fix: Instead of researching the type after dropping it, preserve it.
* Apply suggestions from code review
Co-authored-by: Masen Furer <m_github@0x26.net>
---------
Co-authored-by: Masen Furer <m_github@0x26.net>
* use serializer system
* add checks for unsupported operands
* and and or are now supported
* format
* remove unnecessary call to JSON
* put base before rest
* fix failing testcase
* add hinting to get static analysis to complain
* damn
* big changes
* get typeguard from extensions
* please darglint
* dangit darglint
* remove one from vars
* add without data and use it in plotly
* DARGLINT
* change format for special props
* add pyi
* delete instances of Var.create
* modify client state to work
* fixed so much
* remove every Var.create
* delete all basevar stuff
* checkpoint
* fix pyi
* get older python to work
* dangit darglint
* add simple fix to last failing testcase
* remove var name unwrapped and put client state on immutable var
* fix older python
* fox event issues
* change forms pyi
* make test less strict
* use rx state directly
* add typeignore to page_id
* implement foreach
* delete .web states folder silly
* update reflex chakra
* fix issue when on mount or on unmount is not set
* nuke Var
* run pyi
* import immutablevar in critical location
* delete unwrap vars
* bring back array ref
* fix style props in app
* /health endpoint for K8 Liveness and Readiness probes (#3855)
* Added API Endpoint
* Added API Endpoint
* Added Unit Tests
* Added Unit Tests
* main
* Apply suggestions from Code Review
* Fix Ruff Formatting
* Update Socket Events
* Async Functions
* Update find_replace (#3886)
* [REF-3592]Promote `rx.progress` from radix themes (#3878)
* Promote `rx.progress` from radix themes
* fix pyi
* add warning when accessing `rx._x.progress`
* Use correct flexgen backend URL (#3891)
* Remove demo template (#3888)
* gitignore .web (#3885)
* update overflowY in AUTO_HEIGHT_JS from hidden to scroll (#3882)
* Retain mutability inside `async with self` block (#3884)
When emitting a state update, restore `_self_mutable` to the value it had
previously so that `yield` in the middle of `async with self` does not result
in an immutable StateProxy.
Fix#3869
* Include child imports in markdown component_map (#3883)
If a component in the markdown component_map contains children components, use
`_get_all_imports` to recursively enumerate them.
Fix#3880
* [REF-3570] Remove deprecated REDIS_URL syntax (#3892)
* mixin computed vars should only be applied to highest level state (#3833)
* improve state hierarchy validation, drop old testing special case (#3894)
* fix var dependency dicts (#3842)
* Adding array to array pluck operation. (#3868)
* fix initial state without cv fallback (#3670)
* add fragment to foreach (#3877)
* Update docker-example (#3324)
* /health endpoint for K8 Liveness and Readiness probes (#3855)
* Added API Endpoint
* Added API Endpoint
* Added Unit Tests
* Added Unit Tests
* main
* Apply suggestions from Code Review
* Fix Ruff Formatting
* Update Socket Events
* Async Functions
* /health endpoint for K8 Liveness and Readiness probes (#3855)
* Added API Endpoint
* Added API Endpoint
* Added Unit Tests
* Added Unit Tests
* main
* Apply suggestions from Code Review
* Fix Ruff Formatting
* Update Socket Events
* Async Functions
* Merge branch 'main' into use-old-serializer-in-literalvar
* [REF-3570] Remove deprecated REDIS_URL syntax (#3892)
* /health endpoint for K8 Liveness and Readiness probes (#3855)
* Added API Endpoint
* Added API Endpoint
* Added Unit Tests
* Added Unit Tests
* main
* Apply suggestions from Code Review
* Fix Ruff Formatting
* Update Socket Events
* Async Functions
* [REF-3570] Remove deprecated REDIS_URL syntax (#3892)
* remove extra var
Co-authored-by: Masen Furer <m_github@0x26.net>
* resolve typo
* write better doc for var.create
* return var value when we know it's literal var
* fix unit test
* less bloat for ToOperations
* simplify ImmutableComputedVar.__get__ (#3902)
* simplify ImmutableComputedVar.__get__
* ruff it
---------
Co-authored-by: Samarth Bhadane <samarthbhadane119@gmail.com>
Co-authored-by: Elijah Ahianyo <elijahahianyo@gmail.com>
Co-authored-by: Masen Furer <m_github@0x26.net>
Co-authored-by: benedikt-bartscher <31854409+benedikt-bartscher@users.noreply.github.com>
Co-authored-by: Vishnu Deva <vishnu.deva12@gmail.com>
Co-authored-by: abulvenz <a.eismann@senbax.de>
* delete states if it exists
* simplify ImmutableComputedVar.__get__ (#3902)
* simplify ImmutableComputedVar.__get__
* ruff it
---------
Co-authored-by: benedikt-bartscher <31854409+benedikt-bartscher@users.noreply.github.com>
When emitting a state update, restore `_self_mutable` to the value it had
previously so that `yield` in the middle of `async with self` does not result
in an immutable StateProxy.
Fix#3869
* add var_operations and move some operations to the new style
* change bound style
* can't assume int anymore
* slice is not hashable (how did this work bef)
* convert to int explicitly
* move the rest of the operations to new style
* fix bool guess type
* forgot to precommit dangit
* add type ignore to bool for now
* implement disk state manager
* put states inside of a folder
* return root state all the time
* factor out code
* add docs for token expiration
* cache states directory
* call absolute on web directory
* change dir to app path when testing the backend
* remove accidental 🥒
* test disk for now
* modify schema
* only serialize specific stuff
* fix issue in types
* what is a kilometer
* create folder if it doesn't exist in write
* this code hates me
* check if the file isn't empty
* add try except clause
* add check for directory again
* test_component: improve valid/invalid event trigger tests
Add test cases for event triggers defined as annotations.
Add additional cases around lambda returning different values.
Improve assertions for invalid tests (each line needs its own `pytest.raises`).
More invalid test cases.
* [REF-3589] raise EventHandlerArgMismatch when event handler args don't match spec
Improve error message for common issue.
Previously when the event handler arguments didn't match the spec, the
traceback resulted in:
```
OSError: could not get source code
```
Now this problem is traceable as a distinct error condition and users are
empowered to debug their code and reference the documentation (to be updated)
for further information.
* raise EventFnArgMismatch when lambda args don't match event trigger spec
Improve error message for another common issue encountered in the reflex framework.
Previous error message was
```
TypeError: index.<locals>.<lambda>() takes 0 positional arguments but 1 was given
```
* Fix up lambda test cases
* call_event_fn: adjust number of args for bound methods
* Use lru_cache on expensive typing-related functions
* Skip instantiation of VarData unless data was actually merged
* Revert "integration: bump listening timeout to 1800 seconds"
This reverts commit a94eedff6d.
* Revert "integration: bump listening timeout to 1200 seconds"
This reverts commit 86563b66a4.
* [REF-3633] Introduce a workaround for enterprise users who get stuck with httpx.get SSL
Setting SSL_NO_VERIFY=1 will disable SSL verification during `reflex init`
* Also install fnm using `reflex.utils.net.get`
If the user provided an `appearance` or `color_mode` value to `rx.theme`, then
the resulting value ended up being double-double-quoted in the resulting JS
output.
Instead remove the quotes from the context.js.jinja2 and always pass appearance
as a Var.
* guess_type: if the type is optional, treat it like it's "not None"
When guessing the type for an Optional annotation, the Optional was already
being stripped off, but this value was being ignored, except for error
messages. So actually use the Optional-stripped value.
* Strip Optional when casting Var .to
* fully migrate vars into new system
* i hate rufffff (no i don't)
* fix silly pright issues (except colormode and state)
* remove all instances of Var.create
* create immutable callable var and get rid of more base vars
* implement hash for all functions
* get reflex-web to compile
* get it to compile reflex-web successfully
* fix tests
* fix pyi
* use override from typing_extension
* put plotly inside of a catch
* dicts are unusable sadly
* fix silly mistake
* overload equals to special case immutable var
* improve test_cond
* solve more CI issues, down to 94 failures
* down to 20 errors
* down to 13 errors
* pass all testcases
* fix pyright issues
* reorder things
* use get origin more
* use fixed_type logic
* various optimizations
* go back to passing test cases
* use less boilerplate
* remove unnecessary print message
* remove weird comment
* add test for html issue
* add type ignore
* fix another silly issue
* override get all var data for var operations call
* make integration tests pass
* fix immutable call var
* better logic for finding parent class
* use even better logic for finding state wrt computedvar
* only choose the ones that are defined in the same module
* small dict to large dict
* [REF-3591] Remove chakra-related files from immutable vars PR (#3821)
* Add comments to html metadata component (#3731)
* fix: add verification for path /404 (#3723)
Co-authored-by: coolstorm <manas.gupta@fampay.in>
* Use the new state name when setting `is_hydrated` to false (#3738)
* Use `._is_mutable()` to account for parent state proxy (#3739)
When a parent state proxy is set, also allow child StateProxy._self_mutable to
override the parent's `_is_mutable()`.
* bump to 0.5.9 (#3746)
* add message when installing requirements.txt is needed for chosen template during init (#3750)
* #3752 bugfix add domain for XAxis (#3764)
* fix appharness app_source typing (#3777)
* fix import clash between connectionToaster and hooks.useState (#3749)
* use different registry when in china, fixes#3700 (#3702)
* do not reload compilation if using local app in AppHarness (#3790)
* do not reload if using local app
* Update reflex/testing.py
Co-authored-by: Masen Furer <m_github@0x26.net>
---------
Co-authored-by: Masen Furer <m_github@0x26.net>
* Bump memory on relevant actions (#3781)
Co-authored-by: Alek Petuskey <alekpetuskey@Aleks-MacBook-Pro.local>
* [REF-3334] Validate Toast Props (#3793)
* [REF-3536][REF-3537][REF-3541] Move chakra components into its repo(reflex-chakra) (#3798)
* fix get_uuid_string_var (#3795)
* minor State cleanup (#3768)
* Fix code wrap in markdown (#3755)
---------
Co-authored-by: Alek Petuskey <alek@pynecone.io>
Co-authored-by: Manas Gupta <53006261+Manas1820@users.noreply.github.com>
Co-authored-by: coolstorm <manas.gupta@fampay.in>
Co-authored-by: Thomas Brandého <thomas.brandeho@gmail.com>
Co-authored-by: Shubhankar Dimri <dimrishubhi@gmail.com>
Co-authored-by: benedikt-bartscher <31854409+benedikt-bartscher@users.noreply.github.com>
Co-authored-by: Khaleel Al-Adhami <khaleel.aladhami@gmail.com>
Co-authored-by: Alek Petuskey <alekpetuskey@Aleks-MacBook-Pro.local>
Co-authored-by: Elijah Ahianyo <elijahahianyo@gmail.com>
* pyproject.toml: bump to 0.6.0a1
* pyproject.toml: depend on reflex-chakra>=0.6.0a
New Var system support in reflex-chakra 0.6.0a1
* poetry.lock: relock dependencies
* integration: bump listening timeout to 1200 seconds
* integration: bump listening timeout to 1800 seconds
* Use cached_var_no_lock to avoid ImmutableVar deadlocks (#3835)
* Use cached_var_no_lock to avoid ImmutableVar deadlocks
ImmutableVar subclasses will always return the same value for a _var_name or
_get_all_var_data so there is no need to use a per-class lock to protect a
cached attribute on an instance, and doing so actually is observed to cause
deadlocks when a particular _cached_var_name creates new LiteralVar instances
and attempts to serialize them.
* remove unused module global
---------
Co-authored-by: Masen Furer <m_github@0x26.net>
Co-authored-by: Alek Petuskey <alek@pynecone.io>
Co-authored-by: Manas Gupta <53006261+Manas1820@users.noreply.github.com>
Co-authored-by: coolstorm <manas.gupta@fampay.in>
Co-authored-by: Thomas Brandého <thomas.brandeho@gmail.com>
Co-authored-by: Shubhankar Dimri <dimrishubhi@gmail.com>
Co-authored-by: benedikt-bartscher <31854409+benedikt-bartscher@users.noreply.github.com>
Co-authored-by: Alek Petuskey <alekpetuskey@Aleks-MacBook-Pro.local>
Co-authored-by: Elijah Ahianyo <elijahahianyo@gmail.com>
* Upper bound for reflex-chakra dependency
We have to make a breaking change in reflex-chakra, and it will happen in 0.6.0, so ensure that reflex 0.5.10 never installs the breaking version of reflex-chakra.
* Relock deps
* do not reload if using local app
* Update reflex/testing.py
Co-authored-by: Masen Furer <m_github@0x26.net>
---------
Co-authored-by: Masen Furer <m_github@0x26.net>
* half of the way there
* implement __getitem__ for array
* add some tests
* add fixes to pyright
* fix default factory
* implement array operations
* format code
* fix pyright issue
* give up
* add object operations
* add test for merge
* pyright 🥺
* use str isntead of _var_name
Co-authored-by: Masen Furer <m_github@0x26.net>
* wrong var_type
* make to much nicer
* add subclass checking
* enhance types
* use builtin list type
* improve typing even more
* i'm awaiting october
* use even better typing
* add hash, json, and guess type method
* fix pyright issues
* add a test and fix lots of errors
* fix pyright once again
* add type inference to list
---------
Co-authored-by: Masen Furer <m_github@0x26.net>
When using rx.vars.get_uuid_string_var, wrap the prop Var in `useMemo` so that
the value remains consistent across re-renders of the component.
Fix#3707
* implement var operation decorator
* use older syntax
* use cast and older syntax
* use something even simpler
* add some tests
* use old union tactics
* that's not how you do things
* implement arithmetic operations while we're at it
* add test
* even more operations
* can't use __bool__
* thanos snap
* forgot ruff
* use default factory
* dang it darglint
* i know i should have done that but
* convert values into literalvars
* make test pass
* use older union tactics
* add test to string var
* pright why do you hate me 🥺
* [REF-3184] Raise exception when encountering nested `async with self` blocks
Avoid deadlock when the background task already holds the mutation lock for a
given state.
* [REF-3339] get_state from background task links to StateProxy
When calling `get_state` from a background task, the resulting state instance
is wrapped in a StateProxy that is bound to the original StateProxy and shares
the same async context, lock, and mutability flag.
* If StateProxy has a _self_parent_state_proxy, retrieve the correct substate
* test_state fixup
* implement more literal vars
* fix super issue
* pyright has a bug i think
* oh we changed that
* fix docs
* literalize vars recursively
* do what masen told me :D
* use dynamic keys
* forgot .create
* adjust _var_value
* dang it darglint
* add test for serializing literal vars into js exprs
* fix silly mistake
* add handling for var and none
* use create safe
* is none bruh
* implement function vars and do various modification
* fix None issue
* clear a lot of creates that did nothing
* add tests to function vars
* added simple fix smh
* use fconcat to make an even more complicated test
* reflex.build polling: catch exceptions and retry
Extend interval to 2 seconds to reduce server load.
* Add function to check if a string looks like a generation hash
* reflex init: allow --template to be a generation hash if --ai is specified
* implement LiteralStringVar and format/retrieval mechanism
* use create safe
* add cached properties to ConcatVarOperation
* fix caches
* also include self
* fix inconsistencies in typings
* use default factory not default
* add missing docstring
* experiment with immutable var data
* solve pydantic issues
* add sorted function
* missing docs
* forgot ellipses
* give up on frozen
* dang it darglint
* fix string serialization bugs and remove unused code
* add returns statement
* whitespace moment
* add simple test for string concat
* export ConcatVarOperation
* define new JS-type var classes
* add docstring
* get rid of dataclass definitions and export all new vars
* order imports in the correct way
* only hash once
* implement format for immutable vars
* add some basic test
* make reference only after formatting
* win over pyright
* hopefully now pyright doesn't hate me
* forgot some _var_data
* i don't know how imports work
* use f_string var and remove assignments from pyi file
* override post_init to not break immutability
* add create_safe and test for it
* add module prefix to state names
* fix state names in test_app
* update state names in test_state
* fix state names in test_var
* fix state name in test_component
* fix state names in test_format
* fix state names in test_foreach
* fix state names in test_cond
* fix state names in test_datatable
* fix state names in test_colors
* fix state names in test_script
* fix state names in test_match
* fix state name in event1 fixture
* fix pyright and darglint
* fix state names in state_tree
* fix state names in redis only test
* fix state names in test_client_storage
* fix state name in js template
* add `get_state_name` and `get_full_state_name` helpers for `AppHarness`
* fix state names in test_dynamic_routes
* use new state name helpers in test_client_storage
* fix state names in test_event_actions
* fix state names in test_event_chain
* fix state names in test_upload
* fix state name in test_login_flow
* fix state names in test_input
* fix state names in test_form_submit
* ruff
* validate state module names
* wtf is going on here?
* remove comments leftover from refactoring
* adjust new test_add_style_embedded_vars
* fix state name in state.js
* fix integration/test_client_state.py
new SessionStorage feature was added with more full state names that need to be formatted in
* fix pre-commit issues in test_client_storage.py
* adjust test_computed_vars
* adjust safe-guards
* fix redis tests with new exception state
---------
Co-authored-by: Masen Furer <m_github@0x26.net>
If pydantic v1 is already installed, there is no reason to restore the original
pydantic modules, which seems to introduce subtle incompatibilities with some
pydantic versions.
Perform the pydantic version check early on and exit for v1 before doing
anything with the sys.modules.
Fix#3642
* fix axis orientation prop
* add margin prop explanation
* active bar and on animation start
* remove data key from y-axis
* precommit and pyi generator
---------
Co-authored-by: Tom Gotsman <tomgotsman@Toms-MacBook-Pro.local>
Co-authored-by: Tom Gotsman <tomgotsman@toms-mbp.lan>
* fix: unexpected kwargs raise type error, on _replace
* add: docstring for _replace, test for invalid kwargs replace
* add: parametrize var for replace test
* fix: computed_var _replace with invalid kwargs
* - added possibility to pass front- and backend exception handlers to rx.App
- wrapped the app with ErrorBoundary component to catch rendering errors
* added missing exception handler to reflex.app._process
* regenerated pyi
* fix unit tests for exception handler validation
* fix typing error in ErrorBoudary
* - fix error_bounday pyi
- minor refactoring of error boundary
- removed error boundary from 404 page
* added missing inspect module import after merging main
* fix typing error
* Clean up ErrorBoundary component
* Remove custom _render function
* Remove special imports in Component base class
* Simplify hooks for better composability
* test_exception_handlers: also test in prod mode
* fixed color prop
* fixed error boundary bug and removed hardcoding of the frontend event exception state
* formatted the code after conflict resolution
* fixed type of the error_boundary
* ruff format
---------
Co-authored-by: Maxim Vlah <m.vlah@senbax.de>
Co-authored-by: Masen Furer <m_github@0x26.net>
* feat: Adding an event to go back just as the user would.
* fix: Simplification suggested by masenf.
* fix: And now apply the fix to the right function.
* [REF-3067] Do not purge .web/pages in dev mode
Avoid race condition in hot reload that occurs when pages are removed before
they are recreated.
Fix#3416
* use constants instead of hardcoded string
* add immutable var class
* add missing docs
* override _replace
* fix type imports
* override create as well
* remove deprecated properties and arguments
* remove unused code in ImmutableVar
* fix namespace issue
* no Self in 3.8
Ensure that reflex.utils.compat is loaded whenever `reflex` itself is imported
to try and avoid the sqlmodel metaclass conflict error that arises when
sqlmodel is imported first with pydantic v2, but reflex Model inherits from
rx.Base which is based on pydantic v1.
Fix#3515
The formatting of the upload ID had extra single quotes that were not needed.
Now that `_var_name_unwrapped` is used, any `str`-like Vars will automatically
be formatted with backticks
* split lifespan and middleware logic in separate mixin files
* fix for 3.8
* fix for unit tests
* add missing sys import
---------
Co-authored-by: Masen Furer <m_github@0x26.net>
* pyi_generator: avoid fully qualified names for reflex. types
The previous method added quite a large line diff to the pyi files, so for now,
lets just add the `Breakpoints` import to the default set along with Var,
EventHandler, Style and others.
* pyi_generator: fix generated files using ruff
also generate updated pyi files in reflex/experimental namespace
* remove black from dev dependencies
* poetry.lock: relock deps
* Update all pyi files with new formatting
* pre-commit fixes
* pyi_generator: fix __init__.pyi files again
* implement basic behavior to handle both radix and css
* add all components in theme, AND change pyi to include path of reflex types
* order type annotations in pyi_generator (#3585)
* order type annotations in pyi_generator
* run pyi_generator
* classvars should not be backend vars (#3578)
* classvars should not be backend vars
* cleanup RESERVED_BACKEND_VAR_NAMES
* order type annotations in pyi_generator (#3585)
* order type annotations in pyi_generator
* run pyi_generator
* do not validate non-cached var deps (#3576)
* do not validate non-cached var deps
* further improve Exceptions for misconfigured var deps
* order type annotations in pyi_generator (#3585)
* order type annotations in pyi_generator
* run pyi_generator
* fix git merge remains
* define function globally
* use more modern annotations
* only trigger when direct value and not state
* simplify unions
* accidentally removed avatar oop
---------
Co-authored-by: benedikt-bartscher <31854409+benedikt-bartscher@users.noreply.github.com>
* add computed backend vars
* finish computed backend vars, add tests
* fix token for AppHarness with redis state manager
* fix timing issues
* add unit tests for computed backend vars
* automagically mark cvs with _ prefix as backend var
* fully migrate backend computed vars
* rename is_backend_variable to is_backend_base_variable
* add integration test for implicit backend cv, adjust comments
* replace expensive backend var check at runtime
* keep stuff together
* simplify backend var check method, consistent naming, improve test typing
* fix: do not convert properties to cvs
* add test for property
* fix cached_properties with _ prefix in state cls
* Clear color mode local storage
* use the last compiled time logic to determine when to clear local storage
* precommit fix
* app harness fix
* run prettier on reflex/.templates/web/utils/helpers/color_mode.js
* make sure last_compiled_time is updated for stateless apps as well.
* set the chkara-ui-color-mode cookie instead of clearing it, so it is integrated in the app's useEffect cycle
* fix CI
* fix import formatting
---------
Co-authored-by: Masen Furer <m_github@0x26.net>
* Automatic authentication for backend on Github Codespaces
When running reflex on Github codespaces, the port forwarding mechanism
requires authentication, which happens automatically when first accessing the
port via HTTPS; however since the backend connects over the WSS protocol
instead, it gets an access error with no way to redirect to Github's
authentication servers to get the port open.
This PR adds an automatic redirection mechanism to a backend route when there
is a connection error accessing the frontend. After the backend route loads, it
redirects back to the frontend, but now it can connect to the backend via
websocket because the port forward is authenticated.
* manually update .pyi file 🫨
* Dont escape backticks in JS string interpolation
* add unit tests
* Fix darglint
* add a note to re-visit after new Var API is implemented
* tests should have a good meaning
* add bare sqlalchemy session, Closes#3512
* expose sqla_session at module level, add tests, improve typing
* fix table name
* add model_registry fixture, improve typing
* did not meant to push this
* add docstring to model_registry
* do not expose sqla_session in reflex namespace
All major browser use a "bfcache" to freeze pages when navigating away from the
domain, then they restore the page when going back.
However if the page uses websockets, these get kind of stuck unless you
disconnect them before freezing (and have a mechanism for reconnecting, which
we already do).
Ref: https://web.dev/articles/bfcacheFix#3478
* StatefulComponent event handler useCallback dependency array
Ensure the useCallback dependency array for event handlers also handled
destructuring objects and the `...` rest parameter.
Avoid hooks that are not variable declarations.
* Abstract color_mode related Var creation
* Allow `set_color_mode` to take a parameter at compile time
* Update type hinting of `Var._replace` to indicate that it returns BaseVar
* color_mode_button with allow_system=True uses new set_color_mode API
`set_color_mode` is now a CallableVar and uses very similar logic internally,
so this bit of code can be replaced.
* Fix for pydantic v1.10.17
* Ignore type checking for generic aliases in _var_name_unwrapped
* Allow ClientStateVar.set_value to be used with text inputs
* client_state: If var_name is not provided, create a random name
* client_state: partition the arg value to get `_e0` from `_e0.target.value`
* upgrade to latest ruff
* try to fix dep review
* try to fix dep review (2)
* upgrade black
* upgrade black (2)
* update allowed dependencies
* update allowed dependencies (2)
* update allowed dependencies (3)
* wait between interim and final in yield test
* remove previous commit, increase delay between yield
* forgot to save on the time.sleep(1) removal
* fix integration (maybe?)
* fix pyi?
* what even is going on
* what is realityi?
* test another fix for app harness
* try to wait even longer?
* force uvloop to be optional
* downpin fastapi < 0.111, remove changes to test
* add allow_system prop to colormode iconbutton, and clean up logic
* remove segmentedcontrol change from this PR
* make it work for chakraColorProvider too
* add comment to explain resolved_color_mode
* test_background_task: dispatch multiple async tasks
Use asyncio.gather to dispatch multiple tasks from a single background task
that all compete over the `async with self` lock. Even though the state itself
has a lock, each StateProxy instance should only allow a single `async with
self` context to run at a time.
* Protect StateProxy with an asyncio.Lock
Allow multiple tasks to reference the same StateProxy without stomping on each
other when entering an `async with self` context to acquire the state lock and
ultimately modify the state.
* remove stroke and fill from label as they are unsupported by recharts
* refacted legend
* added props to reference line
* updated type for stroke_width, added stroke, updated type for x y
* added x y to reference dot
* updated reference area
* regenerated pyi
* new pyis
* regenerated pyi
---------
Co-authored-by: Hongyu Yao <hongyuyao@Hongyus-MacBook-Pro-3.local>
Co-authored-by: Hongyu Yao <hongyuyao@hongyus-mbp-3.lan>
* `rx.color_mode.icon`, `rx.color_mode.button` and `rx.color_mode.switch` should not require a backend`
* remove print statement
* unit tests and precommit fix
* add unit tests
* change logic to check if event handlers actually contain state. Also delay websocket object check in state.js so server side events can get executed for stateless apps
* make sure events are not queued for server side events particularly ones that call queueEvents(clear_local_storage, clear_cookies, remove_local_storage, remove_cookies) when the app is stateless(no ws)
* fix unit tests
* fix broken unit tests in test_app
* modify socket check in processEvent to only return if socket exists and theres any event in the queue that requires state
* Apply suggestions from code review
make queueEvent call async
Co-authored-by: Masen Furer <m_github@0x26.net>
* await queueEventIfSocketExists
* Revert "await queueEventIfSocketExists"
This reverts commit 9ef8070b87.
---------
Co-authored-by: Masen Furer <m_github@0x26.net>
1. Updated recharts version to the newest - recharts.py
2. Added `legend_type` back for cartesian class, it was currently commented out - cartesian.py
3. Added `vertical_points` and `horizontal_points` to CartesianGrid class - cartesian.py
4. Added `ticks` `tick` `tick_count` `tick_line` `tick_size` `min_tick_gap`props to Axis class - cartesian.py
5. Refactored `on_click` `on_mouse_down` `on_mouse_up` `on_mouse_move` `on_mouse_out` `on_mouse_enter` `on_mouse_leave` event triggers of `Axis` class using Masen's new method - cartesian.py
6. Added `on_animation_begin` and `on_animation_end` event trigger to `Bar(Cartesian)` class - cartesian.py
7. Added `id` `is_animation_active` `animation_begin` `animation_duration` `animation_easing` `unit` `min_point_size` `name` prop to `Bar(Cartesian)` class - cartesian.py.
8. Added `unit` `name` props to `Area(Cartesian)` class - cartesian.py
9. Added `unit` `name` props to `Line(Cartesian)` class - cartesian.py
10. Added `id` `is_animation_active` `animation_begin` `animation_duration` `animation_easing` props to `Scatter(Recharts)` class - cartesian.py
11. Refactored eventtriggers for `Scatter(Recharts)` class using Masen's new method - cartesian.py
12. Change the var type of stack_id in `Area(Cartesian)` class to be string and int, it used to be only a string. - cartesian.py
13. Added `name_key` prop and `on_animation_start` and `on_animation_end` prop to `Funnul(Recharts)` class cartesian.py
14. Added `on_mouse_down` `on_mouse_up` `on_mouse_over` `on_mouse_out` event triggers to `PieChart(ChartBase)` and also refactored using Masen's new method - Charts.py
15. Refaactored event triggers for referenceDot(Reference) class using Masen's new method. - Cartesian.py
16. Refactored event triggers for ChartBase(RechartsCharts) class using Masen's new method. - Cartesian.py
17. Refactored event triggers for Piechart(ChartBase) class using Masen's new method, Added `on_mouse_down` `on_mouse_up` `on_mouse_over` `on_mouse_out` event triggers - Cartesian.py
Co-authored-by: Hongyu Yao <hongyuyao@hongyus-mbp-3.lan>
In pydantic 1.10.16 (hopefully the last version), they added the `pydantic.v1`
namespace to make transitioning to the v2 package easier without changing code.
However, Reflex was depending on pydantic v1 NOT having `pydantic.v1` to skip
patching names from `v1` into the top level `pydantic` (normally we do this to
force sqlmodel to use v1, even when the v2 package is installed).
Unbreak CI
* Override _var_is_string when handling str literals
Maintain the pre 0.5.4 behavior when dealing with string literal
props, without displaying the deprecation warning.
Wait, isn't it weird to pass `_var_is_string=False` when the type is actually a str??
Yes, yes it is. However this is currently needed to avoid raising the
DeprecationWarning internally. These str-type vars with
_var_is_string set to false are handled by
`reflex.utils.format.format_prop`, but setting them to be
_var_is_string=True causes them to get quoted twice, which is not
what we want.
Var operations refactor will take care of cleaning this up, but for
now, we will go with the hack.
* Ignore type checks
Since I'm using an `isinstance` check now, the type checker thinks that `value`
could possibly be a string (instead of Any), which raises typing errors that
have to be ignored (they were ignored before implicitly due to being Any-typed)
* Make client_state work without global refs (local only)
* client_state: if the default is str, mark _var_is_string=True
Ensure that a string default is not rendered literally
* add `to_int` as a Var operation
* Allow an event handler lambda to return a Var in some cases
If an lambda is passed to an event trigger and it returns a single Var, then
treat it like the Var was directly passed for the event trigger.
This allows ClientState.set_var to be used within a lambda.
* test_connection_banner: Improve assertions
* Actually assert on the presence or absense of the connection banner
* Update XPATH selector to find the connection toast
* Add event handling while backend down to verify queue functionality
* Bring backend down while an event is running to ensure queue does not get
blocked (#3404)
* state.js: set event_processing = false when websocket connects
In case an event was pending when the websocket went down, allow further events
to be processed when it comes back up.
Fix#3404
* test_connection_banner: wait for token indicating backend is connected
* test_connection_banner: increase delay time
make the time window longer in which the backend can go down and get stuck in
event_processing=true for better test reliability
* Ensure the redis connection is reset in new backend thread
Redis has an event loop affinity and needs to be attached to the event loop
that the thread is running.
* Reset event_processing on disconnect
* if the socket never comes back up, it still allows client-side events to be
processed
* on_mount events may start running before the socket is up, so resetting the
flag on connect may break event determinism (test_event_chain.py)
* wip type transforming serializers
* old python sucks
* typing fixups
* Expose the `to` parameter on `rx.serializer` for type conversion
Serializers can also return a tuple of `(serialized_value, type)`, if both ways
are specified, then the returned value MUST match the `to` parameter.
When initializing a new rx.Var, if `_var_is_string` is not specified and the serializer returns a `str` type, then mark `_var_is_string=True` to indicate that the Var should be treated like a string literal.
Include datetime, color, types, and paths as "serializing to str" type.
Avoid other changes at this point to reduce fallout from this change:
Notably, the `serialize_str` function does NOT cast to `str`, which
would cause existing code to treat all Var initialized with a str as a
str literal even though this was NOT the default before.
Update test cases to accomodate these changes.
* Raise deprecation warning for rx.Var.create with string literal
In the future, we will treat strings as string literals in the JS code. To get
a Var that is not treated like a string, pass _var_is_string=False.
This will allow our serializers to automatically identify cast string literals
with less special cases (and the special cases need to be explicitly
identified).
* Add test case for mismatched serialized types
* fix old python
* Remove serializer returning a tuple feature
Simplify the logic; instead of making a wrapper function that returns
a tuple, just save the type conversions in a separate global.
* Reset the LRU cache when adding new serializers
---------
Co-authored-by: Masen Furer <m_github@0x26.net>
* Addresses an issue with pydantic v2 models as Vars
It looks like there's an issue with state vars
which are pydantic v2 models... Here's a
reproducible test case:
```python
import reflex as rx
from pydantic import BaseModel
from reflex.utils.serializers import serializer
class User(BaseModel):
has_image: bool = False
@serializer
def serialize_user(user: User) -> dict:
return user.dict()
class State(rx.State):
user: User = None
def index() -> rx.Component:
return rx.container(
rx.cond(State.user,
rx.text(State.user.has_image),
rx.text("No user"))
)
app = rx.App()
app.add_page(index)
```
This app works only with pydantic <2 installed:
```bash
reflex-test $ reflex run
...
AttributeError: 'FieldInfo' object has no attribute 'outer_type_'
reflex-test $ pip install pydantic==1.10.15
─────────────────────────────────── Starting Reflex App ───────────────────────────────────
Compiling: ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 100% 13/13 0:00:00
─────────────────────────────────────── App Running ───────────────────────────────────────
App running at: http://localhost:3000
```
Looks like this is caused by `outer_type_` no
[longer existing][1] in pydantic v2. I'm guessing
this was introduced back in [v0.4.6][2].
1: https://github.com/pydantic/pydantic/discussions/7217
2: 86526cba51
This change explicitly ignores pydantic v2 models in
`get_attribute_access_type`, rather than trying to treat
them as v1 models.
* ruff formatting
---------
Co-authored-by: Masen Furer <m_github@0x26.net>
* [REF-2977] [REF-2982] Merge layout prop and automatic darkmode
* Expose `template` prop in rx.plotly
* Set default `template` to a color_mode_cond that responds to dark mode
* Merge user-provided `layout` and `template` props into the serialized
plot data
* pyi_generator: avoid affecting the HTML Template component
* Raise warning when importing rx.plotly without plotly installed
* Remove PlotlyLib component and consolidate imports [fixup]
* test_tailwind: include custom stylesheet
* [REF-3004] Use relative path to stylesheet for postcss-import compat
postcss-import balls all of the CSS up into a single file, which happens at
compile time. So, replace the `@/` with `../public` so the import paths can be
resolved relative to the `styles` directory.
* test_compiler: fix compile_stylesheets expectations
* Use constants.Dirs.PUBLIC instead of "public"
* include resize and radius props to the text area component
* run scripts/make_pyi.py for text_area
* pre-commit fixup
---------
Co-authored-by: Masen Furer <m_github@0x26.net>
* pyi_generator: do not generate kwargs for event trigger props
event triggers are handled separately
* Implement event handlers for Plotly
* py38 compat: from __future__ import annotations
* init fix
* Update reflex/components/plotly/plotly.py
Co-authored-by: Masen Furer <m_github@0x26.net>
* plotly: treat `data` as a `dict`-type Var in _render
this allows the data to be passed directly as a figure or from a state var
* removed width height prop as they are no longer needed
* updated
* reverted some of the changes
* fixed unit tests
* regen pyi
---------
Co-authored-by: Hongyu Yao <hongyuyao@hongyus-mbp-3.lan>
Co-authored-by: Masen Furer <m_github@0x26.net>
Co-authored-by: Hongyu Yao <hongyuyao@Hongyus-MacBook-Pro-3.local>
* Improve import times
* add lazy loading to rx.el
* add lazy loading to reflex core components
* minor refactor
* Get imports working with reflex web
* get imports to work with all reflex examples
* refactor to define imports only in the root.
* lint
* deadcode remove
* update poetry deps
* unit tests fix
* app_harness fix
* app_harness fix
* pyi file generate
* pyi file generate
* sort pyi order
* fix pyi
* fix docker ci
* rework pyi-generator
* generate pyi for __init__ files
* test pyright
* test pyright ci
* partial pyright fix
* more pyright fix
* pyright fix
* fix pyi_generator
* add rx.serializer and others
* add future annotation import which fixes container CI, then also load recharts lazily
* add new pyi files
* pyright fix
* minor fixes for reflex-web and flexdown
* forward references for py38
* ruff fix
* pyi fix
* unit tests fix
* reduce coverage to 68%
* reduce coverage to 67%
* reduce coverage to 66%as a workaround to coverage's rounding issue
* reduce coverage to 66%as a workaround to coverage's rounding issue
* exclude lazy_loader dependency review checks.
* its lazy-loader
* Add docstrings and regenerate pyi files
* add link
* address Pr comments
* CI fix
* partially address PR comments.
* edit docstrings and fix integration tests
* fix typo in docstring
* pyi fix
# 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'\
@ -250,7 +249,7 @@ We welcome contributions of any size! Below are some good ways to get started in
- **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 [CONTIBUTING.md](https://github.com/reflex-dev/reflex/blob/main/CONTRIBUTING.md)
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)
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.
<divalign="center">
<imgsrc="https://raw.githubusercontent.com/reflex-dev/reflex/main/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.
<divalign="center">
<imgsrc="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.
Reflex wurde im Dezember 2022 unter dem Namen Pynecone gestartet.
Ab Februar 2024 befindet sich unser Hosting-Service in der Alpha-Phase! In dieser Zeit kann jeder seine Apps kostenlos bereitstellen. Siehe unsere [Roadmap](https://github.com/reflex-dev/reflex/issues/2727), um zu sehen, was geplant ist.
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.
@ -35,7 +35,7 @@ Consulta nuestra [página de arquitectura](https://reflex.dev/blog/2024-03-21-re
## ⚙️ Instalación
Abra un terminal y ejecute (Requiere Python 3.8+):
Abra un terminal y ejecute (Requiere Python 3.10+):
```bash
pip install reflex
@ -239,7 +239,7 @@ Reflex se lanzó en diciembre de 2022 con el nombre de Pynecone.
- **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 [CONTIBUTING.md](https://github.com/reflex-dev/reflex/blob/main/CONTRIBUTING.md)
Buscamos colaboradores, sin importar su nivel o experiencia. Para contribuir consulta [CONTRIBUTING.md](https://github.com/reflex-dev/reflex/blob/main/CONTRIBUTING.md)
@ -36,7 +35,7 @@ Reflex के अंदर के कामकाज को जानने क
## ⚙️ इंस्टॉलेशन (Installation)
एक टर्मिनल खोलें और चलाएं (Python 3.8+ की आवश्यकता है):
एक टर्मिनल खोलें और चलाएं (Python 3.10+ की आवश्यकता है):
```bash
pip install reflex
@ -240,7 +239,7 @@ Reflex में हर सप्ताह नए रिलीज़ और फ
- **GitHub Discussions** (गिटहब चर्चाएँ): उन सुविधाओं के बारे में बात करने का एक शानदार तरीका जिन्हें आप जोड़ना चाहते हैं या ऐसी चीज़ें जो भ्रमित करने वाली हैं/स्पष्टीकरण की आवश्यकता है।
- **GitHub Issues** (गिटहब समस्याएं): ये [बग](https://github.com/reflex-dev/reflex/issues) की रिपोर्ट करने का एक शानदार तरीका है। इसके अतिरिक्त, आप किसी मौजूदा समस्या को हल करने का प्रयास कर सकते हैं और एक पीआर सबमिट कर सकते हैं।
हम सक्रिय रूप से योगदानकर्ताओं की तलाश कर रहे हैं, चाहे आपका कौशल स्तर या अनुभव कुछ भी हो।योगदान करने के लिए [CONTIBUTING.md](https://github.com/reflex-dev/reflex/blob/main/CONTRIBUTING.md) देखें।
हम सक्रिय रूप से योगदानकर्ताओं की तलाश कर रहे हैं, चाहे आपका कौशल स्तर या अनुभव कुछ भी हो।योगदान करने के लिए [CONTRIBUTING.md](https://github.com/reflex-dev/reflex/blob/main/CONTRIBUTING.md) देखें।
رفلکس(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 که به صورت محلی اجرا می شود جایگزین کنید.
<divalign="center">
<imgsrc="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>
در اینجا کد کامل برای ایجاد این پروژه آمده است. همه اینها در یک فایل پایتون انجام می شود!
```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")
```
## بیاید سادش کنیم
<divalign="center">
<imgsrc="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")
```
با افزودن صفحات بیشتر می توانید یک برنامه چند صفحه ای ایجاد کنید.
رفلکس(reflex) در دسامبر 2022 با نام Pynecone راه اندازی شد.
از فوریه 2024، سرویس میزبانی ما در آلفا است! در این مدت هر کسی میتواند برنامههای خود را به صورت رایگان اجرا کند. [نقشه راه](https://github.com/reflex-dev/reflex/issues/2727) را ببینید تا متوجه شوید چه برنامهریزی شده است.
رفلکس(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 - با تشکر از همکاران ما:
- **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: [CONTIBUTING.md](https://github.com/reflex-dev/reflex/blob/main/CONTRIBUTING.md)
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)
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.
<divalign="center">
<imgsrc="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>
Đâ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.
<divalign="center">
<imgsrc="../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.
Reflex phát hành vào tháng 12/2022 với tên là Pynecone.
Đến tháng 02/2024, chúng tôi tạo ra dịch vụ dưới phiên bản alpha! Trong thời gian này mọi người có thể triển khai ứng dụng hoàn toàn miễn phí. Xem [roadmap](https://github.com/reflex-dev/reflex/issues/2727) để biết thêm chi tiết.
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
<imgsrc="docs/images/dalle_colored_code_example.png" alt="Explaining the differences between backend and frontend parts of the DALL-E app." width="900"/>
"Reflex is an open-source app framework built specifically to allow you to build web apps in pure python. 👈 Select a demo from the sidebar to see some examples of what Reflex can do!",
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.