Skip to content

Commit

Permalink
add utc tzinfo to utcnow()
Browse files Browse the repository at this point in the history
  • Loading branch information
cdhigh committed Apr 30, 2024
1 parent 28f9a08 commit 25c0fbf
Show file tree
Hide file tree
Showing 9 changed files with 24 additions and 22 deletions.
2 changes: 1 addition & 1 deletion application/base_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,6 @@ def save_delivery_log(user, book, size, status='ok', to=None):

try:
DeliverLog.create(user=name, to=to, size=size, time_str=user.local_time("%Y-%m-%d %H:%M"),
datetime=datetime.datetime.utcnow(), book=book, status=status)
datetime=datetime.datetime.now(datetime.timezone.utc), book=book, status=status)
except Exception as e:
default_log.warning('DeliverLog failed to save: {}'.format(e))
4 changes: 2 additions & 2 deletions application/lib/calibre/web/feeds/news.py
Original file line number Diff line number Diff line change
Expand Up @@ -2172,7 +2172,7 @@ def parse_feeds(self):

added.add(url)
timeItem = LastDelivered.get_or_none((LastDelivered.user==self.user.name) & (LastDelivered.url==url))
delta = (datetime.datetime.utcnow() - timeItem.datetime) if timeItem else None
delta = (datetime.datetime.now(datetime.timezone.utc) - timeItem.datetime) if timeItem else None
#这里oldest_article和其他的recipe不一样,这个参数表示在这个区间内不会重复推送
if ((not timeItem) or (not self.oldest_article) or (self.delivery_reason == 'manual') or
(delta.days * 24 * 3600 + delta.seconds > 24 * 3600 * self.oldest_article)):
Expand All @@ -2183,7 +2183,7 @@ def parse_feeds(self):
if ((self.delivery_reason == 'manual') or (not self.oldest_article)) and timeItem:
timeItem.delete_instance()
elif timeItem:
timeItem.datetime = datetime.datetime.utcnow()
timeItem.datetime = datetime.datetime.now(datetime.timezone.utc)
timeItem.save()
else:
LastDelivered.create(user=self.user.name, url=url)
Expand Down
5 changes: 3 additions & 2 deletions application/static/base.js
Original file line number Diff line number Diff line change
Expand Up @@ -797,9 +797,10 @@ function OpenUploadRecipeDialog() {

//删除一个已经上传的Recipe
function DeleteUploadRecipe(id, title) {
if (!confirm(i18n.areYouSureDelete.format(title))) {
if (!(event.ctrlKey || event.metaKey) && !confirm(i18n.areYouSureDelete.format(title))) {
return;
}

$.post("/recipe/delete", {id: id}, function (data) {
if (data.status == "ok") {
for (var idx = 0; idx < my_uploaded_recipes.length; idx++) {
Expand All @@ -816,7 +817,7 @@ function DeleteUploadRecipe(id, title) {
}
PopulateMySubscribed();
PopulateLibrary('');
alert(i18n.recipeDeleted);
//alert(i18n.recipeDeleted);
} else if (data.status == i18n.loginRequired) {
window.location.href = '/login';
} else {
Expand Down
2 changes: 1 addition & 1 deletion application/view/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ def AdminAccountChangePost(name):
else:
dbItem.expiration_days = expiration
if expiration:
dbItem.expires = datetime.datetime.utcnow() + datetime.timedelta(days=expiration)
dbItem.expires = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(days=expiration)
else:
dbItem.expires = None
if sm_service == 'admin':
Expand Down
2 changes: 1 addition & 1 deletion application/view/adv.py
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ def AdvImportPost():
dbItem.save()
else:
Recipe.create(title=title, url=url, user=user.name, isfulltext=isfulltext, type_='custom',
time=datetime.datetime.utcnow())
time=datetime.datetime.now(datetime.timezone.utc))

return redirect(url_for("bpSubscribe.MySubscription"))
else:
Expand Down
9 changes: 5 additions & 4 deletions application/view/library_offical.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ def SharedLibraryOfficalAjax():
creator = hashlib.md5(creator.encode('utf-8')).hexdigest()

#判断是否存在,如果存在,则更新分类或必要的信息,同时返回成功
now = datetime.datetime.utcnow()
now = datetime.datetime.now(datetime.timezone.utc)
if url: #自定义RSS,以url为准
dbItem = SharedRss.get_or_none(SharedRss.url == url)
else: #上传的recipe,以title为准
Expand Down Expand Up @@ -123,12 +123,13 @@ def SharedLibraryOfficalAjax():

#更新共享库的最新时间信息
def UpdateLastSharedRssTime():
AppInfo.set_value(AppInfo.lastSharedRssTime, str(int(datetime.datetime.utcnow().timestamp())))
now = datetime.datetime.now(datetime.timezone.utc)
AppInfo.set_value(AppInfo.lastSharedRssTime, str(int(now.timestamp())))

#共享库的订阅源信息管理
@bpLibraryOffical.post(LIBRARY_MGR + "<mgrType>")
def SharedLibraryMgrOffical(mgrType):
now = datetime.datetime.utcnow()
now = datetime.datetime.now(datetime.timezone.utc)
form = request.form
#print(mgrType, LIBRARY_GETSRC)
if mgrType == LIBRARY_GETSRC: #获取一个共享recipe的源代码
Expand Down Expand Up @@ -164,7 +165,7 @@ def SharedLibraryMgrOffical(mgrType):
return respDict

#希望能做到“免维护”,在一定数量的失效报告之后,自动删除对应的源,假定前提是人性本善
delta = abs(now - dbItem.last_invalid_report_time.replace(tzinfo=None))
delta = abs(now - dbItem.last_invalid_report_time)
deltaDays = delta.days

if deltaDays > 180: #半年内没有人报告失效则重新计数
Expand Down
10 changes: 5 additions & 5 deletions application/view/login.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ def LoginPost():
session['userName'] = name
session['role'] = 'admin' if name == adminName else 'user'
if user.expires and user.expiration_days > 0: #用户登陆后自动续期
user.expires = datetime.datetime.utcnow() + datetime.timedelta(days=user.expiration_days)
user.expires = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(days=user.expiration_days)
user.save()
if 'resetpwd' in user.custom: #成功登录后清除复位密码的设置
custom = user.custom
Expand Down Expand Up @@ -123,7 +123,7 @@ def CreateAccountIfNotExist(name, password=None, email='', sender=None, sm_servi
user = KeUser(name=name, passwd_hash=pwdHash, expires=None, expiration_days=expiration,
share_links={'key': shareKey}, base_config=base_config, send_mail_service=sm_service)
if expiration:
user.expires = datetime.datetime.utcnow() + datetime.timedelta(days=expiration)
user.expires = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(days=expiration)
user.save()
return True

Expand All @@ -147,7 +147,7 @@ def ResetPasswordRoute():
user = KeUser.get_or_none(KeUser.name == name) if name else None
if user and token: #重设密码的最后一步
pre_set = user.custom.get('resetpwd', {})
now = datetime.datetime.utcnow().timestamp()
now = datetime.datetime.now(datetime.timezone.utc).timestamp()
pre_time = pre_set.get('expires') or (now - datetime.timedelta(hours=1)).timestamp()
if (token == pre_set.get('token')) and (now < pre_time):
return render_template('reset_password.html', tips='', userName=name, firstStep=False,
Expand Down Expand Up @@ -186,7 +186,7 @@ def ResetPasswordPost():
return render_template('reset_password.html', tips=tips, userName=name, firstStep=True)
else:
token = new_secret_key(length=24)
expires = (datetime.datetime.utcnow() + datetime.timedelta(days=1)).timestamp()
expires = (datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(days=1)).timestamp()
user.set_custom('resetpwd', {'token': token, 'expires': expires})
user.save()
tips = send_resetpwd_email(user, token)
Expand Down Expand Up @@ -269,7 +269,7 @@ def send_resetpwd_email(user, token):
#重置密码的最后一步,校验密码,写入数据库
def reset_pwd_final_step(user, token, new_p1, new_p2):
pre_set = user.custom.get('resetpwd', {})
now = datetime.datetime.utcnow().timestamp()
now = datetime.datetime.now(datetime.timezone.utc).timestamp()
pre_time = pre_set.get('expires') or (now - datetime.timedelta(hours=1)).timestamp()
if (token == pre_set.get('token')) and (now < pre_time):
if new_p1 == new_p2:
Expand Down
4 changes: 2 additions & 2 deletions application/view/logs.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,14 +33,14 @@ def RemoveLogsRoute():

def RemoveLogs():
#停止过期用户的推送
now = datetime.datetime.utcnow()
now = datetime.datetime.now(datetime.timezone.utc)
for user in KeUser.select():
if user.cfg('enable_send') and user.expires and (user.expires < now):
user.set_cfg('enable_send', '')
user.save()

#清理30天之前的推送记录
time30 = datetime.datetime.utcnow() - datetime.timedelta(days=30)
time30 = datetime.datetime.now(datetime.timezone.utc) - datetime.timedelta(days=30)
cnt = DeliverLog.delete().where(DeliverLog.datetime < time30).execute()
cnt += LastDelivered.delete().where(LastDelivered.datetime < time30).execute()
return "{} lines delivery log removed.".format(cnt)
Expand Down
8 changes: 4 additions & 4 deletions application/view/subscribe.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ def MySubscriptionPost():
return redirect(url_for("bpSubscribe.MySubscription", tips=(_("Duplicated subscription!"))))
else:
Recipe.create(title=title, url=url, isfulltext=isfulltext, type_='custom', user=user.name,
time=datetime.datetime.utcnow())
time=datetime.datetime.now(datetime.timezone.utc))
return redirect(url_for("bpSubscribe.MySubscription"))

#添加/删除自定义RSS订阅的AJAX处理函数
Expand Down Expand Up @@ -145,7 +145,7 @@ def AddCustomRss(user, form):
return ret
else:
rss = Recipe.create(title=title, url=url, isfulltext=isfulltext, type_='custom', user=user.name,
time=datetime.datetime.utcnow())
time=datetime.datetime.now(datetime.timezone.utc))
ret['id'] = rss.recipe_id
UpdateBookedCustomRss(user)

Expand Down Expand Up @@ -184,7 +184,7 @@ def UpdateBookedCustomRss(user: KeUser):
if user.cfg('enable_send') == 'all': #添加自定义RSS的订阅
for rss in custom_rss:
BookedRecipe.get_or_create(recipe_id=rss.recipe_id, defaults={'separated': False, 'user': userName,
'title': rss.title, 'description': rss.description, 'time': datetime.datetime.utcnow(),
'title': rss.title, 'description': rss.description, 'time': datetime.datetime.now(datetime.timezone.utc),
'translator': rss.translator, 'tts': rss.tts, 'custom': rss.custom})
elif custom_rss: #删除订阅
ids = [rss.recipe_id for rss in custom_rss]
Expand Down Expand Up @@ -311,7 +311,7 @@ def SaveRecipeIfCorrect(user: KeUser, src: str):
raise Exception(_('The recipe is already in the library.'))

params = {"title": recipe.title, "description": recipe.description, "type_": 'upload',
"needs_subscription": recipe.needs_subscription, "src": src, "time": datetime.datetime.utcnow(),
"needs_subscription": recipe.needs_subscription, "src": src, "time": datetime.datetime.now(datetime.timezone.utc),
"user": user.name, "language": recipe.language}
dbInst = Recipe.create(**params)
params.pop('src')
Expand Down

0 comments on commit 25c0fbf

Please sign in to comment.