From 7ea50ca8938e423404bd6739276edc11671f0e76 Mon Sep 17 00:00:00 2001 From: wangxu <1318272526@qq.com> Date: Tue, 13 Jan 2026 15:44:17 +0800 Subject: [PATCH] =?UTF-8?q?=E6=8F=90=E4=BA=A4=E6=9D=83=E9=99=90=E7=BB=86?= =?UTF-8?q?=E5=88=86=E7=9B=B8=E5=85=B3=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/eva_common.py | 10 ++++- app/task_db_func.py | 7 ++-- app/task_worker.py | 22 +++++----- app/tmnet_db_func.py | 50 +++++++++++++++++++++- app/user_db_func.py | 18 ++++++-- app/user_worker.py | 40 +++++++++++------- test.py | 99 ++++++++++++++++++++++++++++++++++++++------ tool/qcos_func.py | 86 ++++++++++++++++++++++++++++++++++++++ 8 files changed, 284 insertions(+), 48 deletions(-) create mode 100644 tool/qcos_func.py diff --git a/app/eva_common.py b/app/eva_common.py index 07211e6..50e3726 100644 --- a/app/eva_common.py +++ b/app/eva_common.py @@ -604,7 +604,10 @@ def gen_crossids_roads_dir_dict_by_mysql(crossids, nodeid): 'in': roadid, 'out': min_angle_outroadid if min_angle_outroadid != '' else '-', 'entry_lane_num': len(inroad_info_dict[roadid]['lane_turn_info'].split('|')), - 'exit_lane_num': '-' if min_angle_outroadid == '' else outroad_info_dict[min_angle_outroadid]['lane_num'] + 'exit_lane_num': '-' if min_angle_outroadid == '' else outroad_info_dict[min_angle_outroadid]['lane_num'], + 'lane_turn_info': inroad_info_dict[roadid]['lane_turn_info'], + 'reverse_turn': inroad_info_dict[roadid]['reverse_turn'], + 'hold_straight': inroad_info_dict[roadid]['straight_turn_waiting_area'] } for outroadid in outroadid_angle_dict.keys(): out_road = g_roadnet.query_road(outroadid) @@ -613,7 +616,10 @@ def gen_crossids_roads_dir_dict_by_mysql(crossids, nodeid): 'in': '-', 'out': outroadid, 'entry_lane_num': '-', - 'exit_lane_num': outroad_info_dict[outroadid]['lane_num'] + 'exit_lane_num': outroad_info_dict[outroadid]['lane_num'], + 'lane_turn_info': '', + 'reverse_turn': 0, + 'hold_straight': 0 } crosses_roads_dir_dict[crossid] = roads_dir_dict return crosses_roads_dir_dict diff --git a/app/task_db_func.py b/app/task_db_func.py index 2ad9e06..d5f9fa7 100644 --- a/app/task_db_func.py +++ b/app/task_db_func.py @@ -233,11 +233,10 @@ class TaskDbHelper(TableDbHelperBase): }) return download_url_list - def del_task_file(self, nodeid, taskno, file_name, file_id): - download_url = f'/api/download_task_file?nodeid={nodeid}&taskno={taskno}&file_name={file_name}' + def del_task_file(self, nodeid, taskno, file_id): sql = f""" - delete from task.task_upload_file_record where nodeid = %d and taskno = %d and download_url = '%s' and id = %d - """ % (int(nodeid), int(taskno), download_url, int(file_id)) + delete from task.task_upload_file_record where nodeid = %d and taskno = %d and id = %d + """ % (int(nodeid), int(taskno), int(file_id)) return self.do_execute(sql) def update_task_state(self, nodeid, area_id, task_no, state): diff --git a/app/task_worker.py b/app/task_worker.py index f2b7a00..64756e0 100644 --- a/app/task_worker.py +++ b/app/task_worker.py @@ -9,6 +9,7 @@ from flask import request, send_file from pypinyin import lazy_pinyin, Style from app.common_worker import * +from tool.qcos_func import get_client ALLOWED_EXTENSION_TASK = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif', 'doc', 'docx', 'xlsx', 'xls', 'pptx', 'ppt'} @@ -749,17 +750,20 @@ def do_task_upload(params): if len(request.files.keys()) < 1: return json.dumps(make_common_res(1, '文件不存在')) suc_file_num, suc_mysql_num = 0, 0 + g_cos_root = 'https://xinglu-1324629296.cos.ap-beijing.myqcloud.com' + g_cos_bucket = 'xinglu-1324629296' for key in request.files.keys(): file = request.files[key] try: if not (file and file.filename and allowed_file_for_task(file.filename)): return json.dumps(make_common_res(1, '文件格式错误')) - if not os.path.exists(f'./app/static/task_file/{nodeid}/task_no_{taskno}'): - os.makedirs(f'./app/static/task_file/{nodeid}/task_no_{taskno}') - os.chmod(f'./app/static/task_file/{nodeid}/task_no_{taskno}', 0o777) - file.save(f'./app/static/task_file/{nodeid}/task_no_{taskno}/{file.filename}') + file_name = file.filename + cos_key = '/user/cross_doctor/task_file/%s' % ('task_no_' + str(taskno) + '_' + file_name) + file_stream = file.stream + cos_client = get_client() + cos_client.put_object(Bucket=g_cos_bucket, Key=cos_key, Body=file_stream) suc_file_num += 1 - download_url = f'/api/download_task_file?nodeid={nodeid}&taskno={taskno}&file_name={file.filename}&area_id={area_id}&userid={userid}' + download_url = f'{g_cos_root}{cos_key}' ret = db_task.insert_upload_file_record(taskno, nodeid, download_url, area_id) if ret == 1: suc_mysql_num += 1 @@ -767,9 +771,6 @@ def do_task_upload(params): break except Exception as e: logging.error(str(e) + '任务文件上传失败') - if os.path.exists(f'./app/static/task_file/{nodeid}/task_no_{taskno}/{file.filename}'): - os.remove(f'./app/static/task_file/{nodeid}/task_no_{taskno}/{file.filename}') - logging.info('回滚上传操作') break if suc_file_num == suc_mysql_num == len(request.files.keys()): res = make_common_res(0, 'ok') @@ -865,13 +866,10 @@ def del_task_file_api(params): taskno = check_param(params, 'taskno') if not taskno: return json.dumps(make_common_res(2, '任务id异常,请检查后重试')) - file_name = check_param(params, 'file_name') - if not file_name: - return json.dumps(make_common_res(2, '文件名异常,请检查后重试')) file_id = check_param(params, 'file_id') if not file_id: return json.dumps(make_common_res(2, '文件id异常,请检查后重试')) - ret = db_task.del_task_file(nodeid, taskno, file_name, file_id) + ret = db_task.del_task_file(nodeid, taskno, file_id) if ret == 1: res = make_common_res(0, 'ok') res['nodeid'] = nodeid diff --git a/app/tmnet_db_func.py b/app/tmnet_db_func.py index 6229490..a537b24 100644 --- a/app/tmnet_db_func.py +++ b/app/tmnet_db_func.py @@ -104,7 +104,9 @@ class TmnetDbHelper(TableDbHelperBase): if(t2.to_crossid is not null, t2.to_crossid, t1.to_crossid) as to_crossid, if(t2.name is not null, t2.name, t1.name) as name, if(t2.src_direct is not null, t2.src_direct, t1.src_direct) as src_direct, - if(t2.lane_turn_info is not null, t2.lane_turn_info, t1.lane_turn_info) as lane_turn_info + if(t2.lane_turn_info is not null, t2.lane_turn_info, t1.lane_turn_info) as lane_turn_info, + t2.straight_turn_waiting_area, + t2.reverse_turn from (select * from road where nodeid = '%s' and recordstate=0 and to_crossid in (%s) and (is_sup_road is null or is_sup_road<>1)) t1 left join @@ -573,3 +575,49 @@ class TmnetDbHelper(TableDbHelperBase): update cross_survey.cross_survey_jobs set status = 0, done_inroads = '%s' where id = %s """ % (done_inroads, jobid) return self.do_execute(sql) + + def query_cross_info_by_area_id(self, area_id, nodeid): + sql = """ + select + if(t2.name is not null, t2.name, t1.name) as cross_name, + if(t2.cross_no is not null, t2.cross_no, t1.cross_no) as cross_no, + t1.crossid, + if(t2.location is not null, t2.location, t1.location) as location, + if(t2.cross_type is not null, t2.cross_type, t1.cross_type) as cross_type, + if(t2.slcid is not null, t2.slcid, t1.slcid) as slcid, + if(t2.slc_company is not null ,t2.slc_company, t1.slc_company) as slc_company, + if(t2.slckind is not null, t2.slckind, t1.slckind) as slckind, + if(t2.division is not null, t2.division, t1.division) as division, + if(t2.company is not null, t2.company, t1.company) as company, + if(t2.cross_model is not null, t2.cross_model, t1.cross_model) as cross_model, + if(t2.cross_level is not null, t2.cross_level, t1.cross_level) as cross_level, + if(t2.canaliza_type is not null, t2.canaliza_type, t1.canaliza_type) as canaliza_type, + if(t2.internet is not null, t2.internet, t1.internet) as internet, + if(t2.ip_address is not null, t2.ip_address, t1.ip_address) as ip_address, + if(t2.subnet_mask is not null, t2.subnet_mask, t1.subnet_mask) as subnet_mask, + if(t2.gate_away is not null, t2.gate_away, t1.gate_away) as gate_away, + if(t2.remark is not null, t2.remark, t1.remark) as remark, + if(t2.cross_centre is not null, t2.cross_centre, t1.cross_centre) as cross_centre, + if(t2.slc_location is not null, t2.slc_location, t1.slc_location) as slc_location, + if(t2.bicycle_twice_cross_street is not null, t2.bicycle_twice_cross_street, t1.bicycle_twice_cross_street) as bicycle_twice_cross_street, + if(t2.bicycle_twice_cross_type is not null, t2.bicycle_twice_cross_type, t1.bicycle_twice_cross_type) as bicycle_twice_cross_type + from (select * from `cross` where isdeleted = 0 and nodeid = %s and crossid in (select crossid from bound_crosses where nodeid = %s and area_id = %s)) t1 + left join + (select * from cross_ledger_update_info where isdeleted = 0 and nodeid = %s and crossid in (select crossid from bound_crosses where nodeid = %s and area_id = %s)) t2 + on t1.crossid = t2.crossid""" % (nodeid, nodeid, area_id, nodeid, nodeid, area_id) + return self.do_select(sql) + + def query_reversed_lanes_crossid(self, nodeid): + sql = """ + select crossid from reversible_lanes_info where nodeid = %s + """ % (nodeid) + res = [] + for item in self.do_select(sql): + res.append(item['crossid']) + return res + + def check_right_light(self, nodeid): + sql = """ + select crossid from light_info where nodeid = %s and light_type = 4 + """ % (nodeid) + return self.do_select(sql) \ No newline at end of file diff --git a/app/user_db_func.py b/app/user_db_func.py index 6a6065a..1a0e6d0 100644 --- a/app/user_db_func.py +++ b/app/user_db_func.py @@ -208,14 +208,14 @@ class UserDbHelper(TableDbHelperBase): """ % (userid) return self.do_execute(sql) - def insert_user(self, userid, password, user_name, area_id_list, all_area_info_dict): + def insert_user(self, userid, password, user_name, area_id_list, all_area_info_dict, role): values = [] for area_id in area_id_list: values.append((userid, area_id, all_area_info_dict[int(area_id)]['nodeid'])) tmp_token = 'iuqwefhjdbcsajhdshcgaiudncjadhajn_' + userid sql1 = """ - insert into user(userno, user_name, password, token, department, role) values('%s', '%s', '%s', '%s', '信号调优团队', 'engineer') - """ % (userid, user_name, password, tmp_token) + insert into user(userno, user_name, password, token, department, role) values('%s', '%s', '%s', '%s', '信号调优团队', '%s') + """ % (userid, user_name, password, tmp_token, role) sql2 = "insert into area_user(userno, area_id, nodeid) values(%s, %s, %s)" conn, cursor = self.connect() conn.begin() @@ -235,3 +235,15 @@ class UserDbHelper(TableDbHelperBase): logging.error(e) conn.rollback() return False + + def query_role_page(self, role): + sql = """ + select * from role_page where platform = 'cross_doctor' and role = '%s' + """ % (role) + row_list = self.do_select(sql) + res = [] + if row_list: + page_permission = row_list[0]['page_permission'] + for item in page_permission.split(','): + res.append(item) + return res \ No newline at end of file diff --git a/app/user_worker.py b/app/user_worker.py index 01aa32a..6a7dcf7 100644 --- a/app/user_worker.py +++ b/app/user_worker.py @@ -97,8 +97,9 @@ def do_get_user_info(params, token): super_user = 0 if user['userno'] in g_config['executives']: super_user = 1 + role_page = db_user.query_role_page(user['role']) user_t = {'userno': user['userno'], 'user_name': user['user_name'], 'role': user['role'], - 'department': user['department'], 's': super_user} + 'department': user['department'], 's': super_user, 'role_page': role_page} if user['role'] == 'manager': all_areas = db_user.query_all_area_infos() user_area_info = list(all_areas.values()) @@ -196,8 +197,7 @@ def query_user_list(params): keyword = '' role = check_param(params, 'role') if not role: - role = 0 - role = int(role) + role = 'all' start_date = check_param(params, 'start_date') end_date = check_param(params, 'end_date') if not start_date: @@ -212,7 +212,13 @@ def query_user_list(params): page_size = 10 start_index = (int(page) - 1) * int(page_size) end_index = start_index + int(page_size) - + role_dict = { + 'headquarters_engineer': '总部工程师', + 'project_manager': '项目经理', + 'business_expert': '业务专家', + 'project_engineer': '项目工程师', + 'manager': '超级管理员', + } user_list = db_user.query_users() all_area_info = db_user.query_all_area_infos() res_list = user_list.copy() @@ -223,20 +229,14 @@ def query_user_list(params): res_list = [item for item in user_list if keyword in item['userno']] else: res_list = find_user_info(keyword, user_list) - if role != 0: - if role == 1: - role_str = 'engineer' - res_list = [item for item in res_list if item['role'] == role_str] - else: - role_str = 'manager' - res_list = [item for item in res_list if item['role'] == role_str] + if role != 'all': + res_list = [item for item in res_list if item['role'] == role] if start_date != '' and end_date != '': res_list = [item for item in res_list if start_date <= item['last_modify_pwd_time'].strftime("%Y%m%d") <= end_date] for item in res_list: item['last_modify_pwd_time'] = item['last_modify_pwd_time'].strftime("%Y年%m月%d日 %H:%M:%S") if item['role'] != 'manager': - item['role'] = '工程师' area_id_list = item['area_ids'].split(',') if item['area_ids'] else [] nodeid_list = item['nodeids'].split(',') if item['nodeids'] else [] area_name = '' if len(area_id_list) < 1 else ','.join([all_area_info[int(o)]['area_name'] for o in area_id_list]) @@ -244,7 +244,6 @@ def query_user_list(params): item['city_names'] = city_names item['area_names'] = area_name else: - item['role'] = '超级管理员' item['city_names'] = '全部' item['area_names'] = '全部' @@ -288,6 +287,9 @@ def modify_user(params): for area_id in area_id_list: if not str(area_id).lstrip('-').isdigit(): return json.dumps(make_common_res(6, '区域id信息异常,请检查后重试')) + role = check_param(params, 'role') + if not role or role not in ['headquarters_engineer', 'project_manager', 'business_expert', 'project_engineer']: + role = '' modify_sql = '' if user_name != '' and user_name != user_info['user_name']: modify_sql += "set user_name='%s'" % user_name @@ -301,6 +303,11 @@ def modify_user(params): modify_sql += "set password='%s'" % password else: modify_sql += ",password='%s'" % password + if role != '' and role != user_info['role']: + if modify_sql == '': + modify_sql += "set role='%s'" % role + else: + modify_sql += ",role='%s'" % role all_area_info = db_user.query_all_area_infos() res, ret = db_user.update_user_info(modify_sql, modify_userid, area_id_list, new_userid, all_area_info) if res and ret == len(area_id_list): @@ -354,6 +361,11 @@ def create_user(params): return json.dumps(make_common_res(5, '缺少密码信息,请检查后重试')) if len(password) < 6: return json.dumps(make_common_res(6, '密码长度不能小于6位,请检查后重试')) + role = check_param(params, 'role') + if not role: + return json.dumps(make_common_res(7, '缺少角色信息,请检查后重试')) + if role not in ('headquarters_engineer', 'project_manager', 'business_expert', 'project_engineer'): + return json.dumps(make_common_res(8, '角色信息异常,请检查后重试')) area_id_list = check_param(params, 'area_id_list') if not area_id_list or len(area_id_list) < 1: area_id_list = [] @@ -363,7 +375,7 @@ def create_user(params): ip = check_param(params, 'ip') city_name = check_param(params, 'city_name') all_area_info = db_user.query_all_area_infos() - ret = db_user.insert_user(modify_userid, password, user_name, area_id_list, all_area_info) + ret = db_user.insert_user(modify_userid, password, user_name, area_id_list, all_area_info, role) if ret: insert_log_ret = db_user.insert_login_log(modify_userid, 4, ip, city_name, userid) if insert_log_ret == 1: diff --git a/test.py b/test.py index d6549e9..5bbd0d8 100644 --- a/test.py +++ b/test.py @@ -7,6 +7,7 @@ import configparser from google.protobuf.json_format import MessageToJson from app.common_worker import generate_date_range, convert_time +from app.eva_common import gen_crossids_roads_dir_dict_by_mysql, check_outside_left from app.global_source import * import proto.xlcomm_pb2 as pb @@ -14,20 +15,20 @@ def init(): config = configparser.ConfigParser() global g_db_pool, g_db_gw config.read('cross_doctor.ini', encoding='utf-8') - net_filename = 'data/xl_roadnet_350300.txt' - roadinfo_filename = 'data/xl_roadinfo_350300.txt' - roadlinks_filename = 'data/xl_roadlinks_350300.txt' + net_filename = 'data/xl_roadnet_130200.txt' + roadinfo_filename = 'data/xl_roadinfo_130200.txt' + roadlinks_filename = 'data/xl_roadlinks_130200.txt' g_roadnet.load_from_file(net_filename) g_roadinfo_manager.load_from_file(roadinfo_filename) g_roadlinks_manager.load_from_file(roadlinks_filename) - if config.has_option('cloud_db', 'host'): - g_cloud_db['host'] = config.get('cloud_db', 'host') - if config.has_option('cloud_db', 'port'): - g_cloud_db['port'] = int(config.get('cloud_db', 'port')) - g_cloud_pool.init_pool(g_cloud_db) - if config.has_option('db', 'host'): - g_dbinfo['host'] = config.get('db', 'host') - g_db_pool.init_pool(g_dbinfo) + # if config.has_option('cloud_db', 'host'): + # g_cloud_db['host'] = config.get('cloud_db', 'host') + # if config.has_option('cloud_db', 'port'): + # g_cloud_db['port'] = int(config.get('cloud_db', 'port')) + # g_cloud_pool.init_pool(g_cloud_db) + # if config.has_option('db', 'host'): + # g_dbinfo['host'] = config.get('db', 'host') + # g_db_pool.init_pool(g_dbinfo) if config.has_option('cross_delay_db', 'host'): g_cross_delay_db['host'] = config.get('cross_delay_db', 'host') if config.has_option('cross_delay_db', 'port'): @@ -37,6 +38,19 @@ def init(): if config.has_option('cross_delay_db', 'password'): g_cross_delay_db['password'] = config.get('cross_delay_db', 'password') print(g_cross_delay_db) + if config.has_option('roadnet_db', 'host'): + host = config.get('roadnet_db', 'host') + g_roadnet_db['host'] = host + if config.has_option('roadnet_db', 'user'): + user = config.get('roadnet_db', 'user') + g_roadnet_db['user'] = user + if config.has_option('roadnet_db', 'password'): + password = config.get('roadnet_db', 'password') + g_roadnet_db['password'] = password + if config.has_option('roadnet_db', 'dbname'): + dbname = config.get('roadnet_db', 'dbname') + g_roadnet_db['db'] = dbname + g_roadnet_pool.init_pool(g_roadnet_db) g_cross_delay_pool.init_pool(g_cross_delay_db) @@ -73,6 +87,67 @@ def check_err_data(): print(len(date_list), len(phase_type_list), row['cont_times']) +def gen_monitor_cross_ledger_info(): + all_crosses = db_tmnet.query_cross_info_by_area_id(130201, 130200) + cross_info_dict = {item['crossid']: item for item in all_crosses} + crossid_list = [item['crossid'] for item in all_crosses] + cross_roads_dir_dict = gen_crossids_roads_dir_dict_by_mysql(crossid_list, 130200) + for crossid in crossid_list: + cross_info_dict[crossid]['roads_dir_dict'] = cross_roads_dir_dict[crossid] + reversed_lanes_crossid = db_tmnet.query_reversed_lanes_crossid(130200) + res = [] + has_right_light_crosses = db_tmnet.check_right_light(130200) + right_list = [item['crossid'] for item in has_right_light_crosses] + + for crossid in crossid_list: + cross_info = cross_info_dict[crossid] + cross_name = cross_info['cross_name'] + cross_no = cross_info['cross_no'] if cross_info['cross_no'] else '未配置' + cross_type_code = cross_info['cross_type'] + right_light = '无' + if crossid in right_list: + right_light = '有' + if cross_type_code == 1: + cross_type = '丁字路口' + elif cross_type_code == 2: + cross_type = '十字路口' + elif cross_type_code == 3: + cross_type = '行人过街路口' + elif cross_type_code == 4: + cross_type = '丁字路口' + else: + cross_type = '其他' + internet_code = cross_info['internet'] + if internet_code == 0: + internet_name = '未配置' + elif internet_code == 1: + internet_name = '联网' + elif internet_code == 2: + internet_name = '脱机' + else: + internet_name = '未联网' + company = cross_info['company'] if cross_info['company'] else '未配置' + bicycle = '是' if cross_info['bicycle_twice_cross_street'] == 1 else '否' + roads_dir_dict = cross_info['roads_dir_dict'] + reversed_status = '是' if crossid in reversed_lanes_crossid else '否' + outside_left, hold_straight, bus_lane, reverse_turn = '否', '否', '否', '否' + for dir in roads_dir_dict: + lane_info_list = roads_dir_dict[dir]['lane_turn_info'].split('|') + if '17' in lane_info_list: + bus_lane = '是' + if roads_dir_dict[dir]['reverse_turn'] == 1: + reverse_turn = '是' + if roads_dir_dict[dir]['hold_straight'] == 1: + hold_straight = '是' + if '' not in lane_info_list and check_outside_left(lane_info_list): + outside_left = '是' + res.append((crossid, cross_name, cross_no, cross_type, internet_name, company, bicycle, reverse_turn, hold_straight, reversed_status, bus_lane, outside_left, right_light)) + for item in res: + print(item) + + return None + + if __name__ == '__main__': init() - check_err_data() \ No newline at end of file + gen_monitor_cross_ledger_info() \ No newline at end of file diff --git a/tool/qcos_func.py b/tool/qcos_func.py new file mode 100644 index 0000000..66709b2 --- /dev/null +++ b/tool/qcos_func.py @@ -0,0 +1,86 @@ +# -*- coding=utf-8 +from qcloud_cos import CosConfig +from qcloud_cos import CosS3Client +import sys +import os +import logging + +# 正常情况日志级别使用 INFO,需要定位时可以修改为 DEBUG,此时 SDK 会打印和服务端的通信信息 +# logging.basicConfig(level=logging.INFO, stream=sys.stdout) + +g_cos_root = 'https://xinglu-1324629296.cos.ap-beijing.myqcloud.com' +g_cos_bucket = 'xinglu-1324629296' + +def get_client(): + # 1. 设置用户属性, 包括 secret_id, secret_key, region等。Appid 已在 CosConfig 中移除,请在参数 Bucket 中带上 Appid。Bucket 由 BucketName-Appid 组成 + # secret_id = os.environ['COS_SECRET_ID'] # 用户的 SecretId,建议使用子账号密钥,授权遵循最小权限指引,降低使用风险。子账号密钥获取可参见 https://cloud.tencent.com/document/product/598/37140 + # secret_key = os.environ['COS_SECRET_KEY'] # 用户的 SecretKey,建议使用子账号密钥,授权遵循最小权限指引,降低使用风险。子账号密钥获取可参见 https://cloud.tencent.com/document/product/598/37140 + """ + SecretId:AKIDFLFvOfjbFi171mLnEXp370rHZozymN2c + SecretKey:a6RYUDl6EAtQmurb8To4AFRCoDOM6g3D + """ + secret_id = 'AKIDFLFvOfjbFi171mLnEXp370rHZozymN2c' + secret_key = 'a6RYUDl6EAtQmurb8To4AFRCoDOM6g3D' + region = 'ap-beijing' # 替换为用户的 region,已创建桶归属的 region 可以在控制台查看,https://console.cloud.tencent.com/cos5/bucket + # COS 支持的所有 region 列表参见https://cloud.tencent.com/document/product/436/6224 + token = None # 如果使用永久密钥不需要填入 token,如果使用临时密钥需要填入,临时密钥生成和使用指引参见 https://cloud.tencent.com/document/product/436/14048 + scheme = 'https' # 指定使用 http/https 协议来访问 COS,默认为 https,可不填 + + config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key, Token=token, Scheme=scheme) + client = CosS3Client(config) + return client + + +def upload_file_to_cos(local_filename: str, cos_path: str): + client = get_client() + # 本地路径 简单上传 + response = client.put_object_from_local_file( + Bucket=g_cos_bucket, + LocalFilePath=local_filename, + Key=cos_path + ) + print(response['ETag']) + return response + + +def get_file_from_cos(cos_path: str, local_filename: str): + """ + 从cos上下载文件 + :param cos_path: + :param local_filename: + :return: + """ + client = get_client() + response = client.get_object( + Bucket=g_cos_bucket, + Key=cos_path + ) + response['Body'].get_stream_to_file(local_filename) + + + +def upload_order_images_to_cos(idx_to_localfile: dict, orderid: str): + """ + 将一组本地图片,上传到对应的cos的订单目录下 + :param idx_to_localfile: + :param orderid: + :return: idx_to_cosfile + """ + xlsyn_cos_host = 'https://xinglu-1324629296.cos.ap-beijing.myqcloud.com' + cos_order_path = '/user/wave_survey/%s' % orderid + idx_to_cosfile = {} + for idx, local_filepath in idx_to_localfile.items(): + image_filename = local_filepath.split('/')[-1] + cos_path = '%s/%s' % (cos_order_path, image_filename) + upload_file_to_cos(local_filepath, cos_path) + cos_file = '%s/%s' % (xlsyn_cos_host, cos_path) + idx_to_cosfile[idx] = cos_file + return idx_to_cosfile + + +if __name__ == '__main__': + idx_to_localfile = {0:'D:/slgwork/slgcode/wave_survey/1739430848000.jpg', + 2:'D:/slgwork/slgcode/wave_survey/1739430851000.jpg'} + idx_to_cosfile = upload_order_images_to_cos(idx_to_localfile, 'slg_orderid') + print(idx_to_cosfile) +