Skip to content

Commit

Permalink
FIx timezone
Browse files Browse the repository at this point in the history
  • Loading branch information
SkyEye-FAST committed Jan 27, 2024
1 parent e375221 commit f709906
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 6 deletions.
Binary file added GeoLite2-City.mmdb
Binary file not shown.
27 changes: 22 additions & 5 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,16 @@
from os import getenv
from datetime import date

from flask import Flask, g, render_template, request, send_from_directory
from flask import Flask, session, g, render_template, request, send_from_directory
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField

from flask_babel import Babel, lazy_gettext, format_date
from babel.dates import get_timezone_name
import geoip2.database
import geoip2.errors

from base import data, is_valid_key, get_translation
from base import P, data, is_valid_key, get_translation

flask_app = Flask(__name__)
flask_app.config["SECRET_KEY"] = getenv("SECRET_KEY", "dev")
Expand All @@ -27,6 +29,18 @@ def get_locale():

babel = Babel(flask_app, locale_selector=get_locale)

@flask_app.before_request
def determine_timezone():
"""根据IP获取时间"""
ip = request.remote_addr
try:
with geoip2.database.Reader(P / "GeoLite2-City.mmdb") as reader:
response = reader.city(ip)
timezone = response.location.time_zone
session["timezone"] = timezone
except geoip2.errors.AddressNotFoundError:
pass


class QueryForm(FlaskForm):
"""查询表单"""
Expand All @@ -38,8 +52,11 @@ class QueryForm(FlaskForm):
@flask_app.route("/", methods=["GET", "POST"])
def index():
"""主页面"""
timezone = request.headers.get("Time-Zone")

if 'timezone' in session:
timezone = session['timezone']
timezone_str = get_timezone_name(timezone, locale=get_locale())
else:
timezone_str = "UTC"
form = QueryForm()

query_str = form.source_string.data
Expand Down Expand Up @@ -67,7 +84,7 @@ def index():
translation=selected_translation,
date_str=date.today(),
date_str_t=format_date(date.today(), "long"),
timezone_str=get_timezone_name(timezone, locale=get_locale()),
timezone_str=timezone_str,
)


Expand Down
5 changes: 4 additions & 1 deletion base.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,11 @@
import json
from pathlib import Path

# 当前绝对路径
P = Path(__file__).resolve().parent

# 语言文件文件夹
LANG_DIR = Path(__file__).resolve().parent / "lang"
LANG_DIR = P / "lang"

# 是否忽略补充字符串
IGNORE_SUPPLEMENTS = True
Expand Down

0 comments on commit f709906

Please sign in to comment.