ソースを参照

新增设备上报客流统计接口

zhangdongming 2 年 前
コミット
809b37c610

+ 3 - 0
Ansjer/server_urls/algorithm_shop_url.py

@@ -8,6 +8,7 @@
 """
 from django.urls import re_path
 
+from AdminController import AlgorithmShopManageController
 from Controller.AlgorithmShop import AlgorithmShopController
 from Controller.CloudPhoto import CloudPhotoController
 from Controller.Cron import CronCloudPhotoController
@@ -17,5 +18,7 @@ urlpatterns = [
     re_path(r'^cron/(?P<operation>.*)$', CronCloudPhotoController.CronCloudPhotoView.as_view()),
     re_path(r'^photo/(?P<operation>.*)$', CloudPhotoController.CronCloudPhotoView.as_view()),
     re_path(r'^open/(?P<operation>.*)$', AlgorithmShopController.AlgorithmShopView.as_view()),
+    re_path(r'^(?P<apiVersion>[a-zA-Z0-9]+)/manage/(?P<operation>.*)$',
+            AlgorithmShopManageController.AlgorithmShopManageView.as_view()),
 
 ]

+ 76 - 1
Controller/AlgorithmShop/AlgorithmShopController.py

@@ -6,16 +6,23 @@
 @Email   : zhangdongming@asj6.wecom.work
 @Software: PyCharm
 """
+import json
 import logging
 import time
+from datetime import datetime
 
 from django.db.models import F, Value, CharField
 from django.views.generic.base import View
 
 from Model.models import DeviceAlgorithmExplain, DeviceAlgorithmBanner, DeviceUidAlgorithmType, \
-    DeviceTypeAlgorithmInfo, DeviceAppScenario, DeviceScenarioLangInfo, DeviceAlgorithmScenario
+    DeviceTypeAlgorithmInfo, DeviceAppScenario, DeviceScenarioLangInfo, DeviceAlgorithmScenario, \
+    DeviceAlgorithmPassengerFlow
+from Object.ETkObject import ETkObject
+from Object.Enums.TimeZone import TimeZone
+from Object.RedisObject import RedisObject
 from Object.ResponseObject import ResponseObject
 from Object.TokenObject import TokenObject
+from Object.utils import LocalDateTimeUtil
 
 LOGGER = logging.getLogger('info')
 
@@ -32,6 +39,8 @@ class AlgorithmShopView(View):
         return self.validation(request.POST, request, operation)
 
     def validation(self, request_dict, request, operation):
+        if operation == 'passengerFlowStatistical':
+            return self.passenger_flow_statistical(request_dict, ResponseObject('en'))
         token = TokenObject(request.META.get('HTTP_AUTHORIZATION'))
         lang = request_dict.get('lang', token.lang)
         response = ResponseObject(lang)
@@ -52,6 +61,72 @@ class AlgorithmShopView(View):
         else:
             return response.json(0)
 
+    @classmethod
+    def passenger_flow_statistical(cls, request_dict, response):
+        """
+        添加客流统计
+        Args:
+            request_dict (dict): 请求参数字典
+            response: 响应对象
+        """
+        try:
+            LOGGER.info('*****AlgorithmShopView.passenger_flow_statistical:params{}'.format(json.dumps(request_dict)))
+            sign = request_dict.get('sign')
+            eto = ETkObject(sign)
+            uid = eto.uid
+            if not uid:
+                return response.json(444)
+
+            d_time = request_dict.get('deviceTime')
+            enter_count = request_dict.get('enterCount')
+            tz_value = request_dict.get('timeZone')
+            exit_count = request_dict.get('exitCount')
+
+            if not all([sign, enter_count, exit_count, tz_value]):
+                return response.json(444)
+            enter_count = int(enter_count)
+            exit_count = int(exit_count)
+            redis = RedisObject(5)
+            key = f'ASJ:PASSENGER:FLOW:{uid}:{d_time}'
+
+            # 检查Redis中是否已存在相同key的数据
+            r_data = redis.get_data(key)
+            if r_data:
+                return response.json(0)
+
+            now_time = int(time.time())
+            data = {
+                'uid': uid,
+                'updated_time': now_time,
+                'created_time': now_time,
+                'device_time': int(d_time)
+            }
+
+            tz = TimeZone.get_value(int(tz_value))
+            date_time = LocalDateTimeUtil.time_format_date(int(d_time), tz)
+            data['statistical_time'] = datetime.strptime(date_time, '%Y-%m-%d %H:%M:%S')
+
+            LOGGER.info(f'uid{uid}-DeviceTime:{d_time},tz:{tz},结果:{date_time}')
+            passenger_flow_list = []
+            if enter_count > 0:
+                data['count'] = enter_count
+                data['type'] = 1
+                passenger_flow_list.append(DeviceAlgorithmPassengerFlow(**data))
+            if exit_count > 0:
+                data['count'] = exit_count
+                data['type'] = 2
+                passenger_flow_list.append(DeviceAlgorithmPassengerFlow(**data))
+            DeviceAlgorithmPassengerFlow.objects.bulk_create(passenger_flow_list)
+            # 将数据存入Redis,并设置过期时间为10分钟
+            redis.CONN.setnx(key, d_time)
+            redis.CONN.expire(key, 600)
+
+            return response.json(0)
+        except Exception as e:
+            LOGGER.info('***get_algorithm_list_by_scenario_id,errLine:{}, errMsg:{}'
+                        .format(e.__traceback__.tb_lineno, repr(e)))
+            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
+
     @classmethod
     def get_algorithm_list_by_scenario_id(cls, scenario_id, lang):
         """

+ 2 - 2
Model/models.py

@@ -3177,7 +3177,7 @@ class DeviceAlgorithmPassengerFlow(models.Model):
     uid = models.CharField(max_length=32, db_index=True, default='', verbose_name='设备uid')
     type = models.SmallIntegerField(default=0, verbose_name='客流类型,1:进,2:离开')
     count = models.IntegerField(default=0, verbose_name='当前时段统计数量')
-    statistical_time = models.DateTimeField(blank=True, null=True, verbose_name=u'统计日期时间')
+    statistical_time = models.DateTimeField(auto_now_add=True, blank=True, null=True, verbose_name=u'统计日期时间')
     device_time = models.IntegerField(default=0, verbose_name='设备上报时间戳')
     updated_time = models.IntegerField(default=0, verbose_name='更新时间')
     created_time = models.IntegerField(default=0, verbose_name='创建时间')
@@ -3739,4 +3739,4 @@ class CityInformation(models.Model):
     class Meta:
         db_table = 'city_information'
         verbose_name = '城市信息'
-        verbose_name_plural = verbose_name
+        verbose_name_plural = verbose_name

+ 12 - 39
Object/utils/LocalDateTimeUtil.py

@@ -256,42 +256,15 @@ def time_stamp_to_time(time_stamp, time_format):
     return time.strftime(time_format, time_array)
 
 
-if __name__ == '__main__':
-    zero_today, last_today = get_today_date(True)
-    month_end = get_cur_month_end()
-    start_time, month_end_time = get_start_and_end_time(month_end, '%Y-%m-%d')
-    print(zero_today)
-    print(month_end_time)
-
-    # # 获取当前月
-    # print('当前月', get_cur_month())
-    # # 获取上一个月
-    # print('上一个月', get_last_month_num())
-    # # 获取上两个月
-    # print('上两个月', get_last_month_num(number=2))
-    # # 获取下一个月
-    # print('下一个月', get_next_month())
-    # # 获取下两个月
-    # print('下两个月', get_next_month(number=2))
-    # # 获取当前月的第一天
-    # print('当前月的第一天', get_cur_month_start())
-    # # 获取当前月的最后一天
-    # print('当前月的最后一天', get_cur_month_end())
-    # # 获取上个月的第一天
-    # print('上个月的第一天', get_last_month_start())
-    # # 获取下个月的第一天
-    # print('下个月的第一天', get_next_month_start())
-    # # 获取上个月的最后一天
-    # print('上个月的最后一天', get_last_month_end())
-    # # 获取下个月的最后一天
-    # print('下个月的最后一天', get_next_month_end())
-    dd = str(1650791368303)
-    print(dd[0:10])
-    print(dd[10:])
-    dateArray = datetime.datetime.utcfromtimestamp(1650791368)
-    print(dateArray.date())
-    next_start_time, next_end_time = get_start_and_end_time(get_next_month_start(), '%Y-%m-%d')
-    print(type(next_end_time))
-    print('下月开始时间{}'.format(next_start_time))
-    start_time, end_time = get_start_and_end_time(get_next_month_end(), '%Y-%m-%d')
-    print('下月结束时间{}'.format(end_time))
+def time_format_date(timestamp, tz):
+    # 解析时区偏移量
+    tz_hours, tz_minutes = map(int, tz.split(':'))
+    # 将时间戳转换为 datetime 对象
+    dt = datetime.datetime.fromtimestamp(timestamp)
+    # 创建 timedelta 对象,表示时区偏移量
+    tz_offset = datetime.timedelta(hours=tz_hours, minutes=tz_minutes)
+    # 调整 datetime 对象的时区
+    dt = dt + tz_offset
+    # 格式化日期时间字符串
+    formatted_date = dt.strftime('%Y-%m-%d %H:%M:%S')
+    return formatted_date