08. Jupyter Notebook

ehemalige Veranstaltungen ia3.netz + ia3.data sowie ia4.Netz im Studiengang Interaktive Medien

(c) 2020 Hochschule Augsburg - Fakultät für Informatik - Prof.Dr.Nik Klever

In [13]:
%%writefile Aufgabe7/flaskr.py
# all the imports
import os
import sqlite3
from flask import Flask, request, session, g, redirect, url_for, abort, \
     render_template, flash

app = Flask(__name__) # create the application instance :)
app.config.from_object(__name__) # load config from this file , flaskr.py

# Load default config and override config from an environment variable
app.config.update(dict(
    DATABASE=os.path.join(app.root_path, 'flaskr.csv'),
    SECRET_KEY='development key',
    USERNAME='admin',
    PASSWORD='default'
))
app.config.from_envvar('FLASKR_SETTINGS', silent=True)

def init_csv():
    with open(app.config['DATABASE'],"r") as f:
        alllines = f.read()
        app.entries = [line.split(';') for line in alllines.split("\n")[1:-1]]

@app.route('/')
def show_entries():
    entries = []
    for e in app.entries:
        entries.append(dict(title=e[1],text=e[2]))
    return render_template('show_entries.html', entries=entries)

@app.route('/add', methods=['POST'])
def add_entry():
    if not session.get('logged_in'):
        abort(401)
    #len(app.entries)+1,request.form['title'], request.form['text']
    entry = [len(app.entries)+1,request.form['title'], request.form['text']]
    app.entries.append(entry)
    with open(app.config['DATABASE'],"a") as f:
        f.write(str(entry[0])+";"+";".join(entry[1:]))
        f.write("\n")
        #f.write("{0};{1};{2}\n".format(*entry))
    flash('New entry was successfully posted')
    return redirect(url_for('show_entries'))

@app.route('/login', methods=['GET', 'POST'])
def login():
    error = None
    if request.method == 'POST':
        if request.form['username'] != app.config['USERNAME']:
            error = 'Invalid username'
        elif request.form['password'] != app.config['PASSWORD']:
            error = 'Invalid password'
        else:
            session['logged_in'] = True
            flash('You were logged in')
            return redirect(url_for('show_entries'))
    return render_template('login.html', error=error)

@app.route('/logout')
def logout():
    session.pop('logged_in', None)
    flash('You were logged out')
    return redirect(url_for('show_entries'))

if __name__ == "__main__":
    init_csv()
    app.run()
Overwriting Aufgabe7/flaskr.py
In [3]:
%%writefile Aufgabe7/templates/layout.html
<!doctype html>
<title>Flaskr</title>
<link rel=stylesheet type=text/css href="{{ url_for('static', filename='style.css') }}">
<div class=page>
  <h1>Flaskr</h1>
  <div class=metanav>
  {% if not session.logged_in %}
    <a href="{{ url_for('login') }}">log in</a>
  {% else %}
    <a href="{{ url_for('logout') }}">log out</a>
  {% endif %}
  </div>
  {% for message in get_flashed_messages() %}
    <div class=flash>{{ message }}</div>
  {% endfor %}
  {% block body %}{% endblock %}
</div>
Writing Aufgabe7/templates/layout.html
In [4]:
%%writefile Aufgabe7/templates/show_entries.html
{% extends "layout.html" %}
{% block body %}
  {% if session.logged_in %}
    <form action="{{ url_for('add_entry') }}" method=post class=add-entry>
      <dl>
        <dt>Title:
        <dd><input type=text size=30 name=title>
        <dt>Text:
        <dd><textarea name=text rows=5 cols=40></textarea>
        <dd><input type=submit value=Share>
      </dl>
    </form>
  {% endif %}
  <ul class=entries>
  {% for entry in entries %}
    <li><h2>{{ entry.title }}</h2>{{ entry.text|safe }}
  {% else %}
    <li><em>Unbelievable.  No entries here so far</em>
  {% endfor %}
  </ul>
{% endblock %}
Writing Aufgabe7/templates/show_entries.html
In [5]:
%%writefile Aufgabe7/templates/login.html
{% extends "layout.html" %}
{% block body %}
  <h2>Login</h2>
  {% if error %}<p class=error><strong>Error:</strong> {{ error }}{% endif %}
  <form action="{{ url_for('login') }}" method=post>
    <dl>
      <dt>Username:
      <dd><input type=text name=username>
      <dt>Password:
      <dd><input type=password name=password>
      <dd><input type=submit value=Login>
    </dl>
  </form>
{% endblock %}
Writing Aufgabe7/templates/login.html
In [6]:
%%writefile Aufgabe7/static/style.css
body            { font-family: sans-serif; background: #eee; }
a, h1, h2       { color: #377ba8; }
h1, h2          { font-family: 'Georgia', serif; margin: 0; }
h1              { border-bottom: 2px solid #eee; }
h2              { font-size: 1.2em; }

.page           { margin: 2em auto; width: 35em; border: 5px solid #ccc;
                  padding: 0.8em; background: white; }
.entries        { list-style: none; margin: 0; padding: 0; }
.entries li     { margin: 0.8em 1.2em; }
.entries li h2  { margin-left: -1em; }
.add-entry      { font-size: 0.9em; border-bottom: 1px solid #ccc; }
.add-entry dl   { font-weight: bold; }
.metanav        { text-align: right; font-size: 0.8em; padding: 0.3em;
                  margin-bottom: 1em; background: #fafafa; }
.flash          { background: #cee5F5; padding: 0.5em;
                  border: 1px solid #aacbe2; }
.error          { background: #f0d6d6; padding: 0.5em; }
Writing Aufgabe7/static/style.css
In [9]:
%%writefile Aufgabe7/flaskr.csv
1;Titel;Text
Writing Aufgabe7/flaskr.csv
In [12]:
entry = [1,"Test","Text"]
str(entry[0])+";"+";".join(entry[1:])
Out[12]:
'1;Test;Text'
In [17]:
%%writefile Aufgabe7/flaskr.py
# all the imports
import os
import sqlite3
from flask import Flask, request, session, g, redirect, url_for, abort, \
     render_template, flash

app = Flask(__name__) # create the application instance :)
app.config.from_object(__name__) # load config from this file , flaskr.py

# Load default config and override config from an environment variable
app.config.update(dict(
    DATABASE=os.path.join(app.root_path, 'flaskr.csv'),
    SECRET_KEY='development key',
    USERNAME='admin',
    PASSWORD='default'
))
app.config.from_envvar('FLASKR_SETTINGS', silent=True)

@app.template_filter('crlf')
def crlf_filter(s):
    rs = s.replace("_CRLF_","<br/>")
    return rs

def crlf_encode(s):
    return s.replace("\r\n","_CRLF_")

def init_csv():
    with open(app.config['DATABASE'],"r") as f:
        alllines = f.read()
        app.entries = [line.split(';') for line in alllines.split("\n")[1:-1]]

@app.route('/')
def show_entries():
    entries = []
    for e in app.entries:
        entries.append(dict(title=e[1],text=e[2]))
    return render_template('show_entries.html', entries=entries)

@app.route('/add', methods=['POST'])
def add_entry():
    if not session.get('logged_in'):
        abort(401)
    #len(app.entries)+1,request.form['title'], request.form['text']
    entry = [len(app.entries)+1,request.form['title'], crlf_encode(request.form['text'])]
    app.entries.append(entry)
    with open(app.config['DATABASE'],"a") as f:
        f.write("{0};{1};{2}\n".format(*entry))
    flash('New entry was successfully posted')
    return redirect(url_for('show_entries'))

@app.route('/login', methods=['GET', 'POST'])
def login():
    error = None
    if request.method == 'POST':
        if request.form['username'] != app.config['USERNAME']:
            error = 'Invalid username'
        elif request.form['password'] != app.config['PASSWORD']:
            error = 'Invalid password'
        else:
            session['logged_in'] = True
            flash('You were logged in')
            return redirect(url_for('show_entries'))
    return render_template('login.html', error=error)

@app.route('/logout')
def logout():
    session.pop('logged_in', None)
    flash('You were logged out')
    return redirect(url_for('show_entries'))

if __name__ == "__main__":
    init_csv()
    app.run()
Overwriting Aufgabe7/flaskr.py
In [16]:
%%writefile Aufgabe7/templates/show_entries.html
{% extends "layout.html" %}
{% block body %}
  {% if session.logged_in %}
    <form action="{{ url_for('add_entry') }}" method=post class=add-entry>
      <dl>
        <dt>Title:
        <dd><input type=text size=30 name=title>
        <dt>Text:
        <dd><textarea name=text rows=5 cols=40></textarea>
        <dd><input type=submit value=Share>
      </dl>
    </form>
  {% endif %}
  <ul class=entries>
  {% for entry in entries %}
    <li><h2>{{ entry.title }}</h2>{{ entry.text|crlf|safe }}
  {% else %}
    <li><em>Unbelievable.  No entries here so far</em>
  {% endfor %}
  </ul>
{% endblock %}
Overwriting Aufgabe7/templates/show_entries.html
In [18]:
%%writefile flask_beispiel_5.py
from flask import request, Flask, render_template_string

login_template = """  <h2>Login</h2>
  {% if error %}<p class=error><strong>Error:</strong> {{ error }}{% endif %}
  <form action="{{ url_for('login') }}" method=post>
    <dl>
      <dt>Username:
      <dd><input type=text name=username>
      <dt>Password:
      <dd><input type=password name=password>
      <dd><input type=submit value=Login>
    </dl>
  </form>
"""

helloworld_template = """  <h2>Hello {{user}}</h2>
  {% if error %}<p class=error><strong>Error:</strong> {{ error }}{% endif %}
"""

def valid_login(user,passwd):
    if user.startswith('a'): return True
    else: return False

def log_the_user_in(user):
    return render_template_string(helloworld_template, user=user)


app = Flask(__name__)
app.debug = True

@app.route('/login', methods=['POST', 'GET'])
def login():
    error = None
    if request.method == 'POST':
        if valid_login(request.form['username'],
                       request.form['password']):
            return log_the_user_in(request.form['username'])
        else:
            error = 'Invalid username/password'
    # the code below is executed if the request method
    # was GET or the credentials were invalid
    return render_template_string(login_template, error=error)

if __name__ == "__main__":
    app.run()
Writing flask_beispiel_5.py
In [20]:
%%writefile flask_beispiel_6.py
from flask import request, Flask, render_template_string

login_template = """  <h2>Login</h2>
  {% if error %}<p class=error><strong>Error:</strong> {{ error }}{% endif %}
  <form action="{{ url_for('loginform') }}" method=get>
    <dl>
      <dt>Username:
      <dd><input type=text name=username>
      <dt>Password:
      <dd><input type=password name=password>
      <dd><input type=submit value=Login>
    </dl>
  </form>
"""

helloworld_template = """  <h2>Hello {{user}}</h2>
  {% if error %}<p class=error><strong>Error:</strong> {{ error }}{% endif %}
"""

def valid_login(user,passwd):
    if user.startswith('a'): return True
    else: return False

def log_the_user_in(user):
    return render_template_string(helloworld_template, user=user)


app = Flask(__name__)
app.debug = True

@app.route('/loginform', methods=['GET'])
def loginform():
    if valid_login(request.args['username'],
                   request.args['password']):
        return log_the_user_in(request.args['username'])
    else:
        error = 'Invalid username/password'
    return render_template_string(login_template, error=error)

@app.route('/login', methods=['GET'])
def login():
    error = None
    return render_template_string(login_template, error=error)

if __name__ == "__main__":
    app.run()
Overwriting flask_beispiel_6.py
In [23]:
%%writefile flask_beispiel_7.py
from flask import request, Flask, render_template_string

login_template = """  <h2>Login</h2>
  {% if error %}<p class=error><strong>Error:</strong> {{ error }}{% endif %}
  <form action="{{ url_for('loginform') }}" method=get>
    <dl>
      <dt>Username:
      <dd><input type=text name=username>
      <dt>Password:
      <dd><input type=password name=password>
      <dd><input type=submit value=Login>
    </dl>
  </form>
"""

helloworld_template = """  <h2>Hello {{user}}</h2>
<ul>
{% for i in environ %}
  <li>{{ i }}: {{ environ[i] }}</li>
{% endfor %}
</ul>
  {% if error %}<p class=error><strong>Error:</strong> {{ error }}{% endif %}
"""

def valid_login(user,passwd):
    if user.startswith('a'): return True
    else: return False

def log_the_user_in(user):
    return render_template_string(helloworld_template, user=user, environ=request.environ)


app = Flask(__name__)
app.debug = True

@app.route('/loginform', methods=['GET'])
def loginform():
    if valid_login(request.args['username'],
                   request.args['password']):
        return log_the_user_in(request.args['username'])
    else:
        error = 'Invalid username/password'
    return render_template_string(login_template, error=error)

@app.route('/login', methods=['GET'])
def login():
    error = None
    return render_template_string(login_template, error=error)

if __name__ == "__main__":
    app.run()
Overwriting flask_beispiel_7.py
In [24]:
%%writefile flask_beispiel_8.py
from flask import Flask, session, redirect, url_for, escape, request

app = Flask(__name__)
app.debug = True

@app.route('/')
def index():
    if 'username' in session:
        return 'Logged in as %s' % escape(session['username'])
    return 'You are not logged in'

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        session['username'] = request.form['username']
        return redirect(url_for('index'))
    return '''
        <form action="" method="post">
            <p><input type=text name=username>
            <p><input type=submit value=Login>
        </form>
    '''

@app.route('/logout')
def logout():
    # remove the username from the session if it's there
    session.pop('username', None)
    return redirect(url_for('index'))

# set the secret key.  keep this really secret:
app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'

if __name__ == "__main__":
    app.run()
Writing flask_beispiel_8.py
In [30]:
%%writefile templates/PTFBestellformular.html
<html>
    <head>
        <title>PTF Bestellformular</title>
    </head>
    <body>
        <h1>PTF Bestellformular</h1>
        <form ACTION="/PTFBestellformular" method="GET">
            <h3>Kunde</h3>
            <p>Name <input name="Kunde" size="46"/></p>
            <p>Strasse <input name="Strasse" size="40"/></p>
            <p>Ort <input name="Ort" size="20"> Plz <input name="Plz" size="4"></p>
            <h3>Kreditkarte</h3> 
            <p>Mastercard 
                <input name="Kreditkarte" type="radio" value="Mastercard"/>
               Visacard 
                <input name="Kreditkarte" type="radio" value="Visacard"/>
            </p>
            <p>Nummer 
                <input name="Kreditkartennummer" size="10"/>
               Ablaufdatum 
                <input name="Ablaufdatum" size="4"/>
            </p>
            <h3>PTF Bestellgröße</h3>
            <p>Groß 
                <input name="Groesse" type="radio" value="gross"/>
               Mittel 
                <input name="Groesse" type="radio" value="mittel"/>
               Klein 
                <input name="Groesse" type="radio" value="klein"/>
            </p>
            <h3>Zustellung</h3>
            <p>Expresszustellung <input name="Express" type="checkbox"/></p>
            <p><input type="submit" value="Bestellung abschicken"/></p>
        </form>
        <p>Vielen Dank für ihre Bestellung!</p>
    </body>
</html>
Writing templates/PTFBestellformular.html
In [31]:
%%writefile flask_beispiel_9.py
from flask import Flask, session, redirect, url_for, escape, request, render_template

app = Flask(__name__)
app.debug = True

@app.route('/')
def index():
    return render_template("PTFBestellformular.html")

@app.route('/PTFBestellformular', methods=['GET'])
def login():
    return '''<!doctype html
<html>
    <head>
        <title>PTF Bestellung</title>
    </head>
    <body>
        <h2>PTF Bestellung</h2>
        {}
    </body>
</html>
    '''.format(request.args)

if __name__ == "__main__":
    app.run()
Overwriting flask_beispiel_9.py
In [32]:
%%writefile flask_beispiel_10.py
from flask import Flask, session, redirect, url_for, escape, request, render_template

app = Flask(__name__)
app.debug = True

@app.route('/')
def index():
    return render_template("PTFBestellformular.html")

@app.route('/PTFBestellformular', methods=['GET'])
def login():
    return render_template("PTFBestellung.html",bestellung=request.args)

if __name__ == "__main__":
    app.run()
Writing flask_beispiel_10.py
In [33]:
%%writefile templates/PTFBestellung.html
<!doctype html>
<html>
    <head>
        <title>PTF Bestellung</title>
    </head>
    <body>
        <h2>PTF Bestellung</h2>
        <ul>
        {% for entry in bestellung %}
            <li>{{ entry }}: {{ bestellung[entry] }}</li>
        {% endfor %}
        </ul>
    </body>
</html>
Writing templates/PTFBestellung.html