Skip to content

AstFile 文件对象

什么是 AstFile?

AstFile 是 AsyncTest 在自定义脚本中提供的 文件操作对象,用于加载、保存和管理文件。

AstFile 可以单独使用,也可以与 AstExcel 结合使用来处理 Excel 文件。

你可以通过 at.AstFile() 创建一个文件对象。


基本用法

python
# 创建文件对象
ast_file = at.AstFile()

加载文件

load()

从 BytesIO 对象加载文件

python
ast_file.load(file, filename)

参数:

  • file: BytesIO 文件对象
  • filename: 文件名(字符串)

返回值:

示例:

python
from io import BytesIO

# 创建一个 BytesIO 对象
file_data = BytesIO(b"hello world")

# 加载文件
ast_file = at.AstFile()
ast_file.load(file_data, "test.txt")

load_from_system()

异步方法 - 从 AsyncExecutor 系统中加载已有文件

python
await ast_file.load_from_system(filename, cover_file=False)

参数:

  • filename: 系统中的文件名
  • cover_file: 是否覆盖原始文件(默认 False

返回值: AstFile 对象本身(支持链式调用)

示例:

python
# 从系统加载文件
ast_file = at.AstFile()
await ast_file.load_from_system("data.csv")

# 加载并标记覆盖原始文件
ast_file = at.AstFile()
await ast_file.load_from_system("config.json", cover_file=True)

注意: 如果系统中找不到该文件,会抛出 RuntimeError 异常。


保存文件

save()

异步方法 - 保存文件到临时目录,并返回文件唯一标识

python
object_unique_key = await ast_file.save(file)

参数:

  • file: BytesIO 文件对象

返回值: 文件唯一标识(字符串),可用于在全局上下文中引用该文件

示例:

python
from io import BytesIO

ast_file = at.AstFile()
await ast_file.load_from_system("template.txt")

# 修改文件内容后保存
new_content = BytesIO(b"new content")
unique_key = await ast_file.save(new_content)
print(f"文件唯一标识: {unique_key}")

# 可以将 unique_key 保存到临时变量,供后续步骤使用
at.temp.set("file_key", unique_key)

释放文件

close()

释放内存中的文件字节数据

python
ast_file.close()

返回值:

示例:

python
# 文件使用完毕后释放内存
ast_file.close()

文件属性

属性类型说明
fileBytesIO / None文件对象
filepathstr文件路径
filenamestr文件名
cover_filebool是否覆盖原始文件

完整使用示例

从系统加载文件并保存修改

python
from io import BytesIO

# 从系统加载文件
ast_file = at.AstFile()
await ast_file.load_from_system("original.txt")

# 读取原始内容
original_content = ast_file.file.read()
print(f"原始内容: {original_content}")

# 修改内容并保存
new_content = BytesIO(b"modified content")
unique_key = await ast_file.save(new_content)
print(f"文件唯一标识: {unique_key}")

# 释放内存
ast_file.close()

创建新文件

python
from io import BytesIO
import json

# 创建文件对象
ast_file = at.AstFile()

# 构造文件内容
data = {"name": "sheldon", "age": 18}
file_content = BytesIO(json.dumps(data).encode("utf-8"))

# 加载并保存
ast_file.load(file_content, "user_data.json")
unique_key = await ast_file.save(file_content)

at.temp.set("json_file_key", unique_key)

配合 request 对象更新上传文件

python
# 从系统加载文件
ast_file = at.AstFile()
await ast_file.load_from_system("avatar.png")

# 修改文件后保存,获取唯一标识
new_avatar = BytesIO(b"...")  # 新的文件内容
unique_key = await ast_file.save(new_avatar)

# 使用 unique_key 更新请求中的文件
await at.request.async_update_body_file("avatar", unique_key)

注意事项

  • load_from_system()save() 是异步方法,需要使用 await
  • load()close() 是同步方法,无需 await
  • save() 返回的唯一标识可用于 at.request.async_update_body_file() 中引用文件
  • 文件使用完毕后建议调用 close() 释放内存
  • cover_file=True 时会覆盖系统中的原始文件,请谨慎使用

总结

AstFile 提供了完整的文件操作能力:

  • 通过 at.AstFile() 创建文件对象
  • 支持从 BytesIO 或系统文件加载
  • 保存后返回唯一标识,可在全局上下文中引用
  • 可单独使用,也可与 AstExcel 结合处理 Excel 文件