【Azure 应用服务】Azure App Service (Windows) 使用Flask框架部署Python应用,如何在代码中访问静态文件呢?如何设置文件路径?是相对路径还是绝对路径呢?

问题描述

使用Flask框架部署Python代码,如何访问其中的静态文件呢?如static问价夹中的图像资源,同时如何在代码中读取txt文件中的内容呢?是相对路径或者是绝对路径呢?

实验步骤

在App Service (Windows)环境中部署Flask Python应用时,需要考虑注意参考文档“发布到 Windows 上的 Azure 应用服务”, Python项目的Web.config内容为:

<system.webServer>
  <handlers>
    <add name="PythonHandler" path="*" verb="*" modules="FastCgiModule"
        scriptProcessor="D:homePython361x64python.exe|D:homePython361x64wfastcgi.py"
        resourceType="Unspecified" requireAccess="Script"/>
  </handlers>
</system.webServer>

而特别对于Flash项目,需要添加项目的启动配置:

例如,如果项目命名为“FlaskAzurePublishExample”,则该条目如下所示:

<!-- Flask apps only: change the project name to match your app -->
<add key="WSGI_HANDLER" value="FlaskAzurePublishExample.app"/>

以下的实验是在通过相对路径访问静态图片:

  • 首先项目路径如下(项目发布到Azure后,通过Kudu站点查看项目文件路径)

【Azure 应用服务】Azure App Service (Windows) 使用Flask框架部署Python应用,如何在代码中访问静态文件呢?如何设置文件路径?是相对路径还是绝对路径呢?

    • 静态文件放在了static这个文件夹下
    • test.py运行代码如下:
    • from flask import Flask,render_template
       
      app = Flask(__name__, static_folder='', static_url_path='')
      @app.route('/')
      def index():
          return render_template('index.html')
          
      if __name__ == '__main__':
      app.run()
  • 访问的时候用url_for函数,templates文件夹下的index.html如下:

【Azure 应用服务】Azure App Service (Windows) 使用Flask框架部署Python应用,如何在代码中访问静态文件呢?如何设置文件路径?是相对路径还是绝对路径呢?

  • 测试结果,直接访问站点根目录时可以访问到静态文件

 【Azure 应用服务】Azure App Service (Windows) 使用Flask框架部署Python应用,如何在代码中访问静态文件呢?如何设置文件路径?是相对路径还是绝对路径呢?

以上是通过HTML访问项目中的静态资源文件,如果是需要通过代码的方式读取txt文件中的内容,由于可能存在发布后的相对路径与本地测试时候路径不一致,所以建议使用部署在App Service中的绝对路径。如:open(‘D:/hone/site/wwwroot/static/test.txt’,’r’)  

但如果一定需要使用相对路径,这可以考虑使用App Service Home路径的环境变量,如:open(‘%HOME%/site/wwwroot/static/test.txt,’r’) 。

参考资料

发布到 Windows 上的 Azure 应用服务https://docs.microsoft.com/zh-cn/visualstudio/python/publish-to-app-service-windows?view=vs-2019#publish-to-app-service---visual-studio-2017-and-later