### Project Setup and Dependencies
Source: https://github.com/reflex-dev/reflex-examples/blob/main/form-designer/requirements-dev.txt
This section outlines the essential tools and libraries required to run and test the Reflex examples. It includes installation commands for package managers and testing frameworks.
```bash
pip install pytest
pip install playwright
playwright install
pip install pytest-playwright
pip install uvicorn
pip install psutil
```
--------------------------------
### Run the Application
Source: https://github.com/reflex-dev/reflex-examples/blob/main/linkinbio/README.md
Starts the Reflex application. The app will be accessible at http://localhost:3000 by default.
```bash
reflex run
```
--------------------------------
### Install Dependencies
Source: https://github.com/reflex-dev/reflex-examples/blob/main/linkinbio/README.md
Installs the Python packages required for the Link in Bio application using pip. It relies on the `requirements.txt` file.
```bash
pip install -r requirements.txt
```
--------------------------------
### Database Initialization and Migration
Source: https://github.com/reflex-dev/reflex-examples/blob/main/basic_crud/README.md
Commands to initialize the Reflex database and apply migrations for the basic CRUD example.
```bash
reflex db init
reflex db migrate
```
--------------------------------
### Running the Reflex Application
Source: https://github.com/reflex-dev/reflex-examples/blob/main/basic_crud/README.md
Commands to initialize and run the Reflex application.
```bash
reflex init
reflex run
```
--------------------------------
### Reflex and OpenAI Integration Example
Source: https://github.com/reflex-dev/reflex-examples/blob/main/dalle/requirements.txt
This snippet demonstrates how to set up a Reflex application that integrates with the OpenAI API. It requires reflex version 0.8.0 or higher and openai version 1 or higher. The example likely involves making API calls to OpenAI for tasks such as text generation or chat completion within a Reflex UI.
```python
import reflex as rx
# Assuming you have an OpenAI client initialized elsewhere
# from openai import OpenAI
# client = OpenAI(api_key="YOUR_API_KEY")
def index():
return rx.text("Welcome to the Reflex OpenAI Example!")
# Example of a function that might call OpenAI
def get_openai_response(prompt: str) -> str:
# Replace with actual OpenAI API call
# response = client.chat.completions.create(
# model="gpt-3.5-turbo",
# messages=[{"role": "user", "content": prompt}]
# )
# return response.choices[0].message.content
return f"Simulated response for: {prompt}"
# Example usage within a Reflex component
def chat_component():
return rx.vstack(
rx.text("Ask me something!"),
rx.button("Get Response", on_click=lambda: print(get_openai_response("Hello")))
)
app = rx.App()
app.add_page(index)
app.add_page(chat_component, route="/chat")
```
--------------------------------
### Clone Repository and Navigate
Source: https://github.com/reflex-dev/reflex-examples/blob/main/linkinbio/README.md
Clones the reflex-examples repository and navigates into the linkinbio directory. This is the first step to setting up the project locally.
```bash
git clone https://github.com/reflex-dev/reflex-examples
cd reflex-examples/linkinbio
```
--------------------------------
### Product API Endpoints
Source: https://github.com/reflex-dev/reflex-examples/blob/main/basic_crud/README.md
Defines the API endpoints for managing products, including supported HTTP methods and their functionalities.
```APIDOC
Products API:
GET /products
Description: Retrieves a list of all products.
Parameters: None
Returns: A list of product objects.
POST /products
Description: Creates a new product.
Request Body: A JSON object representing the product to be created.
Returns: The newly created product object.
GET /products/[id]
Description: Retrieves a specific product by its ID.
Parameters:
id: The unique identifier of the product.
Returns: The product object corresponding to the provided ID.
PUT /products/[id]
Description: Updates an existing product by its ID.
Parameters:
id: The unique identifier of the product to update.
Request Body: A JSON object containing the updated product information.
Returns: The updated product object.
DELETE /products/[id]
Description: Deletes a product by its ID.
Parameters:
id: The unique identifier of the product to delete.
Returns: A confirmation message or status indicating the deletion.
```
--------------------------------
### Core Dependencies
Source: https://github.com/reflex-dev/reflex-examples/blob/main/chat_v2/requirements.txt
Lists the essential Python packages and their version constraints for the reflex-examples project. These include AI, instrumentation, and core framework libraries.
```python
openai>=1.55.3
openinference-instrumentation>=0.1.18
opentelemetry-exporter-otlp>=1.27.0
pytz>=2024.2
together>=1.3.1
reflex>=0.8.0
```
--------------------------------
### Reflex Configuration
Source: https://github.com/reflex-dev/reflex-examples/blob/main/linkinbio/README.md
Configuration file for the Reflex application. It typically defines the app name and other project-specific settings.
```python
import reflex as rx
config = rx.Config(
app_name="linkinbio",
# ... other configurations
)
```
--------------------------------
### Requirements File
Source: https://github.com/reflex-dev/reflex-examples/blob/main/linkinbio/README.md
Lists the Python dependencies required for the Link in Bio application, including the specific version of the Reflex framework.
```plaintext
reflex==0.1.10
```
--------------------------------
### Local React Component (hello.jsx)
Source: https://github.com/reflex-dev/reflex-examples/blob/main/local-component/README.md
A basic React component that displays a greeting. This serves as the custom UI element to be integrated into the Reflex application.
```javascript
import { component } from "@ائح/reflex";
export default component(
(props) => {
return
Hello {props.name}!
;
},
{
name: "hello",
}
);
```
--------------------------------
### Git Ignore File
Source: https://github.com/reflex-dev/reflex-examples/blob/main/linkinbio/README.md
Specifies files and directories that should be ignored by Git version control. This prevents unnecessary files from being committed.
```plaintext
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
dist/
*.egg-info/
```
--------------------------------
### Link in Bio App Logic
Source: https://github.com/reflex-dev/reflex-examples/blob/main/linkinbio/README.md
Contains the main application logic for the Link in Bio app, including functions to define UI components like link buttons and the main page layout. It handles displaying user information and links.
```python
import reflex as rx
def link_button(text, url):
return rx.button(
text,
style={
"width": "100%",
"height": "50px",
"background": "#fff",
"color": "#000",
"border_radius": "5px",
"margin_top": "10px",
"border": "none",
"font_size": "16px",
"font_weight": "bold",
},
on_click=lambda: rx.redirect(url),
)
def index():
return rx.vstack(
rx.heading("Erin Mikail Staples", size="7", color="#fff"),
rx.text("Software Engineer", color="#fff"),
link_button("GitHub", "https://github.com/erinmikailstaples"),
link_button("LinkedIn", "https://www.linkedin.com/in/erinmikailstaples/"),
link_button("Twitter", "https://twitter.com/erinmikailstaples"),
link_button("Personal Website", "https://erinmikailstaples.com/"),
spacing="3",
align="center",
padding="5em",
bg="radial-gradient(circle at 24.1% 118.9%, #ff9a9e 0%, #fecfef 49%, #a9def9 100%)",
)
app = rx.App()
app.add_page(index)
```
--------------------------------
### Reflex Wrapper for Local Component
Source: https://github.com/reflex-dev/reflex-examples/blob/main/local-component/README.md
Python code that defines a Reflex component wrapper for the custom React component. It maps Python properties to React props.
```python
import reflex as rx
from .local_component import hello
def index():
return rx.center(
hello(name="World"),
height="100vh",
)
```
--------------------------------
### App Styling
Source: https://github.com/reflex-dev/reflex-examples/blob/main/linkinbio/README.md
Defines the styling for the Link in Bio app components, including buttons, links, and the overall layout. It uses a vibrant gradient background and modern UI elements.
```python
import reflex as rx
STYLES = {
"heading": {
"color": "white",
"font_size": "3em",
},
"text": {
"color": "white",
"font_size": "1.5em",
},
"button": {
"width": "100%",
"height": "50px",
"background": "#fff",
"color": "#000",
"border_radius": "5px",
"margin_top": "10px",
"border": "none",
"font_size": "16px",
"font_weight": "bold",
},
"vstack": {
"spacing": "3",
"align": "center",
"padding": "5em",
"bg": "radial-gradient(circle at 24.1% 118.9%, #ff9a9e 0%, #fecfef 49%, #a9def9 100%)",
},
}
```
--------------------------------
### Data Loading and Model Definition in Reflex
Source: https://github.com/reflex-dev/reflex-examples/blob/main/data_visualisation/Readme.md
This snippet illustrates how to define database models and load data into a Reflex application. It highlights the importance of matching model keys to data source column names and provides guidance on handling column names that are not valid Python identifiers. It also mentions the flexibility of adding support for new data types by creating custom `loading_data` functions.
```python
from reflex.model import Model
class Customer(Model):
"""Database model for customer data."""
name: str
email: str
phone: str
class Cereals(Model):
"""Database model for cereal data."""
name: str
manufacturer: str
calories: int
class Covid(Model):
"""Database model for COVID-19 data."""
country: str
cases: int
deaths: int
class Countries(Model):
"""Database model for country information."""
name: str
capital: str
population: int
# Example of how to load data (assuming data_loading.py exists)
# from data_loading import load_csv_data
#
# def get_customers():
# return load_csv_data(Customer, "path/to/customers.csv")
# In your app setup:
# config = rx.Config(
# app_name="data_app",
# db_url="sqlite:///./data.db",
# frontend_packages=["react-data-grid"],
# backend_packages=["sqlalchemy"],
# )
# rx.add_app(app_name="data_app", config=config)
# rx.add_page(Index, route="/")
# To use a specific model:
# Set MODEL = Customer
# Set data_file_path = "path/to/your/data.csv"
```
--------------------------------
### LoremState.stream_text Background Task
Source: https://github.com/reflex-dev/reflex-examples/blob/main/lorem-stream/README.md
The background task responsible for generating and streaming lorem text. It manages task progress, iteration counts, and text generation. It can be assigned a new task ID or use an existing one.
```python
class LoremState(State):
running: bool = False
progress: int = 0
end_at: int = 0
text: str = ""
def stream_text(self, task_id: Optional[str] = None):
if task_id is None:
task_id = str(uuid.uuid4())
else:
self.set_session(task_id)
self.running = True
self.progress = 0
self.end_at = random.randint(5, 15)
while self.running and self.progress < self.end_at:
self.progress += 1
self.text += lorem.sentence()
yield
self.running = False
```
--------------------------------
### Dynamic JSON Tree Rendering
Source: https://github.com/reflex-dev/reflex-examples/blob/main/json-tree/README.md
This snippet shows how to use Reflex's dynamic components to render a JSON structure. It takes JSON input and displays it as a nested data list, bypassing the need for `rx.cond` or `rx.foreach` for dynamic UI generation.
```python
import reflex as rx
class State(rx.State):
json_input: str = ""
parsed_json: dict = {}
def parse_json(self):
try:
self.parsed_json = rx.utils.json.loads(self.json_input)
except:
self.parsed_json = {"error": "Invalid JSON"}
def index():
return rx.vstack(
rx.input(
placeholder="Paste valid JSON here",
value=State.json_input,
on_change=State.set_json_input
),
rx.button("Parse JSON", on_click=State.parse_json),
rx.cond(
State.parsed_json,
rx.data_list(
items=rx.utils.json.json_to_data_list(State.parsed_json)
)
)
)
app = rx.App()
app.add_page(index)
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.