Templates

base.html template:-

<!doctype html>
 
<html lang="en-gb">
  <head>
    <link rel="icon" type="image/x-icon" href="/static/globe.ico">
      {% block header %}
      {% endblock %}
      <meta charset="utf-8">
    <style>
    fieldset {
      background-color: #eeeeee;
      width: 60% }
    legend {
      background-color: gray;
      color: white;
      padding: 5px 10px; }
    input {
      margin: 5px;  }
    </style>
  </head>
 
  <body>
    <img src="/static/globe.jpg" width="250" align="right">
    {% block content %}
    {% endblock %}
  </body>
</html>

Passing a dictionary into a template

Python

Flask needs to return a template and the name of any dictionaries used.

from flask import make_response, render_template, request
 
    headers = {'title': 'Login Page'}
    result = {'username': username}
    return render_template('output.html', headers=headers, result=result)

output.html

{% extends "base.html" %}
 
{% block header %}
<title>{{ headers['title'] }}</title>
{% endblock %}
 
 
{% block content %}
    <h1>Data Result</h1>
 
    <fieldset>
     <legend>Data returned</legend>
     <table>
       <tr><td>Username</td><td>{{ result['username'] }}</td></tr>
     </table>
    </fieldset>
{% endblock %}

Setting Cookies

See 'status':-

        loginresult = {'username': username, 'known_as': known_as, 'expiry': cookie_expiry}
        response = make_response(render_template(
            'loginoutput.html', loginresult=loginresult, headers=headers)
        )
 
        response.set_cookie('status', 'not_known')
        return response

MySQL connector

Also works with MariaDB

Boolean

Get boolean true/false back, db stores 1 or 0

statement = "SELECT IF(login_status, 'true', 'false') from user_model WHERE user_id = %s;"

session_name = session["username"]
mycursor.execute(statement, (session_name,))
 
python/flask-templates.txt · Last modified: 12/09/2023 13:36 by andrew