DetectControllerV2.py 25 KB

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