Files
fioul/webapp.py

59 lines
1.4 KiB
Python

import locale
import os
from bottle import hook, request, route, run, static_file, view
import models
from models import Price
# ----------------------------------------------------------------------
# Web application
@route("/")
@view("search_results")
def results_page():
query = Price.select().order_by(Price.date.desc())
results = list(query)
day_classes = {
0: "monday",
1: "tuesday",
2: "wednesday",
3: "thursday",
4: "friday",
5: "saturday",
6: "sunday",
}
return dict(results=results, day_classes=day_classes)
@route("/static/<filename>")
def serve_static_file(filename):
project_dir = os.path.dirname(__file__)
static_root = os.path.join(project_dir, "static")
return static_file(filename, root=static_root)
@hook("before_request")
def set_locale():
"""Set the locale for all categories to the first lang in Accept-Language
header. Default to fr_FR.UTF-8
"""
accept_language = request.get_header("Accept-Language", "fr-FR")
first_lang = accept_language.split(";")[0].split(",")[0]
lang = first_lang.translate(str.maketrans("-", "_")) + ".UTF-8"
try:
locale.setlocale(locale.LC_ALL, lang)
except locale.Error:
locale.setlocale(locale.LC_ALL, "fr_FR.UTF-8")
@hook("before_request")
def connect_to_db():
models.db.connect()
@hook("after_request")
def close_db_connection():
models.db.close()