> ## Documentation Index
> Fetch the complete documentation index at: https://launchdarkly.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Build A Beautiful Camera with Python, feature flags, and WebSockets

> Build a collaborative Flask photo booth, target sticker packs with LaunchDarkly, and update open browsers with Socket.IO.

**Developer**

**Federal docs**

**EU docs**

*Published November 23, 2026*

Portrait of Diane Phan.

by Diane Phan

Want to squeeze into a photo booth with your friends without squeezing into an actual booth? Let's build one in the browser. Take a photo, add a few hearts, and invite someone else to decorate the same picture with you.

**A Beautiful Camera** is a Python application inspired by purikura, the Japanese photo booths known for playful photo decorations. Our version has a shared photo, colorful sticker packs, and a gallery for saving your creations. It also has a release problem to solve: how do you introduce a new sparkle sticker pack to selected visitors, then turn it off if something goes wrong while people are still decorating?

In this tutorial, you'll run the Flask photo booth and walk through the code that connects LaunchDarkly feature flags to a live interface. You'll use targeting to give different artists different sticker packs, then use Socket.IO to update their browsers without reloading the page.

The [complete photo booth source](https://github.com/dianephan/purikura-prototype) includes the camera, styles, and gallery. Follow along with that implementation. The code samples below explain existing sections rather than forming a second application to paste into `app.py`.

Here's the booth before releasing the sparkle pack:

![A Beautiful Camera with Diane selected, classic heart and star stickers on a pastel backdrop, and the sparkle palette locked.](https://mintcdn.com/launchdarkly/9mdC6T6nS8-uzXsc/images/tutorials/build-a-beautiful-camera/01-classic-booth.png?fit=max\&auto=format\&n=9mdC6T6nS8-uzXsc\&q=85\&s=5881a96d6c6159834e55f2e94bd8b282)

*The classic booth works while sparkle targeting is off. The control room reports `OFF` for every artist.*

All screenshots show the actual app captured with Playwright using local SDK test data. The green camera image is Chromium's simulated camera, not a person's photo. Local flag fixtures and the app's notification callback reproduce the tutorial's release states. These captures do not verify a live LaunchDarkly stream or show the LaunchDarkly UI.

## Tutorial requirements

To follow along, you need:

* Python 3.10 or newer and Git installed on your computer.
* A code editor and a browser with camera support.
* A LaunchDarkly account with permission to create flags and segments in a project and environment.
* The server-side software development kit (SDK) key for that environment.

You can decorate the pastel backdrop without granting camera access. To take a photo, use `localhost` or a site served over HTTPS. Browsers require a secure context and your permission for [`getUserMedia()`](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia).

## Understand the two live connections

A feature flag separates deploying code from releasing a feature. We can deploy the sparkle pack with the rest of the application, then decide who can use it through `sparkleStickerEngine`. The Python server evaluates that flag for each artist.

WebSockets solve a different part of the experience: keeping a browser and server in communication after the page loads. We use [Socket.IO](https://socket.io/docs/v4/) for named, bidirectional events. It can use WebSocket transport and fall back to HTTP long-polling. Because Socket.IO adds its own protocol, this app uses its JavaScript client rather than the browser's native `WebSocket` constructor.

There are two separate connections in this design:

```text theme={null}
LaunchDarkly ── flag configuration stream ──> Python SDK
                                                 │
                                        Evaluate each artist
                                                 │
Browser <──── Socket.IO: flag_update ──────── Flask server
Browser ───── Socket.IO: place_sticker ──────> Flask server
All browsers <── Socket.IO: sticker_added ─── Flask server
```

The SDK's default streaming connection receives configuration updates from LaunchDarkly. It is separate from the browser connection. Our application bridges them by evaluating the updated flag and sending the results through Socket.IO. A flag change does not update an already-rendered page on its own.

## Set up the Python application

Clone the project and create a virtual environment:

```bash theme={null}
git clone https://github.com/dianephan/purikura-prototype.git
cd purikura-prototype
python3 -m venv .venv
source .venv/bin/activate
python -m pip install -r requirements.txt
cp .env.example .env
```

On Windows PowerShell, activate with `.venv\Scripts\Activate.ps1` and copy the configuration with `Copy-Item .env.example .env`.

The dependencies include Flask for routes and templates, Flask-SocketIO and `simple-websocket` for browser events, `launchdarkly-server-sdk` for flag evaluation, and `python-dotenv` for local configuration. The [flag-change listener requires Python SDK version 9.1 or later](https://launchdarkly.com/docs/sdk/features/flag-changes.md#python). Install a compatible version if your existing environment has 9.0:

```bash theme={null}
python -m pip install "launchdarkly-server-sdk>=9.1,<10"
```

Open `.env` and replace the placeholder SDK key with the server-side key from your chosen LaunchDarkly environment:

```dotenv theme={null}
LD_SDK_KEY=sdk-your-environment-key
PORT=5055
```

Keep this key on the server. The browser receives evaluated booleans, not SDK credentials.

The files we'll work through have these responsibilities:

| File | Responsibility |
| - | - |
| `app.py` | Evaluate flags, manage the shared booth, and handle Socket.IO events. |
| `templates/index.html` | Render the camera, sticker palettes, gallery, and control room. |
| `static/booth.js` | Capture photos, send interactions, and update the interface. |
| `static/style.css` | Style the pastel booth, sticker effects, and locked palettes. |

## Configure the sticker flags

Create the flags in the same project and environment as your SDK key. Flag keys are case-sensitive.

Start by defining the reusable audiences:

1. Open your environment's **Segments** page.
2. Create a segment with the key `free-tier`.
3. Add a rule matching the `artist` context kind's `plan` attribute to `free`.
4. Save the segment.
5. Create a segment with the key `premium-tier`.
6. Add a rule matching the `artist` context kind's `plan` attribute to `pro`.
7. Save the segment.

Next, configure the primary flag:

1. Create a boolean flag with the key `sparkleStickerEngine`.
2. Set its off variation to `false`.
3. Add an individual target for context kind `artist`, key `diane-artist`, serving `true`.
4. Add a targeting rule matching the `free-tier` segment, serving `false`.
5. Set the default rule to serve `true`.
6. Save the configuration with targeting off in your chosen environment.

Finally, configure the second pack:

1. Create a boolean flag with the key `spookyStickerPack`.
2. Set its off variation to `false`.
3. Add a targeting rule matching the `premium-tier` segment, serving `true`.
4. Set the default rule to serve `false`.
5. Save the configuration and turn targeting on.

Both flags reuse the same audience definitions. This lets you release sparkle stickers and a seasonal pack independently.

With sparkle targeting on, expect these results:

| Artist key | Plan | Sparkle | Spooky | Why sparkle is available |
| - | - | - | - | - |
| `diane-artist` | `free` | Yes | No | Individual target. |
| `mika-pro` | `pro` | Yes | Yes | Default rule. |
| `sam-free` | `free` | No | No | Free-tier rule serves `false`. |
| `rin-pro` | `pro` | Yes | Yes | Default rule. |

Diane receives sparkle even though she matches the free-tier segment because [individual targeting](https://launchdarkly.com/docs/home/flags/individual-targeting.md) takes precedence over custom rules, assuming prerequisites are satisfied. When targeting is off, the configured off variation applies, including to Diane.

## Initialize the SDK and evaluate each artist

Open `app.py`. The `main()` function initializes one shared LaunchDarkly client before starting the server. This excerpt shows the default setup. The repository also supports optional endpoint overrides:

```python theme={null}
ldclient.set_config(Config(SDK_KEY))
client = ldclient.get()
if not client.is_initialized():
    raise SystemExit("LaunchDarkly client failed to initialize")

client.flag_tracker.add_listener(on_flag_change)
socketio.run(app, host="0.0.0.0", port=PORT, debug=False,
             allow_unsafe_werkzeug=True)
```

The app exits if initialization fails. After initialization, the [Python SDK](https://launchdarkly.com/docs/sdk/server-side/python) evaluates flags using its local flag data rather than making a network request for each sticker placement.

LaunchDarkly needs a context describing who is requesting the feature. In `build_context()`, the app creates an `artist` context with a stable key and attributes that match our rules:

```python theme={null}
artist = (
    Context.builder(persona_key)
    .kind("artist")
    .name(p["name"])
    .set("plan", p["plan"])
    .set("country", p["country"])
    .set("device", p["device"])
    .build()
)
user = Context.builder(persona_key).kind("user").name(p["name"]).build()
return Context.create_multi(user, artist)
```

Here, `p` is the selected persona's record from `PERSONAS`. The multi-kind context combines `artist`, which supplies targeting attributes, with `user`, which the sample reserves for experiment randomization. You can use an `artist` context alone when experimentation is outside your application’s scope.

The `evaluate()` function retrieves the sparkle decision and its explanation:

```python theme={null}
ctx = build_context(persona_key)
detail = ldclient.get().variation_detail(FLAG_KEY, ctx, False)
spooky = bool(ldclient.get().variation(SPOOKY_FLAG_KEY, ctx, False))
```

The final `False` is the fallback if evaluation cannot produce a value. It is separate from the off variation you configured in LaunchDarkly. A temporary stream interruption does not automatically turn the flag off: the SDK can continue using its last known flag data.

The function returns each artist's decisions with `detail.reason`. The control room displays reasons such as `OFF`, `TARGET_MATCH`, `RULE_MATCH`, and `FALLTHROUGH`, connecting the visible sticker palette to the rule that selected it. Its segment labels are derived from the demo personas' plans. They are not a segment-membership response from LaunchDarkly.

## Send flag changes to browsers without a reload

The server creates its Socket.IO instance near the top of `app.py`:

```python theme={null}
socketio = SocketIO(app, async_mode="threading", cors_allowed_origins="*",
                    max_http_buffer_size=8_000_000)
```

The larger message limit accommodates a captured image. The permissive origins setting is part of this demo. Restrict allowed origins for a deployed application. Start the sample with `python app.py` so it uses [`socketio.run()`](https://flask-socketio.readthedocs.io/en/latest/getting_started.html), as shown above.

The registered listener connects SDK changes to the browser event stream:

```python theme={null}
def on_flag_change(flag_change):
    if flag_change.key not in (FLAG_KEY, SPOOKY_FLAG_KEY):
        return
    socketio.emit("flag_update", {
        "evaluations": evaluate_all(),
        "at": time.strftime("%H:%M:%S"),
    })
```

`flag_change.key` identifies a changed flag. It does not contain one universal boolean for every visitor. The callback re-evaluates the personas because the same flag can serve different values to Diane and Sam. It uses `socketio.emit()` to broadcast from outside a browser request handler.

In `static/booth.js`, the client receives those decisions:

```javascript theme={null}
socket.on("flag_update", (update) => {
  applyEvaluations(update.evaluations, true);
  addLog(`${update.at} — flag changed in LaunchDarkly`);
});
```

`applyEvaluations()` finds the current artist, enables or disables their palette buttons, and updates the control room. If a selected sparkle sticker becomes unavailable, it switches the selection back to a classic heart. There is no `location.reload()`, which means the current photo and placed stickers remain on screen.

After enabling sparkle, compare the unlocked palette with each artist's evaluation reason:

![Diane's sparkle palette unlocked with sparkle stickers on the captured image. The control room shows TARGET\_MATCH for Diane, RULE\_MATCH for Sam, and FALLTHROUGH for Mika and Rin.](https://mintcdn.com/launchdarkly/9mdC6T6nS8-uzXsc/images/tutorials/build-a-beautiful-camera/03-sparkle-released.png?fit=max\&auto=format\&n=9mdC6T6nS8-uzXsc\&q=85\&s=fb8cda6c97d14b8c48b032fbfcf5f054)

*Diane receives sparkle through her individual target. Sam still receives classic stickers through the free-tier rule.*

The [SDK listener documentation](https://launchdarkly.com/docs/sdk/features/flag-changes.md#python) describes configuration notifications and context-specific value listeners. Here we use a configuration listener so one callback can refresh every demo persona. Updates travel asynchronously through both connections. This is a live update, not a guarantee of zero delay.

## Share the photo and sticker placements

First, connect each browser to the booth. The client creates its connection with `const socket = io()` and joins on every connection, including reconnections:

```javascript theme={null}
socket.on("connect", () => {
  conn.classList.replace("offline", "online");
  join();
});
```

`join()` sends the selected persona. The server's `handle_join()` records the Socket.IO session ID and responds to that browser with a `booth_state` snapshot containing the photo, stickers, gallery, and current evaluations. This matters because a browser that was disconnected during a flag change must get current state when it returns.

The camera stays local until someone takes a snapshot. In the camera button handler, request a front-facing video stream without audio:

```javascript theme={null}
cameraStream = await navigator.mediaDevices.getUserMedia({
  video: { facingMode: "user", width: { ideal: 1280 } },
  audio: false,
});
cameraVideo.srcObject = cameraStream;
setCameraUi(true);
```

Select **camera** to open the preview before capturing a frame:

![The camera preview displays Chromium's green test pattern, with snap and cancel controls available below the photo frame.](https://mintcdn.com/launchdarkly/9mdC6T6nS8-uzXsc/images/tutorials/build-a-beautiful-camera/02-camera-preview.png?fit=max\&auto=format\&n=9mdC6T6nS8-uzXsc\&q=85\&s=bfa9d883a0e7bd012284c6352a38715c)

*The preview is local to this browser. Select **snap!** to share a still photo, or **cancel** to stop the camera.*

When the visitor selects **snap!**, the app draws a mirrored frame onto an 800-by-600 canvas, encodes a JPEG, emits `set_photo`, and stops the camera tracks. The server validates the data URL, replaces the shared photo, clears the previous stickers, and broadcasts `photo_updated`. Everyone in this demo shares one booth, which means a new photo replaces the backdrop for all connected visitors. Live camera video is not broadcast.

Sticker placement uses the same event-driven pattern. The client converts a click to percentage coordinates so different screen sizes can show the sticker in the same relative position:

```javascript theme={null}
canvas.addEventListener("click", (ev) => {
  const rect = canvas.getBoundingClientRect();
  const x = ((ev.clientX - rect.left) / rect.width) * 100;
  const y = ((ev.clientY - rect.top) / rect.height) * 100;
  socket.emit("place_sticker", { emoji: selectedEmoji, x, y });
});
```

The server checks the persona and emoji, evaluates access to gated packs, clamps the coordinates, and appends the accepted sticker to shared state. It then emits `sticker_added` to everyone. Each browser calls `addSticker()` to display the server's accepted result, including the sparkle or spooky effect.

Hiding a palette is useful feedback, but the server must enforce the flag too. This excerpt from `handle_place_sticker()` performs that check before saving or broadcasting a sticker:

```python theme={null}
is_sparkle = emoji in SPARKLE_PACK
is_spooky = emoji in SPOOKY_PACK
if is_sparkle or is_spooky:
    evaluation = evaluate(persona)
    blocked = ("sparkle engine" if is_sparkle and not evaluation["sparkle"]
               else "spooky pack" if is_spooky and not evaluation["spooky"]
               else None)
    if blocked:
        socketio.emit("denied", {
            "message": f"the {blocked} isn't enabled for {PERSONAS[persona]['name']} (◡‿◡ ) try a classic sticker!",
        }, to=request.sid)
        return
```

A stale browser can still send a placement event after its palette should have locked. Re-evaluating on the server checks that action against the SDK's current flag data. The persona selector is for demonstration, however: a production app must derive identity and plan from an authenticated session rather than let visitors choose another person's identity.

The **save** button composites the photo and current stickers into a JPEG. The server writes that image to `gallery/` and broadcasts `gallery_added`, letting the browsers show the new thumbnail.

After saving, check that your decorated photo appears in the gallery:

![A decorated camera snapshot remains in the booth and a matching thumbnail appears in the gallery below the sticker palettes.](https://mintcdn.com/launchdarkly/dEUBvCcqy3mkDuUc/images/tutorials/build-a-beautiful-camera/06-saved-gallery.png?fit=max\&auto=format\&n=dEUBvCcqy3mkDuUc\&q=85\&s=34c3a18548d81f8921a04b1b52cc9ab9)

*Select a gallery thumbnail to open the saved image. The other connected browser receives the same gallery entry.*

## Test the release with two browsers

Start the application from your activated virtual environment:

```bash theme={null}
python app.py
```

Open [the local photo booth](http://localhost:5055) in two browser windows or separate browser profiles. Then work through the release:

1. Select **Diane** in one window and **Sam** in the other.
2. Take a photo with **camera** and **snap!**, or keep the pastel backdrop.
3. Place a classic sticker and confirm it appears in both windows.
4. Turn on `sparkleStickerEngine` in your LaunchDarkly environment and save the change.
5. Confirm Diane's sparkle palette unlocks while Sam's remains locked.
6. Place a sparkle sticker as Diane and confirm both windows display it.
7. Switch Sam's window to **Mika** and confirm the sparkle and spooky packs are available.
8. Turn off `sparkleStickerEngine` and save the change.
9. Confirm both windows lock sparkle placements while keeping the photo and existing stickers.
10. Place another classic sticker and save the decorated photo to the gallery.
11. Refresh one window and confirm it receives the current photo, stickers, gallery, and flag decisions.

Sam can see a sparkle sticker placed by Diane even though Sam cannot place one. The flag controls the ability to add that pack's stickers. It does not hide collaborative content contributed by someone else.

Compare Sam's window with Diane's released state:

![Sam selected in the photo booth with his sparkle palette locked, while Diane's sparkle stickers remain visible on the shared photo and her control-room row still shows sparkle access.](https://mintcdn.com/launchdarkly/9mdC6T6nS8-uzXsc/images/tutorials/build-a-beautiful-camera/04-sam-targeting.png?fit=max\&auto=format\&n=9mdC6T6nS8-uzXsc\&q=85\&s=ed5f0eece1e76402cf2754359f7574ac)

*Sam sees the shared artwork, but `RULE_MATCH` keeps his own sparkle palette locked.*

Turning the flag off acts as a kill switch for **new sparkle placements**. It does not remove existing sparkle effects or stop all sticker rendering. A rollback designed to stop a faulty animation entirely would also need to disable effects on existing stickers.

After rollback, look for locked sparkle controls and the preserved artwork:

![Diane's sparkle palette is locked after rollback, every artist's evaluation reason is OFF, and the previously placed sparkle stickers remain on the same photo.](https://mintcdn.com/launchdarkly/dEUBvCcqy3mkDuUc/images/tutorials/build-a-beautiful-camera/05-sparkle-rollback.png?fit=max\&auto=format\&n=dEUBvCcqy3mkDuUc\&q=85\&s=0090fc7c829b1a1ff3885daebfa93eb9)

*The flag has turned off for every artist. Existing stickers stay on the photo, and classic stickers remain available.*

## Add an optional emergency trigger

The toggle in the LaunchDarkly UI is enough to demonstrate rollback. The sample also includes an **emergency de-sparkle** button that posts to a configured LaunchDarkly trigger. If your account supports a trigger that turns flag targeting off, create one for `sparkleStickerEngine` in the same environment, then add its URL to `.env`:

```dotenv theme={null}
LD_TRIGGER_URL=your-trigger-url
```

You can create that trigger in the UI, or without it. In the UI, open the environment's **three-dot** overflow menu, select **Configuration in environment**, then click **+ Add trigger** in the "Triggers" section. Choose **Generic trigger** as the trigger type and an action that turns targeting off. To learn more, read [Creating flag triggers](https://launchdarkly.com/docs/home/releases/triggers-create.md).

The [Create a flag trigger](https://launchdarkly.com/docs/api/flag-triggers/create-flag-trigger.md) API takes an API access token (`api-...`), not the server-side SDK key:

```bash theme={null}
curl -X POST \
  "https://app.launchdarkly.com/api/v2/flags/<project-key>/sparkleStickerEngine/triggers/<environment-key>" \
  -H "Authorization: $LD_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "integrationKey": "generic-trigger",
    "instructions": [{ "kind": "turnFlagOff" }],
    "comment": "Emergency de-sparkle: turn sparkleStickerEngine targeting off"
  }'
```

Copy `triggerURL` from the `201` response into `LD_TRIGGER_URL`. LaunchDarkly returns that URL only on create.

Restart the Python server to load the new variable. The button calls `/api/panic`. That server route sends the POST request to LaunchDarkly. The normal SDK listener and Socket.IO path then updates the browsers. Keep the trigger URL on the server because anyone who possesses it may be able to invoke its action. Read the [LaunchDarkly trigger documentation](https://launchdarkly.com/docs/home/releases/triggers) for current availability and setup.

The sample panic route has no authentication. Protect this administrative action before exposing it beyond a controlled demo.

## Troubleshoot the live updates

Use these checks to narrow down a setup issue:

| Symptom | Check |
| - | - |
| The server exits during startup. | Verify the server-side SDK key and network access. |
| Everyone receives classic stickers. | Check the flag key, environment, targeting toggle, and evaluation reasons. |
| Diane does not receive the individual target. | Check context kind `artist` and key `diane-artist`, including capitalization. |
| The seasonal pack stays locked for Mika. | Check `spookyStickerPack`, its premium-tier rule, and the segment's `artist.plan` condition. |
| Toggling a flag does not update the page. | Check the browser's Socket.IO connection, listener registration in `main()`, and the project and environment of the changed flag. |
| The camera is unavailable. | Check browser permission and use `localhost` or HTTPS. |
| The gallery disappears after a restart or deployment. | Check whether the host uses ephemeral storage. Saved images require persistent storage to survive it. |

## Keep building your photo booth

You now have a working release exercise: deploy a sticker feature, expose it to selected artists, propagate updated decisions to open browsers, and disable new placements while visitors keep decorating.

For your next iteration, add private booth rooms so separate groups can decorate their own photos. The current app keeps one shared booth in Python memory and saves gallery images on local disk. Running multiple server processes requires shared application state and coordinated Socket.IO broadcasts. The development server configuration in this sample is for the tutorial.

You can also explore engagement metrics. The app already calls `track("sticker-placed", build_context(persona))` for accepted placements. Configure a metric and experiment separately to investigate whether access to the sparkle pack changes behavior. Tracking an event alone does not establish an experiment or a causal result.

Try a seasonal pack, a different camera frame, or an artist-only beta. The same pattern applies: evaluate the feature on the server, notify connected browsers when decisions change, and validate gated actions when they arrive.
