【问题标题】:required to have flask static folder outside of project root需要在项目根目录之外有烧瓶静态文件夹
【发布时间】:2020-01-09 01:07:50
【问题描述】:

我需要将所有静态文件存储在项目文件夹之外。尽管我像下面这样更新了烧瓶配置,但它仍然没有将图像保存在该文件夹中...

app = Flask(__name__, static_folder='../Storage/static', static_url_path='/storage')

但是当我尝试使用以下代码保存文件时,它总是将图像存储在 project_folder->static 中

def save_image(image: FileStorage, folder: str = None, name: str = None) -> str:
    return IMAGE_SET.save(image, folder, name)

需求示例:

当前

project_folder/
               static/
                      images/

需要存储喜欢

Storage(parallel folder)/
               static/
                     images/   

 

请帮忙, 我尝试使用以下链接但没有帮助...

Flask not recognising static folder

How do i link to images not in Static folder in flask

Change static folder from config in Flask

Setting my <img> source to a file path outside of flask static folder

【问题讨论】:

    标签: python flask flask-restful


    【解决方案1】:

    下面是我的测试代码, 文件夹 '../Storage/static/images' 应该在运行代码之前创建或使用 os.makedirs() 先创建:

    import sys,os
    from flask import  Flask
    from werkzeug.datastructures import FileStorage
    file = None
    fp=open('110326-666286.jpg', 'rb')
    file = FileStorage(fp)
    
    app=Flask(__name__)
    app.debug=True
    
    def save_image(image: FileStorage, folder: str = None, name: str = None) -> str:
        if not os.path.exists(folder):
            os.makedirs(folder)
        return image.save(folder+'/'+name)
    
    @app.route('/hello/<name>/<surname>')
    def hello(name,surname):
      save_image(file,'../Storage/static/images','110326-666286_.jpg')
      if os.path.exists('../Storage/static/images'+'/'+'110326-666286_.jpg'):
        res='image saved'
      else:
        res='image not saved'
      return '<h1>hello, %s %s</h1><p>%s</p>'%(name,surname,res)
    
    
    
    if __name__=='__main__':
      app.run(host='127.0.0.1',port=8080)
    

    下面是结果

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-26
      • 2020-04-22
      • 1970-01-01
      • 2011-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多