file_get_contents读取不到session的原因

本文探讨了在PHP中使用file_get_contents读取包含session的文件时遇到的问题及原因。当同时使用这两个功能时,可能会出现由于句柄未正确关闭而导致的阻塞现象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

例如有两个文件:

 

test1.php:

test2.php:

但是会发现test1.php的file_get_contents根本都读取不到test2.php的session.

 

原因如下:

file_get_contents,文件操作时需要打开句柄

默认的session是文件,也是需要打开一个句柄的

由于先打开句柄的那个没有关闭句柄,所以就造成了这种"阻塞"现象....

 

@router.post(path='/ledgers/upload', description='互锁台账上传') async def _(files: List[UploadFile] = File(...)): # 获取当前用户ID user_id = CTX_USER_ID.get() log_user_id = user_id if user_id else 0 # 初始化结果集 results = [] total_records = 0 success_files = 0 print('互锁台账上传逻辑') for file in files: print(file.filename) file_result = { "filename": file.filename, "status": "pending", "records": 0, "errors": [] } try: # 1. 验证文件类型 if not file.filename.lower().endswith(('.xlsx', '.xls')): raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="仅支持.xlsx和.xls格式的Excel文件" ) # 2. 读取Excel文件 contents = await file.read() df = pd.read_excel(contents) print(df.columns) # 3. 验证列名是否匹配 missing_required = [cn for cn in REQUIRED_COLUMNS if cn not in df.columns] if missing_required: file_result["errors"].append(f"缺少必填列: {', '.join(missing_required)}") file_result["status"] = "failed" results.append(file_result) continue other_missing = [cn for cn in df.columns if cn not in COLUMN_MAPPING] if other_missing: file_result["warnings"] = [f"忽略未定义列: {', '.join(other_missing)}"] # 5. 重命名列(中文→英文) df.rename(columns=COLUMN_MAPPING, inplace=True) # 6. 处理空值 df.replace({np.nan: None}, inplace=True) # 7. 必填字段空值检查 required_fields_en = [COLUMN_MAPPING[col] for col in REQUIRED_COLUMNS] for index, row in df.iterrows(): for col in required_fields_en: if row[col] is None or str(row[col]).strip() == "": error_msg = f"第{index + 2}行: '{col}'不能为空" file_result["errors"].append(error_msg) # 8. 数据验证和转换 valid_records = [] # 存储(行索引, 记录)的列表 for index, row in df.iterrows(): try: record = InterLockLedgerCreate(**row.to_dict()) valid_records.append((index, record)) # 记录行索引和记录 except ValidationError as e: error_msg = f"第{index + 2}行数据错误: {str(e)}" file_result["errors"].append(error_msg) # 9. 批量保存到数据库 saved_count = 0 print(f"valid_records:{valid_records}") for index, record in valid_records: print(f"record:{record}") try: await interlockledger_controller.create(obj_in=record) except Exception as e: # 捕获所有保存时的异常 error_msg = f"第{index + 2}行数据保存失败: {str(e)}" file_result["errors"].append(error_msg) saved_count += 1 # 10. 更新该文件的上传结果 file_result["records"] = saved_count if file_result["errors"]: if saved_count > 0: file_result["status"] = "partial" else: file_result["status"] = "failed" else: file_result["status"] = "success" results.append(file_result) total_records += saved_count if saved_count > 0: success_files += 1 # 记录日志(每个文件处理完后记录?但原代码是在循环内记录,这里我们保持原样,即每个文件处理完记录一次) await insert_log( log_type=LogType.UserLog, log_detail_type=LogDetailType.InterLockLedgerUpload, by_user_id=log_user_id, ) except HTTPException as e: file_result["status"] = "failed" file_result["errors"].append(str(e.detail)) results.append(file_result) except Exception as e: file_result["status"] = "failed" file_result["errors"].append(f"系统错误: {str(e)}") results.append(file_result) # 构建最终响应 response_data = { "total_files": len(files), "success_files": success_files, "total_records": total_records, "details": results } print(response_data) return Success(msg="Upload Successfully", data=response_data) await interlockledger_controller.create(obj_in=record)无异常时 saved_count才能加1
最新发布
07-18
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值