How to A/B test prices in Flask

Price testing in Flask, step by step: send the visitor cookie with every response, charge the tested price in Stripe Checkout and verify revenue by webhook.

Short answer

Install leverprice and create one client at import time, outside create_app(). Where the price renders, call get_price(request), wrap the template in make_response() and add every quote.set_cookie value with apply_cookies(). At checkout, price again and pass quote.price and the whole quote.metadata to Stripe Checkout. Then connect Stripe's webhook to Leverprice for verified revenue.

  • render_template() returns a string with no headers, so build a response with make_response() before adding the Set-Cookie values.
  • Assigning response.headers['Set-Cookie'] replaces every Set-Cookie already on the response; apply_cookies() and headers.add() append.
  • Flask-Caching stores whatever the view returns, Set-Cookie included, so a cached pricing route turns every visitor into the first one.
  • flask run loads .env through python-dotenv, gunicorn does not: a key that works locally can be missing in production.

Flask's render_template() returns a string, and a string has no headers. A price test needs exactly one header on the way out: the Set-Cookie that pins each visitor to their price. Skip it and the price can change on every reload, and the checkout can charge a different amount than the page showed.

Everything below runs on Flask 3.1, stripe-python 17 and the leverprice package for Python 3.9+.

How does price testing work in a Flask app?

Your server picks the price. get_price() reads the visitor's __pp cookie and user agent from Flask's request, chooses their price from a signed config held in memory, checks it against bounds you set in code and returns a quote: price in minor units (2900 is $29.00), currency, a signed metadata dict and a list of Set-Cookie values. The browser runs no Leverprice JavaScript.

Pass Flask's request proxy as it is. The SDK unwraps it to the real request object, so several get_price() calls in one request share one visitor, and the last quote's cookie carries every assignment. The checkout route asks again and gets the same answer, because the signed cookie travels with the browser. For why this belongs on the server rather than in a script tag, see server-side price testing.

How do I install and configure the SDK in Flask?

Terminal
pip install leverprice stripe
.env
LEVERPRICE_SECRET_KEY=pp_sk_test_...
STRIPE_SECRET_KEY=sk_test_...

Create both clients in a module of their own, at import time:

pricing.py
import os

from leverprice import Leverprice
from stripe import StripeClient

leverprice = Leverprice(
    secret_key=os.environ.get("LEVERPRICE_SECRET_KEY"),
    products={
        # Guardrails in minor units: a price outside them is never returned.
        "pro": {"currency": "usd", "fallback_price": 2900, "min_price": 1900, "max_price": 4900},
    },
)
stripe_client = StripeClient(os.environ["STRIPE_SECRET_KEY"])

Keep the client out of create_app(). Tests and CLI commands can call the factory many times in one process, and every extra client fetches and verifies its own config. One module-level instance is thread-safe and serves the whole process.

fallback_price is what visitors pay when Leverprice cannot answer: no key, LEVERPRICE_DISABLED=1, or no signed config within 500 ms. get_price() never raises for those reasons, only for a product key missing from products. A config that tries to charge outside min_price and max_price gets your fallback instead. The SDK docs list every other option.

How do I show the tested price in a Flask view?

Build a real response object, then add the cookies to it:

app.py
from flask import Flask, make_response, render_template, request, session
from leverprice import apply_cookies

from pricing import leverprice

app = Flask(__name__)


@app.get("/pricing")
def pricing():
    quote = leverprice.get_price("pro", request, user_id=session.get("user_id"))
    response = make_response(render_template("pricing.html", quote=quote))
    return apply_cookies(response, quote)
templates/pricing.html
<p class="price">{{ "%.2f"|format(quote.price / 100) }} {{ quote.currency|upper }}</p>
<form method="post" action="{{ url_for('checkout') }}">
  <button type="submit">Buy Pro</button>
</form>

apply_cookies() calls response.headers.add() for each value. Don't assign the header instead: Werkzeug's Headers.__setitem__ is set(), which removes all existing tuples for that name before adding one, so a second Set-Cookie silently replaces the first.

user_id puts a signed-in customer in the same bucket on every device; only an HMAC of it leaves your server. Use the same value in every route that prices the product.

If a view returns a template from several branches, register the cookies once with after_this_request instead:

app.py
from flask import after_this_request


@app.get("/plans")
def plans():
    quote = leverprice.get_price("pro", request, user_id=session.get("user_id"))

    @after_this_request
    def add_price_cookie(response):
        return apply_cookies(response, quote)

    return render_template("plans.html", quote=quote)

Why must the pricing route stay out of Flask-Caching?

Because @cache.cached() stores whatever the view returned and replays it without running the view. Flask-Caching saves the return value as is, and with make_response() that value is a full response with its Set-Cookie header. Every later visitor would receive the first visitor's price and the first visitor's signed cookie, so the whole audience collapses into one visitor and the test stops learning.

Leave pricing routes uncached in Flask-Caching and in any CDN in front of the app. If the page is expensive to render, cache the parts around the price, or load the price from a small uncached JSON route and cache the rest of the HTML.

How do I charge the same price with Stripe Checkout?

Price the checkout on the server again; ignore any amount the form sends. Stripe's price_data takes the amount inline, so there is no Stripe Price object per tested price:

app.py
from flask import redirect, url_for

from pricing import stripe_client


@app.post("/checkout")
def checkout():
    quote = leverprice.get_price("pro", request, user_id=session.get("user_id"))
    checkout_session = stripe_client.v1.checkout.sessions.create({
        "mode": "payment",
        "line_items": [{
            "quantity": 1,
            "price_data": {
                "currency": quote.currency,
                "unit_amount": quote.price,
                "product_data": {"name": "Pro"},
            },
        }],
        "metadata": quote.metadata,  # signed attribution: pass it whole
        "payment_intent_data": {"metadata": quote.metadata},
        "success_url": url_for("thanks", _external=True),
        "cancel_url": url_for("pricing", _external=True),
    })
    return apply_cookies(redirect(checkout_session.url, code=303), quote)


@app.get("/thanks")
def thanks():
    return render_template("thanks.html")

Name the Stripe object checkout_session so it doesn't shadow Flask's session. quote.metadata holds pp_exp, pp_var, pp_vid and pp_sig, signed together, so it goes into Stripe whole. Flask has no CSRF protection of its own; if you use Flask-WTF's CSRFProtect, the checkout form needs its hidden csrf_token field like any other form.

Selling a subscription? Set "mode": "subscription", add "recurring": {"interval": "month"} to price_data, and move the metadata copy from payment_intent_data to subscription_data; the Checkout Session API takes payment_intent_data only in payment mode. Leverprice's Stripe verification covers one-time payments, so report a subscription's first payment with track_purchase() from your own webhook route; it shows as unverified, and renewals never count toward a test.

Other providers follow the same two rules. Polar accepts an ad-hoc price per checkout, and Leverprice verifies one-time orders and a subscription's first payment there. Lemon Squeezy takes custom_price in cents until it stops processing payments on March 31, 2027. Dodo Payments takes a custom amount only on pay-what-you-want products, and its one-time payments are verified.

Can I show a different price per country?

Yes. Turn on regional prices in the dashboard and each country gets a price you set by hand or one derived from its tier (5 tiers by World Bank price level), in its own currency. Example: ₹999 for a visitor from India, $29 for one from the US. Your client decides where the country comes from and which prices may pass:

pricing.py
leverprice = Leverprice(
    secret_key=os.environ.get("LEVERPRICE_SECRET_KEY"),
    country_header="cf-ipcountry",  # set by Cloudflare; on Vercel: x-vercel-ip-country
    products={
        "pro": {
            "currency": "usd", "fallback_price": 2900, "min_price": 1900, "max_price": 4900,
            "regional": {  # currencies you accept, each with hard bounds
                "usd": {"min_price": 800, "max_price": 4900},
                "eur": {"min_price": 1100, "max_price": 6000},
                "inr": {"min_price": 48000, "max_price": 230000},
            },
        },
    },
)

country_header has no default because a header visitors can send themselves would let them choose their price. That also means every request must reach Flask through the CDN that sets it: if your origin answers direct traffic, anyone can send CF-IPCountry by hand. If you look countries up yourself, pass country= to get_price(). Unlisted currencies, prices outside their bounds, bots and unknown countries all get the standard price.

The checkout above passes quote.currency already, so Stripe charges in the visitor's currency; check that your account supports each one. The template's / 100 fits two-decimal currencies only. JPY has no minor unit, per Stripe's zero-decimal currencies, so format by currency.

How does Leverprice verify revenue from Stripe?

With Stripe's own signed webhooks, sent straight to Leverprice. In the dashboard, open Payments and connect Stripe to get an endpoint URL. Add it in Stripe as a webhook endpoint for checkout.session.completed, checkout.session.async_payment_succeeded and charge.refunded, then paste that endpoint's signing secret back into Leverprice.

Never paste an API key: a signing secret can confirm events but cannot move money. The Stripe integration page walks through each step.

Revenue reaches Leverprice from Stripe directly, signed with the endpoint's secret.

Write your own route only if you cannot add an endpoint or you sell subscriptions. Revenue reported from it is labeled unverified and never overrides a verified purchase:

webhooks.py
import os

import stripe
from flask import Blueprint, request

from pricing import leverprice, stripe_client

bp = Blueprint("webhooks", __name__)
PAID = {"checkout.session.completed", "checkout.session.async_payment_succeeded"}


@bp.post("/webhooks/stripe")
def stripe_webhook():
    try:
        event = stripe_client.construct_event(
            request.get_data(), request.headers.get("Stripe-Signature"), os.environ["STRIPE_WEBHOOK_SECRET"]
        )
    except (ValueError, stripe.SignatureVerificationError):
        return "", 400
    if event.type in PAID and event.data.object.payment_status == "paid":
        session = event.data.object
        tax = session.total_details.amount_tax if session.total_details else 0
        leverprice.track_purchase(
            provider="stripe",
            order_id=session.payment_intent or session.invoice,  # invoice: subscription mode
            amount=session.amount_total - tax,
            currency=session.currency,
            metadata=session.metadata.to_dict(),
            timestamp=event.created,
        )
    return "", 200

Verify the raw body from request.get_data() before reading any JSON. With Flask-WTF, put @csrf.exempt under the route decorator, as its CSRF docs show, because Stripe cannot send a token. And keep .to_dict(): since stripe-python 15.0.0, Stripe objects are not dicts, and the SDK cannot read attribution from one.

How do I test it locally?

Start the dev server with flask --app app run --debug and walk the flow with test keys:

  1. Connect a test-mode Stripe endpoint in Leverprice; test data never mixes with live data.
  2. Load the pricing page, note the price, reload. It must not change.
  3. Open a private window: that is a new visitor and may see another price.
  4. Click Buy and compare Stripe's amount with the page. Pay with a card from Stripe's testing docs, such as 4242 4242 4242 4242.
  5. Remove LEVERPRICE_SECRET_KEY and restart. The page must show your fallback price, and quote.reason must be "disabled".

The dev server prints http://127.0.0.1:5000, and the cookie is Secure by default. MDN documents the HTTPS exception for localhost only, so browse to localhost, and set cookie_secure=False in development if you test from a phone over the LAN. Requests from curl or python-requests get the standard price with reason "bot".

What changes when I deploy Flask?

Production servers don't read .env. Flask's CLI docs say dotenv files are "only loaded by the flask command or calling run()", so set LEVERPRICE_SECRET_KEY, STRIPE_SECRET_KEY and the live keys in the service's real environment. Connect the live-mode Stripe endpoint in Leverprice too; it has its own signing secret.

Behind a reverse proxy, url_for(..., _external=True) builds http URLs unless Flask trusts the forwarded headers. Wrap the app as the proxy guide shows, with the number of proxies you actually have:

app.py
from werkzeug.middleware.proxy_fix import ProxyFix

app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1, x_host=1, x_prefix=1)

Under gunicorn, the client handles forking: each worker starts with fresh threads and an empty event queue. With --preload, call leverprice.preload() at the end of pricing.py and every worker starts with the verified config. LEVERPRICE_DISABLED=1 plus a restart switches every visitor to the fallback price without a deploy.

What breaks most often?

SymptomLikely causeFix
Price changes on reloadThe view returns a string, so no cookie is sentmake_response() plus apply_cookies()
One of two cookies is lostresponse.headers["Set-Cookie"] = ... replaced the otherUse apply_cookies() or headers.add()
Every visitor sees the same price@cache.cached() or a CDN caches the routeRemove caching from pricing routes
reason is "disabled" only in production.env was loaded by flask run, not by gunicornSet the keys in the service environment
Stripe redirects to an http success URLNo ProxyFix behind the proxyWrap app.wsgi_app as shown above
Purchases from your own route lack attributionA StripeObject passed as metadataPass session.metadata.to_dict()

Frequently asked questions

Can I use async views?

Yes, but the sync API is simpler in Flask. Per the async docs, Flask runs each async view in its own event loop on a worker thread, so a sync get_price() only blocks that request. For an app that is async end to end, the FastAPI guide shows the async client.

How do I price monthly and yearly plans on one page?

Define two products, call get_price() once per product with the same request, and apply both quotes' cookies. The quotes share one visitor, and the last cookie carries every assignment.

Does this work with Flask-Login?

Yes. Pass current_user.get_id() as user_id when current_user.is_authenticated, or None otherwise. Only its hash leaves your server.

What happens when the test ends?

Lock in the winner in the dashboard and it is live for every visitor in about a second. The Flask code stays as it is, so there is nothing to deploy.