【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 ...
随机推荐
- solr(CVE-2017-12629)远程命令执行
影响版本Apache Solr 5.5.0到7.0.1版本 solr(CVE-2017-12629-RCE) 环境搭建 1.burp检测 创建listen POST /solr/demo/config ...
- 还在用Postman?来,花2分钟体验下ApiPost的魅力
2分钟玩转APIPOST 本文通过简单介绍如何利用ApiPost调试接口和快速的生成接口文档,让您初步体验ApiPost的魅力! 1. API写完想要测试?试试模拟发送一次请求 新建接口,我想模拟发送 ...
- SQL语句(四)联表查询
目录 一.关联查询的分类 按年代分 按功能分 二.sql92语法的连接 语法 1. 简单应用 2. 为表起别名 3. 加入筛选 4. 加入分组 5. 三表连接 6. 非等值连接 7. 自连接 三.sq ...
- SQL语句(二)数据排序和单行函数
目录 一.排序查询 1. 基本排序 2. 多条件排序 二.单行函数 调用方法 字符函数 ①LENGTH函数 ②CONCAT函数 ③upper 和 lower ④substr ⑤instr ⑥trim ...
- azure bash: az: command not found
https://docs.microsoft.com/en-us/cli/azure/install-azure-cli-linux?pivots=dnf
- (2)用 if语句 区间判断
1 /*此例子只作为演示*/ 2 3 #include <stdio.h> 4 int main() 5 { 6 printf("请问贵公司给出的薪资是:\n"); 7 ...
- Jackson格式化时间和科学计数法问题
1. 首先如果有自定义 WebMvcConfigurer 或者 WebMvcConfigurationSupport 的,一定不要在上面加 @EnableWebMvc 注解,因为这个注解会覆盖掉s ...
- Maven 下载、安装与配置
一.需要准备的东西 确定电脑上已经成功安装JDK 二.下载与安装 1. 前往https://maven.apache.org/download.cgi下载最新版的Maven程序: 注意:Maven3. ...
- DAY04 与用户交 互格式化输出与运算符
与用户交互 输入: input # python2与python3的区别 # python3 res = input('please in put your username>>>& ...
- 将白码平台数据存储到MySQL数据库
概述: 此前在白码平台上搭建并使用系统,若想要将白码平台上搭建的系统的数据存储到自己本地的MySQL数据库中的话,需要将数据导出后再对数据进行处理.如今想要实现这一需求,直接通过使用白码的数据库对接功 ...