我正在使用SQLGQUALY-file包FilField将文件保存在本地存储中,它正在保存,但不允许给出自定义文件名,自动将文件保存为未命名.我需要解决这个问题.

我正在研究FastAPI项目并使用如下所示的文件变量来保存文件

class UserDoc(Base):
    __tablename__ = "user_doc"

    id = Column(Integer, primary_key=True)
    file = Column(FileField)

这是我保存文件的方式

@router.post(
    "doc_upload"
)
async def document_upload(
    user_file: UploadFile = File(...),
    db: Session = Depends(deps.get_db),
    current_user: dict = Depends(get_current_user_via_jwt),
):
    try:
        # code logic
        file_contents = await user_file.read()
        document_data = {"file": file_contents}
        db_document = UserDocument(**document_data)
        db.add(db_document)
        db.commit()
        db.refresh(db_document)
    except Exception as _:
        # exception logic

文件内容存储在数据库中为

{
   "content_path":null,
   "filename":"unnamed",
   "content_type":"application/octet-stream",
   "size":267226,
   "files":[
      "upload_folder/121e7cbf-f19c-4538-8fcf-2f323f31e53e"
   ],
   "file_id":"121e7cbf-f19c-4538-8fcf-2f323f31e53e",
   "upload_storage":"upload_folder",
   "uploaded_at":"2024-04-19T05:21:35.429745",
   "path":"upload_folder/121e7cbf-f19c-4538-8fcf-2f323f31e53e",
   "url":"/base_path/upload_folder/121e7cbf-f19c-4538-8fcf-2f323f31e53e",
   "saved":true
}

因此,当我try 下载它给我的未命名文件时,我想用名称保存它.

推荐答案

你必须像File(content=file_contents, filename="some file name here")一样使用sqlalchemy_file.File

对你已经拥有的东西进行改变.

from sqlalchemy_file import File

file_contents = await user_file.read()

document_data = {"file": File(content=file_contents, filename="some file name here")}
db_document = UserDocument(**document_data)
db.add(db_document)
db.commit()

Python相关问答推荐

使用pandas、matplotlib和Yearbox绘制时显示错误的年份

仅从风格中获取 colored颜色 循环

Pandas 第二小值有条件

使用SciPy进行曲线匹配未能给出正确的匹配

对某些列的总数进行民意调查,但不单独列出每列

如何避免Chained when/then分配中的Mypy不兼容类型警告?

处理带有间隙(空)的duckDB上的重复副本并有效填充它们

如何在WSL2中更新Python到最新版本(3.12.2)?

对象的`__call__`方法的setattr在Python中不起作用'

在pandas中使用group_by,但有条件

无法连接到Keycloat服务器

基于形状而非距离的两个numpy数组相似性

关于两个表达式的区别

Python—为什么我的代码返回一个TypeError

numpy数组和数组标量之间的不同行为

使用SQLAlchemy从多线程Python应用程序在postgr中插入多行的最佳方法是什么?'

来自Airflow Connection的额外参数

正在try 让Python读取特定的CSV文件

如何在PYTHON中向单元测试S Side_Effect发送额外参数?

是否将Pandas 数据帧标题/标题以纯文本格式转换为字符串输出?