【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 ...
随机推荐
- mysql采坑笔记
mysqld --initialize-insecure // 初始化数据 mysql -u root -p // 登录 navicat for mysql 1251错误解决方法 ALTER USER ...
- jquery 阻止表单提交方法
<form name="message_form" action="?m=mobilecenter&c=index&a=service" ...
- Apache OfBiz 反序列化命令执行漏洞(CVE-2020-9496)
影响版本 - Apache Ofbiz:< 17.12.04 访问 https://192.168.49.2:8443/webtools/control/xmlrpc 抓包 进行数据包修改 pa ...
- 大数据学习(21)—— ZooKeeper原理
这一篇我们对zookeeper的主要原理做一个简单介绍.zookeeper的核心原理是zookeeper atomic broadcast(ZAB协议),它来源于paxos协议.这里用通俗易懂的话,介 ...
- IDEA创建Mapper.xml文件识别不成功的问题
在IDEA的maven项目中,创建一个EmpMapper.xml的文件识别不成功,图标显示为文本文档类型,在写代码时也不会弹出提示 解决方法: 在文件->设置->编辑器->文件类型中 ...
- Java的equsals和==
先上结论:在我们常用的类中equals被重写后,作用就是为了比较对象的内容,==是比较对象的内存地址.但并不能说所有的equals方法就是比较对象的内容. Java 中的==: 1.对于对象引用类型: ...
- 干了六年Android开发现在裸辞失业了,再过2个月就30了,该怎么继续生活?
这是我在某论坛看到别人分享的故事,觉得可以展开聊一下,对于我们这些中年程序员,可以裸辞吗? 前言 首先介绍一下主人公的情况.目前所在的是一家小的创业公司,待了3年多,薪资一般吧,之前在一家中型上市企业 ...
- [论文阅读] Residual Attention(Multi-Label Recognition)
Residual Attention 文章: Residual Attention: A Simple but Effective Method for Multi-Label Recognition ...
- Linux 鸟叔的私房菜--完全结束
2018年10月22日 我不想再拖下去了,一本书看不完就无法进行下一本书的阅读,可能算是我的一个强迫症(借口吧) 之前看05年第一版<鸟叔的Linux私房菜>停在脚本语言那里,迟迟没有前进 ...
- java8-stream常用操作(1)
前言 java8的Stream 流式操作,用于对集合进行投影.转换.过滤.排序.去重等,更进一步地说,这些操作能链式串联在一起使用,类似于 SQL 语句,可以大大简化代码.下面我就将平时常用的一些st ...