This commit is contained in:
xinzish
2025-08-16 09:21:05 +08:00
3 changed files with 12 additions and 98 deletions

101
main.py
View File

@@ -144,44 +144,6 @@ redis_client = redis.Redis(host="localhost", port=6379, db=0)
# influx_org_name = influxdb_info.org # influx_org_name = influxdb_info.org
# influx_client = InfluxDBClient(url=influx_url, token=influx_token, org=influx_org_name, timeout=100*1000) # 100 seconds # influx_client = InfluxDBClient(url=influx_url, token=influx_token, org=influx_org_name, timeout=100*1000) # 100 seconds
def setup_logger():
# 创建日志目录
log_dir = "logs"
os.makedirs(log_dir, exist_ok=True)
# 配置基础日志格式
log_format = "%(asctime)s - %(levelname)s - %(message)s"
formatter = logging.Formatter(log_format)
# 创建主 Logger
logger = logging.getLogger()
logger.setLevel(logging.INFO) # 全局日志级别
# --- 1. 按日期分割的日志文件 Handler ---
log_file = os.path.join(log_dir, "fastapi.log")
file_handler = TimedRotatingFileHandler(
filename=log_file,
when="midnight", # 每天午夜轮转
interval=1,
backupCount=7,
encoding="utf-8"
)
file_handler.suffix = "fastapi-%Y-%m-%d.log" # 文件名格式
file_handler.setFormatter(formatter)
file_handler.setLevel(logging.INFO) # 文件记录所有级别日志
# --- 2. 控制台实时输出 Handler ---
console_handler = logging.StreamHandler() # 默认输出到 sys.stderr (控制台)
console_handler.setFormatter(formatter)
console_handler.setLevel(logging.INFO) # 控制台仅显示 INFO 及以上级别
# 将 Handler 添加到 Logger
logger.addHandler(file_handler)
# logger.addHandler(console_handler)
return logger
logger = setup_logger()
# 配置 CORS 中间件 # 配置 CORS 中间件
app.add_middleware( app.add_middleware(
@@ -197,62 +159,8 @@ lock_simulation = Value('i', 0)
app.add_middleware(GZipMiddleware, minimum_size=1000) app.add_middleware(GZipMiddleware, minimum_size=1000)
logger = logging.getLogger()
async def receive_with_body(body: bytes) -> Receive: logger.setLevel(logging.INFO)
async def receive() -> dict:
return {
"type": "http.request",
"body": body,
"more_body": False,
}
return receive
@app.middleware("http")
async def log_requests(request: Request, call_next):
if request.url.path == "/favicon.ico":
return Response(status_code=204)
# 记录接收请求的时间
request_time = time.time()
request_time_str = datetime.fromtimestamp(request_time).strftime('%Y-%m-%d %H:%M:%S')
# 判断是否为文件上传
is_file_upload = request.headers.get("content-type", "").startswith("multipart/form-data")
# 记录接收的请求数据
logger.info(f"Received request: {request.method} {request.url} at {request_time_str}")
if not is_file_upload:
request_body = await request.body()
logger.info(f"Request body: {request_body.decode('utf-8')}")
# 创建新的 Request 对象,传递缓存的请求体
receive = await receive_with_body(request_body)
request = Request(request.scope, receive=receive)
else:
logger.info(f"Request body: File")
# 处理请求
response = await call_next(request)
# 记录发送响应的时间
response_time = time.time()
response_time_str = datetime.fromtimestamp(response_time).strftime('%Y-%m-%d %H:%M:%S')
processing_time = response_time - request_time
# 记录发送的响应数据
# response_body = b""
# async for chunk in response.body_iterator:
# response_body += chunk
# 记录响应的状态码以及是否成功
success_status = response.status_code < 400
logger.info(f"Response status: {response.status_code} at {response_time_str}, success: {success_status}")
# logging.info(f"Response body: {response_body.decode('utf-8')}")
logger.info(f"Processing time: {processing_time:.3f} seconds")
return response
@app.on_event("startup") @app.on_event("startup")
async def startup_db(): async def startup_db():
@@ -2915,8 +2823,9 @@ async def fastapi_run_simulation_manually_by_date(data: Run_Simulation_Manually_
thread.start() thread.start()
# thread.join() # thread.join()
matched_keys = redis_client.keys(f"*{item['simulation_date']}*") # DingZQ 08152025
redis_client.delete(*matched_keys) # matched_keys = redis_client.keys(f"*{item['simulation_date']}*")
# redis_client.delete(*matched_keys)
############################################################ ############################################################

View File

@@ -51,12 +51,12 @@ Password Tjwater@123456
Organizatio TJWATEORG Organizatio TJWATEORG
Bucket TJWATERBUCKET Bucket TJWATERBUCKET
API Token : cpuAmRnJqSMd7F34q1VjG6JgwZfO0S0w0vK2ZmAvA6zvf6m-6UAobUKSW3xhGr_nxZI5HsFlpfZHT1i8sI3LyQ== API Token : LsqvuqtBqtBv44z_CWh5bWfn9hs1QKcYu5kWahF_cdF6JyqtwuUxU5CK7HWP7BOtP5_2f5mjx76qXyuPLOHWdw==
influx config create --config-name onboarding ` influx config create --config-name onboarding `
--host-url "http://localhost:8086" ` --host-url "http://localhost:8086" `
--org "TJWATERORG" ` --org "TJWATERORG" `
--token "cpuAmRnJqSMd7F34q1VjG6JgwZfO0S0w0vK2ZmAvA6zvf6m-6UAobUKSW3xhGr_nxZI5HsFlpfZHT1i8sI3LyQ==" ` --token "LsqvuqtBqtBv44z_CWh5bWfn9hs1QKcYu5kWahF_cdF6JyqtwuUxU5CK7HWP7BOtP5_2f5mjx76qXyuPLOHWdw=="
--active --active
@@ -83,6 +83,8 @@ Setup instructions for WMH's work
4submit_risk_probability_result 4submit_risk_probability_result
5pressure_sensor_placement_sensitivity 5pressure_sensor_placement_sensitivity
6. In times table, all time values should be the format "hh:mm::ss"
NOTES: NOTES:
1. SCADA设备的时候单位要转换现在模拟算出来的单位是L/sSCADA数据是m3/hL/s要乘3.6才是m3/h 1. SCADA设备的时候单位要转换现在模拟算出来的单位是L/sSCADA数据是m3/hL/s要乘3.6才是m3/h
2. 之前的SCADA压力应该转过了SCADA数据的单位是MPa要乘以100才是m 2. 之前的SCADA压力应该转过了SCADA数据的单位是MPa要乘以100才是m

View File

@@ -593,6 +593,9 @@ def run_simulation(name: str, simulation_type: str, modify_pattern_start_time: s
# 打开数据库 # 打开数据库
open_project(name_c) open_project(name_c)
dic_time = get_time(name_c) dic_time = get_time(name_c)
print(dic_time)
# 获取水力模拟步长0:15:00 # 获取水力模拟步长0:15:00
globals.hydraulic_timestep = dic_time['HYDRAULIC TIMESTEP'] globals.hydraulic_timestep = dic_time['HYDRAULIC TIMESTEP']
# 将时间字符串转换为 timedelta 对象 # 将时间字符串转换为 timedelta 对象