Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Flask: Counter

from flask import Flask
app = Flask(__name__)

counter = 1

@app.get("/")
def main_page():
    global counter
    counter += 1
    return str(counter)

Access the page from several browsers. There is one single counter that lives as long as the process lives.

import counter
import pytest

@pytest.fixture()
def web():
    return counter.app.test_client()


def test_app(web):
    rv = web.get('/')
    assert rv.status == '200 OK'
    assert rv.data.decode('utf-8') == '2'

    rv = web.get('/')
    assert rv.status == '200 OK'
    assert rv.data.decode('utf-8') == '3'

    rv = web.get('/')
    assert rv.status == '200 OK'
    assert rv.data.decode('utf-8') == '4'

def test_app_separate(web):
    rv = web.get('/')
    assert rv.status == '200 OK'
    assert rv.data.decode('utf-8') == '5'
    # The counter is global!