【Azure 应用服务】Python flask 应用部署在Aure App Service中作为一个子项目时,解决遇见的404 Not Found问题
问题描述
在成功的部署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:
- modify
PATH_INFOto handle the prefixed url.- modify
SCRIPT_NAMEto 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问题的更多相关文章
- 【Azure 应用服务】Python flask 应用部署在Aure App Service 遇见的 3 个问题
在App Service(Windows)中部署Flask应用时的注意事项: ● 添加Python扩展插件,Python 3.6.4 x64: ●● 配置 FastCGI 处理程序,添加Web.con ...
- 【Azure 应用服务】App Service中运行Python 编写的 Jobs,怎么来安装Python包 (pymssql)呢?
问题描述 在App Service中运行Python编写的定时任务,需要使用pymssql连接到数据库,但是发现使用 python.exe -m pip install --upgrade -r re ...
- 【应用服务 App Service】Azure App Service 中如何安装mcrypt - PHP
问题描述 Azure App Service (应用服务)如何安装PHP的扩展 mcrypt(mcrypt 是php里面重要的加密支持扩展库) 准备条件 创建App Service, Runtime ...
- 【应用服务 App Service】当遇见某些域名在Azure App Service中无法解析的错误,可以通过设置指定DNS解析服务器来解决
问题情形 当访问部署在Azure App Service中的应用返回 "The remote name could not be resolved: ''xxxxxx.com'" ...
- 【应用服务 App Service】在Azure App Service中使用WebSocket - PHP的问题 - 如何使用和调用
问题描述 在Azure App Service中,有对.Net,Java的WebSocket支持的示例代码,但是没有成功的PHP代码. 以下的步骤则是如何基于Azure App Service实现PH ...
- 如何将Azure DevOps中的代码发布到Azure App Service中
标题:如何将Azure DevOps中的代码发布到Azure App Service中 作者:Lamond Lu 背景 最近做了几个项目一直在用Azure DevOps和Azure App Servi ...
- 【应用服务 App Service】App Service中抓取网络日志
问题描述 众所周知,Azure App Service是一种PaaS服务,也就是说,IaaS层面的所有内容都由平台维护,所以使用App Service的我们根本无法触碰到远行程序的虚拟机(VM), 所 ...
- 【Azure 应用程序见解】 Application Insights 对App Service的支持问题
问题描述 Web App 发布后, Application Insights 收集不到数据了 问题分析 在应用服务(App Service)中收集应用的监控数据(如Request,Exception, ...
- Azure应用服务+Github实现持续部署
上次我们介绍了如何使用Azure应用服务(不用虚机不用Docker使用Azure应用服务部署ASP.NET Core程序).我们通过Visual studio新建一个项目后手动编译发布代码.然后通过F ...
随机推荐
- 正则:支持6-20位数字、字母和特殊字符(仅限!@#$%^&*())
checkpwd(newpsd); function checkpwd() { var newpsd = $(":input[name='newpsd']").val(); var ...
- 一个故事看懂HTTPS
我是一个浏览器,每到夜深人静的时候,主人就打开我开始学习. 为了不让别人看到浏览记录,主人选择了"无痕模式". 但网络中总是有很多坏人,他们通过抓包截获我和服务器的通信,主人干了什 ...
- Java ParallelStream
ParallelStream 处理数据 Stream 接口提供了parallelStream方法来将集合转换为并行流.即将一个集合分为多个数据块,并用不同的线程分别处理每个数据块的流. 并且使用par ...
- Java 执行控制流程
1.带标签的break会中断并跳出标签所指的循环: 2.带标签的continue会中断本次循环,并开始标签所指处循环的下一轮循环.
- TCP实现聊天
TCP实现聊天 IO流关闭是简写的,正常写要判断是否为null 客户端:(最好捕获异常) 1.连接服务器Socket 2.发送消息 package net.TCPChat; import java.i ...
- String s="a"+"b"+"c",到底创建了几个对象?
首先看一下这道常见的面试题,下面代码中,会创建几个字符串对象? String s="a"+"b"+"c"; 如果你比较一下Java源代码和反 ...
- docker-01
Docker介绍 1 什么是容器? Docker 是一个开源的应用容器引擎,基于 Go 语言 并遵从 Apache2.0 协议开源 Docker 可以让开发者打包他们的应用以及依赖包到一个轻量级.可移 ...
- SpringBoot开发九-生成验证码
需求介绍-生成验证码 先生成随机字符串然后利用Kaptcha API生成验证图片 代码实现 先在pom.xml引入 <dependency> <groupId>com.gith ...
- 017 PCIe总线的事务层(一)
一.PCIe总线的事务层 事务层是PCIe总线层次结构的最高层,该层次将接收PCIe设备核心层的数据请求,并将其转换为PCIe总线事务,PCIe总线使用的这些总线事务在TLP头中定义.PCIe总线继承 ...
- DI 原理解析 并实现一个简易版 DI 容器
本文基于自身理解进行输出,目的在于交流学习,如有不对,还望各位看官指出. DI DI-Dependency Injection,即"依赖注入":对象之间依赖关系由容器在运行期决定, ...