DetectControllerV2.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  1. import json
  2. import logging
  3. import os
  4. import threading
  5. import time
  6. import apns2
  7. import boto3
  8. import botocore
  9. import jpush as jpush
  10. from botocore import client
  11. from django.http import JsonResponse
  12. from django.views.generic.base import View
  13. from pyfcm import FCMNotification
  14. from AnsjerPush.config import AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY
  15. from AnsjerPush.config import JPUSH_CONFIG, FCM_CONFIG, APNS_CONFIG, BASE_DIR, APNS_MODE
  16. from Model.models import UidPushModel, SysMsgModel
  17. from Object.ETkObject import ETkObject
  18. from Object.RedisObject import RedisObject
  19. from Object.UidTokenObject import UidTokenObject
  20. from Object.utils import LocalDateTimeUtil
  21. from Service.CommonService import CommonService
  22. from Service.EquipmentInfoService import EquipmentInfoService
  23. from Service.GatewayService import GatewayPushService
  24. # 移动侦测V2接口
  25. class NotificationV2View(View):
  26. def get(self, request, *args, **kwargs):
  27. request.encoding = 'utf-8'
  28. return self.validation(request.GET)
  29. def post(self, request, *args, **kwargs):
  30. request.encoding = 'utf-8'
  31. return self.validation(request.POST)
  32. def validation(self, request_dict):
  33. logger = logging.getLogger('info')
  34. logger.info("移动侦测V2接口参数:{}".format(request_dict))
  35. uidToken = request_dict.get('uidToken', None)
  36. etk = request_dict.get('etk', None)
  37. channel = request_dict.get('channel', '1')
  38. n_time = request_dict.get('n_time', None)
  39. event_type = request_dict.get('event_type', None)
  40. is_st = request_dict.get('is_st', None)
  41. region = request_dict.get('region', None)
  42. electricity = request_dict.get('electricity', '')
  43. if not all([channel, n_time]):
  44. return JsonResponse(status=200, data={
  45. 'code': 444,
  46. 'msg': 'param is wrong'})
  47. if not region or not is_st:
  48. return JsonResponse(status=200, data={'code': 404, 'msg': 'no region or is_st'})
  49. try:
  50. is_st = int(is_st)
  51. region = int(region)
  52. # 解密获取uid
  53. if etk:
  54. eto = ETkObject(etk)
  55. uid = eto.uid
  56. else:
  57. uto = UidTokenObject(uidToken)
  58. uid = uto.UID
  59. # uid = request_dict.get('uid', None) # 调试
  60. # 判断uid长度
  61. if len(uid) != 20 and len(uid) != 14:
  62. return JsonResponse(status=200, data={'code': 404, 'msg': 'wrong uid'})
  63. logger.info('调用推送接口的uid:{}'.format(uid))
  64. pkey = '{uid}_{channel}_{event_type}_ptl'.format(uid=uid, channel=channel, event_type=event_type)
  65. ykey = '{uid}_redis_qs'.format(uid=uid)
  66. is_sys_msg = self.is_sys_msg(int(event_type))
  67. if is_sys_msg:
  68. dkey = 'push_{uid}_{channel}_{event_type}_flag'.format(uid=uid, channel=channel, event_type=event_type)
  69. else:
  70. dkey = 'push_{uid}_{channel}_flag'.format(uid=uid, channel=channel)
  71. redisObj = RedisObject(db=6)
  72. have_ykey = redisObj.get_data(key=ykey) # uid_set 数据库缓存
  73. have_pkey = redisObj.get_data(key=pkey) # 一分钟限制key
  74. have_dkey = redisObj.get_data(key=dkey) # 推送消息时间间隔
  75. logger.info('ykey:{}, pkey: {}, dkey: {}'.format(have_ykey, have_pkey, have_dkey))
  76. logger.info('ykey:{}, pkey: {}, dkey: {}'.format(ykey, pkey, dkey))
  77. # 一分钟内不推送
  78. if have_pkey:
  79. return JsonResponse(status=200, data={'code': 0, 'msg': 'Push again in one minute'})
  80. redisObj.set_data(key=pkey, val=1, expire=60)
  81. # 查询推送数据
  82. uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid, uid_set__detect_status=1). \
  83. values('token_val', 'app_type', 'appBundleId', 'm_code', 'push_type', 'userID_id', 'userID__NickName',
  84. 'lang', 'm_code', 'tz', 'uid_set__nickname', 'uid_set__detect_interval', 'uid_set__detect_group',
  85. 'uid_set__channel', 'uid_set__ai_type', 'uid_set__new_detect_interval')
  86. if not uid_push_qs.exists():
  87. logger.info('uid_push 数据不存在')
  88. return JsonResponse(status=200, data={'code': 176, 'msg': 'no uid_push data'})
  89. ai_type = uid_push_qs.first()['uid_set__ai_type']
  90. event_type = self.get_combo_msg_type(ai_type, int(event_type))
  91. redis_list = []
  92. for qs in uid_push_qs:
  93. redis_list.append(qs)
  94. # 修改redis数据,并设置过期时间为10分钟
  95. redisObj.set_data(key=ykey, val=str(redis_list), expire=600)
  96. nickname = redis_list[0]['uid_set__nickname']
  97. detect_interval = redis_list[0]['uid_set__detect_interval']
  98. detect_group = redis_list[0]['uid_set__detect_group']
  99. if not nickname:
  100. nickname = uid
  101. logger.info('APP消息推送V2接口,是否进行APP推送:{},1为不推送,null为推送'.format(have_dkey))
  102. if not have_dkey:
  103. # 设置推送消息的时间间隔
  104. new_detect_interval = redis_list[0]['uid_set__new_detect_interval']
  105. detect_interval = new_detect_interval if new_detect_interval > 0 else detect_interval
  106. detect_interval = 60 if detect_interval < 60 else detect_interval
  107. redisObj.set_data(key=dkey, val=1, expire=detect_interval)
  108. logger.info('APP消息推送间隔:{}s'.format(detect_interval))
  109. if is_st == 1 or is_st == 3: # 使用aws s3
  110. aws_s3_client = s3_client(region=region)
  111. bucket = 'foreignpush' if region == 1 else 'push'
  112. kwag_args = {
  113. 'uid': uid,
  114. 'channel': channel,
  115. 'event_type': event_type,
  116. 'n_time': n_time,
  117. }
  118. sys_msg_list = []
  119. userID_ids = []
  120. do_apns_code = ''
  121. do_fcm_code = ''
  122. do_jpush_code = ''
  123. logger.info('进入手机推送------')
  124. logger.info('uid={}'.format(uid))
  125. logger.info(redis_list)
  126. new_device_info_list = []
  127. local_date_time = ''
  128. for up in redis_list:
  129. push_type = up['push_type']
  130. appBundleId = up['appBundleId']
  131. token_val = up['token_val']
  132. lang = up['lang']
  133. tz = up['tz']
  134. if tz is None or tz == '':
  135. tz = 0
  136. # 发送标题
  137. msg_title = self.get_msg_title(appBundleId=appBundleId, nickname=nickname)
  138. # 发送内容
  139. msg_text = self.get_msg_text(channel=channel, n_time=n_time, lang=lang, tz=tz,
  140. event_type=event_type, electricity=electricity)
  141. kwag_args['appBundleId'] = appBundleId
  142. kwag_args['token_val'] = token_val
  143. kwag_args['msg_title'] = msg_title
  144. kwag_args['msg_text'] = msg_text
  145. logger.info('推送要的数据: {}'.format(kwag_args))
  146. local_date_time = CommonService.get_now_time_str(n_time=n_time, tz=tz, lang='cn')
  147. logger.info('<<<<<根据时区计算后日期={},时区={}'.format(local_date_time, tz))
  148. local_date_time = local_date_time[0:10]
  149. logger.info('<<<<<切片后的日期={}'.format(local_date_time))
  150. # 以下是存库
  151. userID_id = up["userID_id"]
  152. if userID_id not in userID_ids:
  153. now_time = int(time.time())
  154. if is_sys_msg:
  155. sys_msg_text = self.get_msg_text(channel=channel, n_time=n_time, lang=lang, tz=tz,
  156. event_type=event_type, electricity=electricity, is_sys=1)
  157. sys_msg_list.append(SysMsgModel(
  158. userID_id=userID_id,
  159. msg=sys_msg_text,
  160. addTime=now_time,
  161. updTime=now_time,
  162. uid=uid,
  163. eventType=event_type))
  164. else:
  165. # start 根据设备侦测时间为准进行分表存储数据
  166. logger.info('分表存数据start------')
  167. new_device_info_list.append(EquipmentInfoService.get_equipment_info_obj(
  168. local_date_time,
  169. device_user_id=userID_id,
  170. event_time=n_time,
  171. event_type=event_type,
  172. device_uid=uid,
  173. device_nick_name=nickname,
  174. channel=channel,
  175. alarm='Motion \tChannel:{channel}'.format(channel=channel),
  176. is_st=is_st,
  177. receive_time=n_time,
  178. add_time=now_time,
  179. storage_location=2,
  180. border_coords='',
  181. ))
  182. # end
  183. userID_ids.append(userID_id)
  184. try:
  185. # 推送消息
  186. if not have_dkey:
  187. logger.info('APP准备推送:{}, {}'.format(uid, request_dict))
  188. if (is_st == 1 or is_st == 3) and (push_type == 0 or push_type == 1): # 推送显示图片
  189. if is_st == 1:
  190. key = '{}/{}/{}.jpeg'.format(uid, channel, n_time)
  191. else:
  192. key = '{}/{}/{}_0.jpeg'.format(uid, channel, n_time)
  193. push_thread = threading.Thread(target=self.push_thread_test, args=(
  194. push_type, aws_s3_client, bucket, key, uid, appBundleId, token_val, event_type, n_time,
  195. msg_title, msg_text, channel))
  196. push_thread.start()
  197. else:
  198. if push_type == 0: # ios apns
  199. do_apns_code = self.do_apns(**kwag_args)
  200. elif push_type == 1: # android gcm
  201. do_fcm_code = self.do_fcm(**kwag_args)
  202. elif push_type == 2: # android jpush
  203. do_jpush_code = self.do_jpush(**kwag_args)
  204. except Exception as e:
  205. logger.info(
  206. "errLine={errLine}, errMsg={errMsg}".format(errLine=e.__traceback__.tb_lineno, errMsg=repr(e)))
  207. continue
  208. if is_sys_msg:
  209. SysMsgModel.objects.bulk_create(sys_msg_list)
  210. else:
  211. # new 分表批量存储 设备信息
  212. if new_device_info_list and len(new_device_info_list) > 0:
  213. # 根据日期获得星期几
  214. week = LocalDateTimeUtil.date_to_week(local_date_time)
  215. EquipmentInfoService.equipment_info_bulk_create(week, new_device_info_list)
  216. logger.info('设备信息分表批量保存end------')
  217. if is_st == 0 or is_st == 2:
  218. for up in redis_list:
  219. if up['push_type'] == 0: # ios apns
  220. up['do_apns_code'] = do_apns_code
  221. elif up['push_type'] == 1: # android gcm
  222. up['do_fcm_code'] = do_fcm_code
  223. elif up['push_type'] == 2: # android jpush
  224. up['do_jpush_code'] = do_jpush_code
  225. del up['push_type']
  226. del up['userID_id']
  227. del up['userID__NickName']
  228. del up['lang']
  229. del up['tz']
  230. del up['uid_set__nickname']
  231. del up['uid_set__detect_interval']
  232. del up['uid_set__detect_group']
  233. return JsonResponse(status=200, data={'code': 0, 'msg': 'success 0 or 2', 're_list': redis_list})
  234. elif is_st == 1:
  235. thumbspng = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
  236. Params = {'Key': thumbspng}
  237. if region == 2: # 2:国内
  238. Params['Bucket'] = 'push'
  239. else: # 1:国外
  240. Params['Bucket'] = 'foreignpush'
  241. response_url = generate_s3_url(aws_s3_client, Params)
  242. for up in redis_list:
  243. up['do_apns_code'] = do_apns_code
  244. up['do_fcm_code'] = do_fcm_code
  245. up['do_jpush_code'] = do_jpush_code
  246. del up['push_type']
  247. del up['userID_id']
  248. del up['userID__NickName']
  249. del up['lang']
  250. del up['tz']
  251. del up['uid_set__nickname']
  252. del up['uid_set__detect_interval']
  253. del up['uid_set__detect_group']
  254. res_data = {'code': 0, 'img_push': response_url, 'msg': 'success'}
  255. return JsonResponse(status=200, data=res_data)
  256. elif is_st == 3:
  257. img_url_list = []
  258. if region == 2: # 2:国内
  259. Params = {'Bucket': 'push'}
  260. else: # 1:国外
  261. Params = {'Bucket': 'foreignpush'}
  262. for i in range(is_st):
  263. thumbspng = '{uid}/{channel}/{filename}_{st}.jpeg'. \
  264. format(uid=uid, channel=channel, filename=n_time, st=i)
  265. Params['Key'] = thumbspng
  266. response_url = generate_s3_url(aws_s3_client, Params)
  267. img_url_list.append(response_url)
  268. for up in redis_list:
  269. up['do_apns_code'] = do_apns_code
  270. up['do_fcm_code'] = do_fcm_code
  271. up['do_jpush_code'] = do_jpush_code
  272. del up['push_type']
  273. del up['userID_id']
  274. del up['userID__NickName']
  275. del up['lang']
  276. del up['tz']
  277. del up['uid_set__nickname']
  278. del up['uid_set__detect_interval']
  279. del up['uid_set__detect_group']
  280. res_data = {'code': 0, 'img_url_list': img_url_list, 'msg': 'success 3'}
  281. return JsonResponse(status=200, data=res_data)
  282. except Exception as e:
  283. logger.info('移动侦测接口异常: {}'.format(e))
  284. logger.info('错误文件', e.__traceback__.tb_frame.f_globals['__file__'])
  285. logger.info('错误行号', e.__traceback__.tb_lineno)
  286. data = {
  287. 'errLine': e.__traceback__.tb_lineno,
  288. 'errMsg': repr(e),
  289. }
  290. return JsonResponse(status=200, data=json.dumps(data), safe=False)
  291. @classmethod
  292. def get_combo_msg_type(cls, ai_type, event_type):
  293. """
  294. 获取组合类型,ai_type == 47 支持算法小店,需判断组合类型
  295. """
  296. logger = logging.getLogger('info')
  297. try:
  298. if ai_type != 47:
  299. return event_type
  300. logger.info('LOG------算法小店组合类型十进制值:{}'.format(event_type))
  301. # 如触发一个事件,则匹配已用类型 1替换后变成51代表移动侦测 1:移动侦测,2:人形,4:车型,8:人脸
  302. event_dict = {
  303. 1: 51,
  304. 2: 57,
  305. 4: 58,
  306. 16: 59,
  307. 8: 60,
  308. 32: 61
  309. }
  310. event_val = event_dict.get(event_type, 0)
  311. # event_val == 0 没有匹配到单个值则认为组合类型
  312. # 如是3,则转为二进制11,代表(1+2)触发了移动侦测+人形侦测
  313. if event_val == 0:
  314. val = cls.dec_to_bin(event_type)
  315. return int(val)
  316. else:
  317. return int(event_val)
  318. except Exception as e:
  319. logger.info('推送错误异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  320. return event_type
  321. @staticmethod
  322. def dec_to_bin(num):
  323. """
  324. 十进制转二进制
  325. """
  326. result = ""
  327. while num != 0:
  328. ret = num % 2
  329. num //= 2
  330. result = str(ret) + result
  331. return result
  332. def push_thread_test(self, push_type, aws_s3_client, bucket, key, uid, appBundleId, token_val, event_type, n_time,
  333. msg_title, msg_text, channel):
  334. logger = logging.getLogger('info')
  335. logger.info('推送图片测试:{} {} {} {} {} {} {} {}'.format(push_type, uid, appBundleId, token_val, event_type, n_time,
  336. msg_title, msg_text))
  337. try:
  338. image_url = aws_s3_client.generate_presigned_url('get_object', Params={'Bucket': bucket, 'Key': key},
  339. ExpiresIn=300)
  340. logger.info('推送图片url:{}'.format(image_url))
  341. if push_type == 0:
  342. GatewayPushService.ios_apns_push(uid, appBundleId, token_val, n_time, event_type, msg_title, msg_text,
  343. uid, channel, image_url)
  344. elif push_type == 1:
  345. GatewayPushService.android_fcm_push(uid, appBundleId, token_val, n_time, event_type, msg_title,
  346. msg_text, uid, channel, image_url)
  347. except Exception as e:
  348. logger.info('推送图片测试异常:{}'.format(e))
  349. def get_msg_title(self, appBundleId, nickname):
  350. package_title_config = {
  351. 'com.ansjer.customizedd_a': 'DVS',
  352. 'com.ansjer.zccloud_a': 'ZosiSmart',
  353. 'com.ansjer.zccloud_ab': '周视',
  354. 'com.ansjer.adcloud_a': 'ADCloud',
  355. 'com.ansjer.adcloud_ab': 'ADCloud',
  356. 'com.ansjer.accloud_a': 'ACCloud',
  357. 'com.ansjer.loocamccloud_a': 'Loocam',
  358. 'com.ansjer.loocamdcloud_a': 'Anlapus',
  359. 'com.ansjer.customizedb_a': 'COCOONHD',
  360. 'com.ansjer.customizeda_a': 'Guardian365',
  361. 'com.ansjer.customizedc_a': 'PatrolSecure',
  362. }
  363. if appBundleId in package_title_config.keys():
  364. return package_title_config[appBundleId] + '(' + nickname + ')'
  365. else:
  366. return nickname
  367. def is_sys_msg(self, event_type):
  368. event_type_list = [702, 703, 704]
  369. if event_type in event_type_list:
  370. return True
  371. return False
  372. def get_msg_text(self, channel, n_time, lang, tz, event_type, electricity='', is_sys=0):
  373. n_date = CommonService.get_now_time_str(n_time=n_time, tz=tz, lang=lang)
  374. etype = int(event_type)
  375. if lang == 'cn':
  376. if etype == 704:
  377. msg_type = '剩余电量:' + electricity
  378. elif etype == 702:
  379. msg_type = '摄像头休眠'
  380. elif etype == 703:
  381. msg_type = '摄像头唤醒'
  382. else:
  383. msg_type = ''
  384. if is_sys:
  385. send_text = '{msg_type} 通道:{channel}'.format(msg_type=msg_type, channel=channel)
  386. else:
  387. send_text = '{msg_type} 通道:{channel} 日期:{date}'.format(msg_type=msg_type, channel=channel, date=n_date)
  388. else:
  389. if etype == 704:
  390. msg_type = 'Battery remaining:' + electricity
  391. elif etype == 702:
  392. msg_type = 'Camera sleep'
  393. elif etype == 703:
  394. msg_type = 'Camera wake'
  395. else:
  396. msg_type = ''
  397. if is_sys:
  398. send_text = '{msg_type} channel:{channel}'. \
  399. format(msg_type=msg_type, channel=channel)
  400. else:
  401. send_text = '{msg_type} channel:{channel} date:{date}'. \
  402. format(msg_type=msg_type, channel=channel, date=n_date)
  403. return send_text
  404. def do_jpush(self, uid, channel, appBundleId, token_val, event_type, n_time,
  405. msg_title, msg_text):
  406. app_key = JPUSH_CONFIG[appBundleId]['Key']
  407. master_secret = JPUSH_CONFIG[appBundleId]['Secret']
  408. _jpush = jpush.JPush(app_key, master_secret)
  409. push = _jpush.create_push()
  410. push.audience = jpush.registration_id(token_val)
  411. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  412. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  413. android = jpush.android(alert=msg_text, priority=1, style=1, alert_type=7,
  414. big_text=msg_text, title=msg_title,
  415. extras=push_data)
  416. push.notification = jpush.notification(android=android)
  417. push.platform = jpush.all_
  418. res = push.send()
  419. print(res)
  420. return res.status_code
  421. def do_fcm(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title, msg_text):
  422. logger = logging.getLogger('info')
  423. try:
  424. serverKey = FCM_CONFIG[appBundleId]
  425. except Exception as e:
  426. logger.info('------fcm_error:{}'.format(repr(e)))
  427. return 'serverKey abnormal'
  428. push_service = FCMNotification(api_key=serverKey)
  429. data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  430. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  431. result = push_service.notify_single_device(registration_id=token_val, message_title=msg_title,
  432. message_body=msg_text, data_message=data,
  433. extra_kwargs={
  434. 'default_vibrate_timings': True,
  435. 'default_sound': True,
  436. 'default_light_settings': True
  437. })
  438. return result
  439. def do_apns(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title,
  440. msg_text):
  441. logger = logging.getLogger('info')
  442. logger.info("进来do_apns函数了")
  443. logger.info(token_val)
  444. logger.info(APNS_MODE)
  445. logger.info(os.path.join(BASE_DIR, APNS_CONFIG[appBundleId]['pem_path']))
  446. try:
  447. cli = apns2.APNSClient(mode=APNS_MODE,
  448. client_cert=os.path.join(BASE_DIR, APNS_CONFIG[appBundleId]['pem_path']))
  449. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  450. "received_at": n_time, "sound": "", "uid": uid, "zpush": "1", "channel": channel}
  451. alert = apns2.PayloadAlert(body=msg_text, title=msg_title)
  452. payload = apns2.Payload(alert=alert, custom=push_data, sound="default")
  453. # return uid, channel, appBundleId, str(token_val), event_type, n_time, msg_title,msg_text
  454. n = apns2.Notification(payload=payload, priority=apns2.PRIORITY_LOW)
  455. res = cli.push(n=n, device_token=token_val, topic=appBundleId)
  456. print(res.status_code)
  457. logger.info("apns_推送状态:")
  458. logger.info(res.status_code)
  459. if res.status_code == 200:
  460. return res.status_code
  461. else:
  462. print('apns push fail')
  463. print(res.reason)
  464. logger.info('apns push fail')
  465. logger.info(res.reason)
  466. return res.status_code
  467. except (ValueError, ArithmeticError):
  468. return 'The program has a numeric format exception, one of the arithmetic exceptions'
  469. except Exception as e:
  470. print(repr(e))
  471. print('do_apns函数错误行号', e.__traceback__.tb_lineno)
  472. logger.info('do_apns错误:{}'.format(repr(e)))
  473. return repr(e)
  474. def s3_client(region):
  475. if region == 2: # 国内
  476. aws_s3_client = boto3.client(
  477. 's3',
  478. aws_access_key_id=AWS_ACCESS_KEY_ID[0],
  479. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[0],
  480. config=botocore.client.Config(signature_version='s3v4'),
  481. region_name='cn-northwest-1'
  482. )
  483. else: # 国外
  484. aws_s3_client = boto3.client(
  485. 's3',
  486. aws_access_key_id=AWS_ACCESS_KEY_ID[1],
  487. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[1],
  488. config=botocore.client.Config(signature_version='s3v4'),
  489. region_name='us-east-1'
  490. )
  491. return aws_s3_client
  492. def generate_s3_url(aws_s3_client, Params):
  493. response_url = aws_s3_client.generate_presigned_url(
  494. ClientMethod='put_object',
  495. Params=Params,
  496. ExpiresIn=3600
  497. )
  498. return response_url