Skip to main content
 首页 » 编程设计

python之Flask url_for 错误地链接到模板之外的静态页面

2025年05月04日13pander-it

我目前正在将我所有的静态文件移动到 S3,并允许将一些图像上传到我的网站。总的来说,这是非常棒的。我毫不费力地将所有现有的 css 和 js 文件上传到 S3,但是我在上传图像并将它们保存到 S3 时遇到了一些问题。

具体来说,这是我在我的 View 中处理文件上传的方式:

image_file = request.files["imageurl"] 
if image_file and allowed_file(image_file.filename): 
    fn = "products/%s" % secure_filename(image_title + "." + image_file.filename.split(".")[-1]) 
    image_file.save(url_for('static', filename=fn)) 
else: 
    response = app.make_response(render_template( 
        'admin/newImage.html', 
        title=title, 
        error="That Image file is invalid.") 
    ) 
    return response 

它全部包装在 POST 请求处理程序中。这里的问题是 url_for('static') 无法链接到正确的路径,所以每当我尝试保存这样的图像时,我都会得到一个 IOError。

通常我会假设我只是对我的目录结构做了一些愚蠢的事情,但是相同的 url_for 模式对我的静态目录中的文件非常有效。关于如何解决这个问题的任何想法?这是我的目录结构(经过修剪以供查看)

├── SpoolEngine 
│   ├── admin.py 
│   ├── __init__.py 
│   ├── templates 
│   │   ├── admin 
│   │   │   ├── base.html 
│   │   ├── base.html 
│   │   ├── _forms.html 
│   │   ├── posts 
│   │   │   ├── complete.html 
│   │   └── super_user 
│   │       ├── base.html 
│   ├── users.py 
│   └── views.py 
└── static 
    ├── css 
    │   ├── admin.css 
    │   └── zebraTable.css 
    ├── img 
    │   └── subtle_grunge.png 
    ├── js 
    │   ├── compatibility.js 
    │   ├── list.js 
    │   ├── login.js 
    │   └── profiler.js 
    └── products 

作为引用,url_for 在 /static/css 中完美运行,并从 admin.py 链接到错误的 url 有什么想法吗?

请您参考如下方法:

url_for 返回一个 url 路径。不是文件系统路径。

因此,您试图将文件保存在 /static/something 中,对于系统而言,这意味着从文件系统的根目录开始的路径,而不是应用程序路径。

你可以用这样的东西为你的文件创建static路径

static_path_to_save = os.path.join([app.root_path, '/static', fn]) 

请注意,在处理上传时,请记住清理所有路径并仔细检查目的地。最佳实践适用,例如,如果您使用用户提供的 文件名(最好是您生成文件名),则去除斜杠。

在您的代码中,如果 2 个用户上传同名文件并相互覆盖,我也会看到一个问题。但这在您的上下文中可能是安全的。