问题描述

在成功的部署Python flask应用到App Service (Windows)后,如果需要把当前项目(如:hiflask)作为一个子项目(子站点),把web.config文件从wwwroot中移动到项目文件夹中。访问时,确遇见了404 Not Found的错误。

查看flask项目的启动日志,可以看见项目启动已经成功。但是为什么请求一直都是404的问题呢?

2021-09-10 05:29:58.224796: wfastcgi.py will restart when files in D:\home\site\wwwroot\hiflask\ are changed: .*((\.py)|(\.config))$
2021-09-10 05:29:58.240445: wfastcgi.py 3.0.0 initialized

问题解决

在搜索 flask return 404问题后,发现是因为 URL前缀(prefixed )的问题。因为当前的flask应用访问路径不再是根目录(/),而是(/hiflask)。 所以需要 flask项目中使用 中间件 来处理 url前缀的问题。

原文内容为:https://stackoverflow.com/questions/18967441/add-a-prefix-to-all-flask-routes/36033627#36033627

ll you have to do is to write a middleware to make the following changes:

  1. modify PATH_INFO to handle the prefixed url.
  2. modify SCRIPT_NAME to generate the prefixed url.

Like this:

class PrefixMiddleware(object):

    def __init__(self, app, prefix=''):
self.app = app
self.prefix = prefix def __call__(self, environ, start_response): if environ['PATH_INFO'].startswith(self.prefix):
environ['PATH_INFO'] = environ['PATH_INFO'][len(self.prefix):]
environ['SCRIPT_NAME'] = self.prefix
return self.app(environ, start_response)
else:
start_response('404', [('Content-Type', 'text/plain')])
return ["This url does not belong to the app.".encode()]

Wrap your app with the middleware, like this:

from flask import Flask, url_for

app = Flask(__name__)
app.debug = True
app.wsgi_app = PrefixMiddleware(app.wsgi_app, prefix='/foo') @app.route('/bar')
def bar():
return "The URL for this page is {}".format(url_for('bar')) if __name__ == '__main__':
app.run('0.0.0.0', 9010)

Visit http://localhost:9010/foo/bar,

You will get the right result: The URL for this page is /foo/bar

而在App Service中的解决方式就是添加了 PrefixMiddleware,并指定prefix为 /hiflask 。 附上完成的hiflask/app.py 代码和web.config内容。

hiflask/app.py

from flask import Flask
from datetime import datetime
from flask import render_template import re class PrefixMiddleware(object):
def __init__(self, app, prefix=''):
self.app = app
self.prefix = prefix def __call__(self, environ, start_response):
if environ['PATH_INFO'].startswith(self.prefix):
environ['PATH_INFO'] = environ['PATH_INFO'][len(self.prefix):]
environ['SCRIPT_NAME'] = self.prefix
return self.app(environ, start_response)
else:
start_response('404', [('Content-Type', 'text/plain')])
return ["This url does not belong to the app.".encode()] #if __name__ =="__name__"
app = Flask(__name__)
app.debug = True
app.wsgi_app = PrefixMiddleware(app.wsgi_app, prefix='/hiflask')
# @app.route("/")
# def home():
# return "Hello, Flask!" print("flask applicaiton started and running..." +datetime.now().strftime("%m/%d/%Y, %H:%M:%S")) # Replace the existing home function with the one below
@app.route("/")
def home():
return render_template("home.html") # New functions
@app.route("/about/")
def about():
return render_template("about.html") @app.route("/contact/")
def contact():
return render_template("contact.html") @app.route("/hello/")
@app.route("/hello/<name>")
def hello_there(name = None):
return render_template(
"hello_there.html",
name=name,
date=datetime.now()
) @app.route("/api/data")
def get_data():
return app.send_static_file("data.json") if __name__ == '__main__':
app.run(debug=True)

hiflask/web.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="WSGI_HANDLER" value="app.app"/>
<add key="PYTHONPATH" value="D:\home\site\wwwroot\hiflask"/>
<add key="WSGI_LOG" value="D:\home\site\wwwroot\hiflask\hiflasklogs.log"/>
</appSettings>
<system.webServer>
<handlers>
<add name="PythonHandler" path="*" verb="*" modules="FastCgiModule" scriptProcessor="D:\home\python364x64\python.exe|D:\home\python364x64\wfastcgi.py" resourceType="Unspecified" requireAccess="Script"/>
</handlers>
</system.webServer>
</configuration>

最终效果(作为子项目部署完成成功,所以一个app service就可以部署多个站点)

提醒一点:App Service中如果要部署多站点,需要在Configration 中配置 Virtual Applications。

参考资料:

https://stackoverflow.com/questions/18967441/add-a-prefix-to-all-flask-routes/36033627#36033627

https://www.cnblogs.com/lulight/p/15220297.html

https://www.cnblogs.com/lulight/p/15227028.html

【Azure 应用服务】Python flask 应用部署在Aure App Service中作为一个子项目时,解决遇见的404 Not Found问题的更多相关文章

  1. 【Azure 应用服务】Python flask 应用部署在Aure App Service 遇见的 3 个问题

    在App Service(Windows)中部署Flask应用时的注意事项: ● 添加Python扩展插件,Python 3.6.4 x64: ●● 配置 FastCGI 处理程序,添加Web.con ...

  2. 【Azure 应用服务】App Service中运行Python 编写的 Jobs,怎么来安装Python包 (pymssql)呢?

    问题描述 在App Service中运行Python编写的定时任务,需要使用pymssql连接到数据库,但是发现使用 python.exe -m pip install --upgrade -r re ...

  3. 【应用服务 App Service】Azure App Service 中如何安装mcrypt - PHP

    问题描述 Azure App Service (应用服务)如何安装PHP的扩展 mcrypt(mcrypt 是php里面重要的加密支持扩展库) 准备条件 创建App Service, Runtime ...

  4. 【应用服务 App Service】当遇见某些域名在Azure App Service中无法解析的错误,可以通过设置指定DNS解析服务器来解决

    问题情形 当访问部署在Azure App Service中的应用返回 "The remote name could not be resolved: ''xxxxxx.com'" ...

  5. 【应用服务 App Service】在Azure App Service中使用WebSocket - PHP的问题 - 如何使用和调用

    问题描述 在Azure App Service中,有对.Net,Java的WebSocket支持的示例代码,但是没有成功的PHP代码. 以下的步骤则是如何基于Azure App Service实现PH ...

  6. 如何将Azure DevOps中的代码发布到Azure App Service中

    标题:如何将Azure DevOps中的代码发布到Azure App Service中 作者:Lamond Lu 背景 最近做了几个项目一直在用Azure DevOps和Azure App Servi ...

  7. 【应用服务 App Service】App Service中抓取网络日志

    问题描述 众所周知,Azure App Service是一种PaaS服务,也就是说,IaaS层面的所有内容都由平台维护,所以使用App Service的我们根本无法触碰到远行程序的虚拟机(VM), 所 ...

  8. 【Azure 应用程序见解】 Application Insights 对App Service的支持问题

    问题描述 Web App 发布后, Application Insights 收集不到数据了 问题分析 在应用服务(App Service)中收集应用的监控数据(如Request,Exception, ...

  9. Azure应用服务+Github实现持续部署

    上次我们介绍了如何使用Azure应用服务(不用虚机不用Docker使用Azure应用服务部署ASP.NET Core程序).我们通过Visual studio新建一个项目后手动编译发布代码.然后通过F ...

随机推荐

  1. shell $? 状态码含义

    Linux 使用了$? 来保存上个执行的命令的退出状态码. 0                命令成功结束 1                通用未知错误 2                误用she ...

  2. 05.表达式目录树Expression

    参考文章 https://www.cnblogs.com/xyh9039/p/12748983.html 1. 基本了解 1.1 Lambda表达式 演变过程 using System; namesp ...

  3. [开源]入坑Qt,我的第一个小程序:MD5计算器

    版权声明 --------- 本文仅在知乎与博客园发布.开发者为szx0427 MFC和Win32搞了好几年了,也算是懂了个皮毛,但是一直觉得用这两者开发软件都很麻烦,需要将大量的代码花费在UI等地方 ...

  4. MySQL-13-日志管理

    常用日志参数 经常用到的有错误.快慢查询.二进制等日志 错误日志 1 作用 记录启动\关闭\日常运行过程中,状态信息,警告,错误,排查MySQL运行过程的故障 2 错误日志配置 默认就是开启的: /数 ...

  5. Vue系列-03-vue-cli自动化工具

    使用Vue-CLI创建项目 安装vue-cli脚手架 Mac安装vue-cli脚手架 lichengguo@lichengguodeMacBook-Pro ~ % sudo npm install - ...

  6. Spring的@PropertySource注解使用

    @PropertySource注解是Spring用于加载配置文件,默认支持.properties与.xml两种配置文件.@PropertySource属性如下: name:默认为空,不指定Spring ...

  7. CobaltStrike去除流量特征

    CobaltStrike去除流量特征 ​普通CS没有做流量混淆会被防火墙拦住流量,所以偶尔会看到CS上线了机器但是进行任何操作都没有反应.这里尝试一下做流量混淆.参考网上的文章,大部分是两种方法,一种 ...

  8. Pikachu-RCE模块

    一.概述 1.1 RCE漏洞 可以让攻击者直接向后台服务器远程注入操作系统命令或者代码,从而控制后台系统. 1.2 远程系统命令执行一般出现这种漏洞,是因为应用系统从设计上需要给用户提供指定的远程命令 ...

  9. Jetpack Compose学习(2)——文本(Text)的使用

    原文: Jetpack Compose学习(2)--文本(Text)的使用 | Stars-One的杂货小窝 对于开发来说,文字最为基础的组件,我们先从这两个使用开始吧 本篇涉及到Kotlin和DSL ...

  10. MeteoInfo-Java解析与绘图教程(三)

    MeteoInfo-Java解析与绘图教程(三) 上文我们说到简单绘制色斑图(卫星云图),但那种效果可定不符合要求,一般来说,客户需要的是在地图上色斑图的叠加,或者是将图片导出分别是这两种效果 当然还 ...