Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

修复postgresql 字段解析失败 #2597

Merged
merged 4 commits into from
Apr 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions common/tests.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import json
import smtplib
import psycopg2
from unittest.mock import patch, ANY
import datetime
from django.contrib.auth import get_user_model
Expand All @@ -17,6 +18,7 @@
)
from common.utils.chart_dao import ChartDao
from common.auth import init_user
from common.utils.extend_json_encoder import ExtendJSONEncoderFTime

User = get_user_model()

Expand Down Expand Up @@ -559,3 +561,25 @@ def test_superuser_required_true(self):
User.objects.filter(username=self.user.username).update(is_superuser=1)
r = self.client.get("/config/")
self.assertNotContains(r, "您无权操作,请联系管理员")


class ExtendJSONEncoderFTimeTest(TestCase):
def setUp(self):
# 初始化测试数据或状态
self.datetime1 = datetime.datetime.now()
self.datetime2 = datetime.datetime.now() - datetime.timedelta(days=1)
self.tz_range = psycopg2._range.DateTimeTZRange(self.datetime2, self.datetime1)
self.date_time = self.datetime1

def test_datetime_tz_range(self):
# 测试 DateTimeTZRange
result = ExtendJSONEncoderFTime().default(self.tz_range)
assert (
self.datetime1.strftime("%Y-%m-%d") in result
and self.datetime2.strftime("%Y-%m-%d") in result
)

def test_datetime(self):
# 测试datetime
result = ExtendJSONEncoderFTime().default(self.date_time)
assert self.datetime1.strftime("%Y-%m-%d") in result
5 changes: 4 additions & 1 deletion common/utils/extend_json_encoder.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# -*- coding: UTF-8 -*-
import base64
import simplejson as json
import psycopg2

from decimal import Decimal
from datetime import datetime, date, timedelta
Expand Down Expand Up @@ -94,7 +95,9 @@ def default(self, obj):
class ExtendJSONEncoderFTime(json.JSONEncoder):
def default(self, obj):
try:
if isinstance(obj, datetime):
if isinstance(obj, psycopg2._range.DateTimeTZRange):
return obj.lower.isoformat(" ") + "--" + obj.upper.isoformat(" ")
elif isinstance(obj, datetime):
return obj.isoformat(" ")
else:
return convert(obj)
Expand Down
Loading