# -*- coding: utf-8 -*-
# ====> 公共工具 <==== #
import json
import os
import random
import re
import socket
import string
import subprocess
import time
from datetime import datetime
from flask import jsonify
from common.log import logger as lg
# 生成长度为n的随机编码
def generate_random_code(length):
letters_and_digits = string.ascii_lowercase + string.digits # 字母和数字
return ''.join(random.choice(letters_and_digits) for _ in range(length))
# 查看端口是否占用, 警告:会产生一些TIME_AWAIT进程
def is_port_in_use(port):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
return s.connect_ex(('127.0.0.1', port)) == 0
# 查看端口是否占用, win专用
def check_port(l_port):
result = subprocess.run(('netstat', '-ano'), capture_output=True, text=True,
creationflags=subprocess.CREATE_NO_WINDOW)
output = result.stdout
lines = output.split('\n')
for line in lines:
if str(l_port) in line and 'LISTENING' in line: # 注意,这里要确保状态是 LISTENING 才表示端口被占用
return True
return False
# json对象数组转表格
def extract_json_array(json_data):
# 读取json对象数组
data = json.loads(json_data)
# 提取一个对象的所有键作为表头
headers = list(data[0].keys())
# 将所有对象的值作为表内容
content = [list(d.values()) for d in data]
# 组合成二维数组
result = [headers] + content
return result
def write_f(path, content):
lg.info(f'写入文件{path}, 文本长度:{len(content)}')
os.makedirs(os.path.dirname(path), exist_ok=True)
# 打开一个新的文本文件,如果文件不存在将会自动创建
file = open(path, "w")
# 写入内容到文件
file.write(content)
# 关闭文件
file.close()
# 读取文件
def read_f(path):
rs = ''
with open(path, 'r') as file:
rs = file.read()
return rs
def read_f_all(path):
try:
with open(path, 'r', encoding='utf-8', errors='ignore') as f:
text = f.read()
except Exception:
try:
with open(path, 'r', encoding='gbk') as f:
text = f.read()
except Exception:
try:
text = read_f(path)
except Exception:
try:
text = read_f_8(path)
except Exception:
text = '读取文件出错'
lg.error("读取文件出错: ", exc_info=True)
return text
# 读取文件
def read_f_8(path):
with open(path, 'r', encoding='utf-8') as file:
rs = file.read()
return rs
def tail_f(path, lines=100):
with open(path, 'r', encoding='utf-8', errors='ignore') as f:
rs = f.readlines()
if lines >= len(rs):
lines = len(rs) - 1
return '\n'.join(rs[-lines:])
# 获取年月日
def get_datetime():
now = datetime.now()
year = now.year
month = now.month
day = now.day
return year, month, day
# 根据key获取map的value
def get_v(c, key, default=""):
if key in c:
return c[key]
else:
return default
def make_api_response_success(data=None):
rs = {
'success': True,
'msg': '',
'code': 200,
'data': data
}
return jsonify(rs)
def make_api_response_failed(data=None):
rs = {
'success': False,
'msg': '',
'code': 400,
'data': data
}
return jsonify(rs)
def make_api_response(success=True, code=200, data=None, msg=None):
rs = {
'success': success,
'msg': msg,
'code': code,
'data': data
}
return jsonify(rs)
# 构建stream响应结果(成功)
def make_stream_success_response(success=True, msg=''):
msg = {
'success': success,
'msg': msg
}
return json.dumps(msg, ensure_ascii=False)
# 构建stream响应结果(失败)
def make_stream_failed_response(success=False, msg=''):
msg = {
'success': success,
'msg': msg
}
lg.warn(f'处理出错, msg:{msg}')
return json.dumps(msg, ensure_ascii=False)
def get_now():
# 获取当前日期和时间
current_datetime = datetime.now()
# 将日期和时间格式化为字符串
formatted_datetime = current_datetime.strftime('%Y-%m-%d %H:%M:%S')
return formatted_datetime
def make_response(code=200, replay_msg='', replay_time=0, type=0, msg=''):
msg = {
'code': code,
'msg': msg,
'data': {
'type': type,
'replay_time': replay_time,
'replay_msg': replay_msg,
'replay_debug': ''
}}
return msg
# 生成图表
def extract_json(response):
'''抽取由```json```包裹的图形'''
pattern = r"```json(.*?)(?=```|$)" # 非贪婪匹配 到下一个### 或###一直到末尾
match = re.search(pattern, response, re.DOTALL)
if match:
return match.group(1) # 返回第一个匹配项的内容
return None
# 判断是否图片
def is_image_file(file_path):
image_extensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.svg'] # 添加其他可能的图片文件扩展名
file_ext = file_path.splite('.')[-1].lower()
if file_ext in image_extensions:
return True
else:
return False
# 判断是否为数值
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
# 判断是否为json
def is_valid_json(string):
try:
j = json.loads(string)
if isinstance(j, list):
return True
else:
j.keys()
return True
except Exception:
return False
# 判断是否为json数组
def is_json_array(my_json):
try:
json_object = json.loads(my_json)
if isinstance(json_object, list):
return True
else:
return False
except Exception as e:
return False
# 计算耗时
def get_hao_shi(st):
return round(time.time() - st, 2)
def generate_random_code(length):
characters = string.ascii_lowercase + string.digits # 使用ascii_lowercase获取小写字母,digits获取数字
code = ''.join(random.choice(characters) for _ in range(length)) # 从字符集中随机选择生成指定长度的随机编码
return code
def get_time_int():
current_time_float = time.time() # 获取当前时间的浮点数时间戳
current_time_int = int(current_time_float)
return str(current_time_int)
def generate_time_random_code(length):
return get_time_int() + generate_random_code(length)
def is_date_time_format(date_string):
try:
# 尝试解析日期时间字符串
datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S')
return True
except Exception:
return False
if __name__ == '__main__':
s1 = '{"name": "Alice", "age": 30}'
s11 = '[{"name": "Alice", "age": 30}]'
s2 = '{"name": "Bob", invalid_key: "value"}'
s3 = 'not a json string'
print(is_valid_json(s1))
print(is_valid_json(s11))
print(is_valid_json(s2))
print(is_valid_json(s3))
python(17) : 公共工具函数
于 2024-12-03 09:23:47 首次发布
1268

被折叠的 条评论
为什么被折叠?



