การอัพโหลดไฟล์ จำเป็นต้องมีการกำหนดค่า SECRET_KEY ไม่งั้นจะ error ว่า RuntimeError: The session is unavailable because no secret key was set. Set the secret_key on the application to something unique and secret.
# save this as app.py
from flask import Flask
from flask import session
import os
app = Flask(__name__)
app.config.update(SECRET_KEY=os.urandom(24))
app.config.from_object(__name__)
@app.route("/")
def hello():
return "Hello, World!"
if __name__ == "__main__":
with app.test_request_context("/"):
session["key"] = "value"
You used Jinja’s sort filter to sort the results of your students by their names. If you had students with the same name, then you could chain the filters:
{% for student in students|sort(attribute="score", reverse=true)
|sort(attribute="name") %}
{# ... #}
{% endfor %}
Include Macros
Implement a Dark Mode
{# templates/macros.html #}
{% macro light_or_dark_mode(element) %}
{% if request.args.get('mode') == "dark" %}
<a href="{{ request.path }}">Switch to Light Mode</a>
<style>
{{ element }} {
background-color: #212F3C;
color: #FFFFF0;
}
{{ element }} a {
color: #00BFFF !important;
}
</style>
{% else %}
<a href="{{ request.path }}?mode=dark">Switch to Dark Mode</a>
{% endif %}
{% endmacro %}
{# templates/base.html #}
{% import "macros.html" as macros %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>{% block title %}{{ title }}{% endblock title %}</title>
</head>
<body>
<header>
{% include "_navigation.html" %}
</header>
{% block content %}
<h1>Welcome to {{ title }}!</h1>
{% endblock content %}
<footer>
{{ macros.light_or_dark_mode("body") }}
</footer>
</body>
</html>