Mal ohne JavaScript:
templates/base.html
[codebox=html5 file=Unbenannt.html]<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Find the Unicorn</title>
</head>
<body>
{% if session.get('username') != None %}
<h1>Hello {{session['username']}}, find the Unicorn</h1>
<p>…or <a href="{{url_for('logout')}}">log out</a>.</p>
{% else %}
<h1>Find the Unicorn</h1>
{% endif %}
{% for message in get_flashed_messages() %}
<p>{{message}}</p>
{% endfor %}
{% block body %}{% endblock %}
</body>
</html>[/code]
templates/index.html
[codebox=html5 file=Unbenannt.html]{% extends "base.html" %}
{% block body %}
<p>Money: {{session['money']}}</p>
<form action="" method="POST">
{% for i in range(1, 10) %}
<input type="radio" id="door{{i}}" name="door" value="{{i}}">
{{'<br>'|safe if i % 3 == 0}}
{% endfor %}
<input type="submit" value="Check!">
</form>
{% endblock %}[/code]
templates/login.html
Code: Alles auswählen
{% extends "base.html" %}
{% block body %}
<form action="" method="POST">
<input type="text" id="username" name="username" placeholder="Your name">
<input type="submit" value="OK">
</form>
{% endblock %}
main.py
Code: Alles auswählen
#!/usr/bin/env python
from __future__ import absolute_import, division, print_function
import random
from flask import (
flash, Flask, redirect, render_template, request, session, url_for
)
app = Flask(__name__)
app.secret_key = (
'\rn\x8ex)\xa4\xfa\xdb\xe1\xc9\x9aAd\xfc#\x96\xc9g\x95\xf5\x0b\xc1n)\x16'
)
@app.route('/', methods=['GET', 'POST'])
def index():
if 'username' in session:
if request.method == 'POST':
try:
door = int(request.form['door'])
except KeyError:
pass
else:
if door == random.randint(1, 9):
amount = 5000
message = 'Yeah, found the unicorn!'
else:
amount = -250
message = 'No unicorn :-('
session['money'] += amount
flash(message)
return render_template('index.html')
else:
return redirect(url_for('login'))
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form['username'].strip()
if username:
session['username'] = username
session['money'] = 2500
flash(u'Logged in as {}.'.format(username))
return redirect(url_for('index'))
return render_template('login.html')
@app.route('/logout')
def logout():
session.pop('username', None)
return redirect(url_for('index'))