---
type: "Source File"
title: "from flask import Flask, render_template, request, jsonify, redirect, url_for, Response"
description: "from flask import Flask, render_template, request, jsonify, redirect, url_for, Response import hashlib import time import re import os import requests import db import scorer from quiz_integrity import."
resource: "https://quiz.copecheck.com"
tags: ["copecheck", "quiz", "source-file", "py"]
timestamp: "2026-09-26T08:28:11Z"
site: "quiz"
source_path: "copecheck-quiz/app.py"
---

# from flask import Flask, render_template, request, jsonify, redirect, url_for, Response

Source path: `copecheck-quiz/app.py`  
Index snapshot generated: `2026-11-24T13:27:52Z`  
File modified: `2026-09-26T08:28:11Z`

```py
from flask import Flask, render_template, request, jsonify, redirect, url_for, Response
import hashlib
import time
import re
import os
import requests
import db
import scorer
from quiz_integrity import InvalidSubmission, validated_submission

app = Flask(__name__)



# ── CDN & Cache Headers ──────────────────────────────────────
@app.after_request
def add_cache_headers(response):
    """Set cache headers for Cloudflare CDN."""
    path = request.path
    if path.startswith('/static/'):
        # Static assets: cache aggressively at CDN and browser
        response.headers['Cache-Control'] = 'public, max-age=604800, stale-while-revalidate=86400'
    elif path.startswith('/api/'):
        # API responses: never cache
        response.headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, max-age=0'
    elif path.endswith('.xml'):
        # Sitemaps/feeds: cache 1 hour
        response.headers['Cache-Control'] = 'public, max-age=3600'
    else:
        # HTML pages: short cache, but allow CDN to serve stale during spikes
        response.headers['Cache-Control'] = 'public, max-age=300, stale-while-revalidate=3600, stale-if-error=86400'
    # Vary by encoding so CDN caches gzip and plain separately
    response.headers.setdefault('Vary', 'Accept-Encoding')
    return response

# Simple rate limiting
_rate = {}

def rate_limited(ip, limit=10, window=60):
    now = time.time()
    key = ip
    if key not in _rate:
        _rate[key] = []
    _rate[key] = [t for t in _rate[key] if now - t < window]
    if len(_rate[key]) >= limit:
        return True
    _rate[key].append(now)
    return False

[redacted secret-like line]
    ip = req.headers.get('X-Forwarded-For', req.remote_addr) or '0.0.0.0'
    return hashlib.sha256(ip.encode()).hexdigest()[:16]


def _notify_oracle_error(endpoint, error_type, details=""):
[redacted secret-like line]
    import requests as http_req
[redacted secret-like line]
[redacted secret-like line]
        # Fallback: log it
        print(f"[ORACLE ERROR] {endpoint}: {error_type} - {details}", flush=True)
        return
    try:
[redacted secret-like line]
            "type": "oracle_error",
            "endpoint": endpoint,
            "error_type": error_type,
            "details": details[:500],
            "site": "quiz.copecheck.com",
            "timestamp": __import__('datetime').datetime.utcnow().strftime("%Y-%m-%d %H:%M UTC"),
        }, timeout=5)
    except:
        pass

@app.route('/')
def index():
    stats = db.get_stats()
    return render_template('index.html', stats=stats)

@app.route('/quiz')
def quiz():
    return render_template('quiz.html')

@app.route('/api/submit', methods=['POST'])
def submit():
    try:
        data = validated_submission(request.get_json(silent=True))
    except InvalidSubmission as exc:
        return jsonify({'error': str(exc)}), 400

[redacted secret-like line]
    return jsonify({
        'session_id': sid,
        'cope_score': score,
        'spectrum_figure': slug,
        'spectrum_name': name,
        'spectrum_desc': desc,
        'cope_type': cope_type
    })

@app.route('/api/oracle', methods=['POST'])
def oracle():
    ip = request.headers.get('X-Forwarded-For', request.remote_addr) or ''
    if rate_limited(ip):
        return jsonify({'error': 'Rate limited. Try again in a minute.'}), 429

    data = request.get_json()
    sid = data.get('session_id')
    if not sid:
        return jsonify({'error': 'Missing session_id'}), 400

    result = db.get_session(sid)
    if not result:
        return jsonify({'error': 'Session not found'}), 404

    session_data, answers = result
    # Oracle now works for all sessions regardless of screwed data

    response = scorer.score_oracle(session_data)
    if response:
        db.update_oracle(sid, response)
        return jsonify({'oracle': response})
    return jsonify({'error': 'Oracle is temporarily unavailable. Try again.'}), 503

@app.route('/api/argue', methods=['POST'])
def argue():
    ip = request.headers.get('X-Forwarded-For', request.remote_addr) or ''
    if rate_limited(ip):
        return jsonify({'error': 'Rate limited. Try again in a minute.'}), 429

    data = request.get_json()
    sid = data.get('session_id')
    message = data.get('message', '').strip()
    history = data.get('history', [])

    if not sid or not message:
        return jsonify({'error': 'Missing session_id or message'}), 400

    result = db.get_session(sid)
    if not result:
        return jsonify({'error': 'Session not found'}), 404

    session_data, answers = result
    count = db.increment_argue(sid)

    if count > 5:
        return jsonify({'reply': "The Oracle has heard enough. Your cope levels have been noted. Come back with a fresh quiz if you want another round.", 'final': True})

    reply = scorer.argue_with_oracle(session_data, message, history)
    if reply:
        return jsonify({'reply': reply, 'final': count >= 5})
    _notify_oracle_error('/api/oracle', 'unavailable', 'score_oracle returned None')
    return jsonify({'error': 'Oracle is temporarily unavailable.'}), 503

@app.route('/results/<session_id>')
def results(session_id):
    result = db.get_session(session_id)
    if not result:
        return render_template('index.html', stats=db.get_stats(), error="Session not found"), 404
    session_data, answers = result
    slug, name, desc = db.get_spectrum(session_data['cope_score'] or 0)
    return render_template('results.html', session=session_data, answers=answers,
                           spectrum_slug=slug, spectrum_name=name, spectrum_desc=desc)

@app.route('/leaderboard')
def leaderboard():
    most_coped, most_lucid, type_counts, daily_stats = db.get_leaderboard()
    return render_template('leaderboard.html', most_coped=most_coped, most_lucid=most_lucid,
                           type_counts=type_counts, daily_stats=daily_stats)

@app.route('/about')
def about():
    return render_template('about.html')

@app.route('/feed')
def feed():
    page = request.args.get('page', 1, type=int)
    recent, total = db.get_recent(page)
    pages = (total + 19) // 20
    return render_template('feed.html', recent=recent, page=page, total_pages=pages)




@app.route('/oracle-debug')
def oracle_debug():
    return render_template('oracle_debug.html')

@app.route('/api/oracle-debug', methods=['POST'])
def oracle_debug_api():
[redacted secret-like line]
    if rate_limited(ip):
        return jsonify({'error': 'Rate limited. Try again in a minute.'}), 429
    data = request.get_json()
    message = data.get('message', '').strip()
    history = data.get('history', [])
    if not message:
        return jsonify({'error': 'Missing message'}), 400
    dummy_session = {'cope_score': 50, 'spectrum_name': 'Fence-Sitter'}
    reply = scorer.argue_with_oracle(dummy_session, message, history)
    if reply:
        return jsonify({'reply': reply, 'final': False})
    return jsonify({'error': 'Oracle is temporarily unavailable.'}), 503


# ── Leaderboard submission with content filtering ──
PROFANITY_LIST = {
    'fuck','shit','ass','bitch','dick','cock','cunt','twat','wank',
    'nigger','nigga','faggot','retard','slut','whore','bastard',
    'piss','bollocks','arsehole','asshole','motherfucker','fag'
}
INJECTION_PATTERNS = re.compile(
    r'(drop\s+table|select\s+\*|union\s+select|<script|javascript:|on\w+=)',
    re.IGNORECASE
)


_NAME_CHECK_PROMPT = (
    'Is this display name appropriate for a public gaming leaderboard? Name: "{name}"\n\n'
    'Reply with ONLY "YES" or "NO: reason".\n'
    'ONLY reject names that contain: explicit profanity, racial/ethnic slurs, '
    'sexual terms, direct threats, or obvious hate symbols.\n'
    'Normal words, common names, gaming handles, and playful nicknames are ALL FINE.\n'
    'When in doubt, say YES. Most names are acceptable.'
)

def _parse_llm_verdict(text):
    """Parse YES/NO response from LLM. Returns (ok, reason)."""
    text = text.strip()
    # Strip <think>...</think> tags from MiniMax responses
    import re as _re
    text = _re.sub(r'<think>.*?</think>', '', text, flags=_re.DOTALL).strip()
    if text.upper().startswith('NO'):
        reason = text[3:].strip(' :.-') if len(text) > 2 else 'Name not appropriate'
        return False, reason
    return True, None

def _check_name_gemma(name):
    """Try Gemma 3 12B via Google AI Studio."""
[redacted secret-like line]
[redacted secret-like line]
        return None  # Signal: not available
[redacted secret-like line]
    payload = {
        'contents': [{'parts': [{'text': _NAME_CHECK_PROMPT.format(name=name)}]}],
[redacted secret-like line]
    }
    resp = requests.post(url, json=payload, timeout=5)
    if resp.status_code == 200:
        text = resp.json().get('candidates', [{}])[0].get('content', {}).get('parts', [{}])[0].get('text', '')
        return _parse_llm_verdict(text)
    return None  # Signal: failed

def _check_name_minimax(name):
    """Try MiniMax M2.7 as fallback."""
[redacted secret-like line]
[redacted secret-like line]
        return None
    resp = requests.post(
        'https://api.minimax.io/v1/chat/completions',
[redacted secret-like line]
        json={
            'model': 'minimax-m2.7',
            'messages': [{'role': 'user', 'content': _NAME_CHECK_PROMPT.format(name=name)}],
[redacted secret-like line]
        },
        timeout=10
    )
    if resp.status_code == 200:
        text = resp.json().get('choices', [{}])[0].get('message', {}).get('content', '')
        return _parse_llm_verdict(text)
    return None

def _llm_check_name(name):
    """Check name via Gemma, falling back to MiniMax if unavailable."""
    try:
        result = _check_name_gemma(name)
        if result is not None:
            return result
    except Exception:
        pass
    try:
        result = _check_name_minimax(name)
        if result is not None:
            return result
    except Exception:
        pass
    return True, None  # Both failed — fail open


def _check_display_name(name):
    """Returns (clean_name, error_msg). error_msg is None if valid."""
    if not name or not name.strip():
        return None, "Name is required"
    name = name.strip()
    if len(name) < 2 or len(name) > 20:
        return None, "Name must be 2-20 characters"
    if not re.match(r'^[a-zA-Z0-9 _\-\.]+$', name):
        return None, "Name can only contain letters, numbers, spaces, hyphens, underscores, dots"
    lower = name.lower()
    for word in PROFANITY_LIST:
        if word in lower:
            return None, "Name contains inappropriate language"
    if INJECTION_PATTERNS.search(name):
        return None, "Invalid name"
    return name, None

@app.route('/api/leaderboard-submit', methods=['POST'])
def leaderboard_submit():
    data = request.get_json(silent=True) or {}
    sid = data.get('session_id', '')
    raw_name = data.get('display_name', '')
    clean_name, err = _check_display_name(raw_name)
    if err:
        return jsonify({'error': err}), 400
    # LLM moderation check
    ok, reason = _llm_check_name(clean_name)
    if not ok:
        return jsonify({'error': reason or 'Name not appropriate'}), 400
    result = db.get_session(sid)
    if not result:
        return jsonify({'error': 'Session not found'}), 404
    session_data, _ = result
    if session_data.get('display_name'):
        return jsonify({'error': 'Already submitted'}), 409
    db.submit_to_leaderboard(sid, clean_name)
    return jsonify({'ok': True, 'display_name': clean_name})

@app.route('/sitemap.xml')
def sitemap():
    xml = '<?xml version="1.0" encoding="UTF-8"?>\n'
    xml += '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n'
    for loc in ['', '/quiz', '/leaderboard', '/about', '/feed']:
        xml += f'  <url><loc>https://quiz.copecheck.com{loc}</loc></url>\n'
    xml += '</urlset>'
    return Response(xml, mimetype='application/xml')

@app.route('/robots.txt')
def robots():
    return Response("User-agent: *\nAllow: /\nSitemap: https://quiz.copecheck.com/sitemap.xml\n", mimetype='text/plain')

@app.route('/health')
def health():
    return jsonify({'status': 'ok', 'service': 'copecheck-quiz'})



# --- Newsletter subscribe proxy (beehiiv) ---
@app.route('/api/subscribe', methods=['POST'])
def api_newsletter_subscribe():
    """Proxy newsletter signups to beehiiv to avoid cross-origin blocks."""
    import requests as _req
    data = request.get_json(silent=True) or {}
    email = data.get('email', '').strip()
    if not email or '@' not in email:
        return jsonify({'error': 'Invalid email'}), 400
    try:
        s = _req.Session()
        s.headers.update({'User-Agent': 'Mozilla/5.0'})
        page = s.get('https://copecheck.beehiiv.com', timeout=10)
        vt = ''
[redacted secret-like line]
        if m:
            vt = m.group(1)
        sf = ''
        m2 = re.search(r'name="signup_flow_id"\s+value="([^"]*)"', page.text)
        if m2:
            sf = m2.group(1)
        form = {
            'email': email,
[redacted secret-like line]
            'signup_flow_id': sf,
            'sent_from_orchid': 'true',
            'is_js_enabled': 'true',
            'fallback_path': '/',
        }
        r = s.post('https://copecheck.beehiiv.com/create', data=form, timeout=10, allow_redirects=True)
        if r.status_code < 400:
            return jsonify({'success': True, 'message': 'Subscribed!'})
        return jsonify({'error': 'Subscription failed', 'status': r.status_code}), 500
    except Exception as e:
        return jsonify({'error': str(e)}), 500



# --- Feedback endpoint ---
@app.route('/api/feedback', methods=['POST'])
def api_feedback():
[redacted secret-like line]
    import json as _json, os as _os, threading
    from datetime import datetime as _dt
    data = request.get_json(silent=True) or {}
    text = data.get('text', '').strip()
    if not text or len(text) > 5000:
        return jsonify({'error': 'Invalid feedback'}), 400
    entry = {
        'text': text,
        'email': data.get('email', '').strip()[:200],
        'page': data.get('page', '')[:500],
        'site': 'quiz.copecheck.com',
        'ts': _dt.utcnow().isoformat(),
        'ip': request.remote_addr,
    }
    # Save locally
    fb_dir = _os.path.join(_os.path.dirname(__file__), 'feedback')
    _os.makedirs(fb_dir, exist_ok=True)
    fb_file = _os.path.join(fb_dir, 'feedback.jsonl')
    with open(fb_file, 'a') as f:
        f.write(_json.dumps(entry) + "\n")
[redacted secret-like line]
    def _notify():
        try:
            import requests as _req
[redacted secret-like line]
        except Exception:
            pass
    threading.Thread(target=_notify, daemon=True).start()
    return jsonify({'success': True})

@app.route('/ai-disclosure')
def ai_disclosure():
    return render_template('ai_disclosure.html')

if __name__ == '__main__':
    app.run(debug=True, port=5011)


# ── Trailing-slash canonicalisation (added 2026-09-26, infra audit) ──
# Flask 404s on "/foo/" when the route is declared as "/foo". This installs a
# before_request hook that 301s the slashed form to the canonical slash-less
# one, but only when the slashed form is not itself a real route. Revert by
# deleting these three lines and slash_canonical.py.
from slash_canonical import install_slash_canonicaliser  # noqa: E402
install_slash_canonicaliser(app)  # noqa: E402
```
