flask 不能访问/login
一 问题Not FoundThe requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.在学习flask 时,需要定义登录页面,路由函数很自然定义为如下:@app.route("/login/", methods=['GE
一 问题
Not Found
The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.
在学习flask 时,需要定义登录页面,路由函数很自然定义为如下:
@app.route("/login", methods=['GET', 'POST'])
写好路由函数后,访问页面,发现却是:
源码如下:
@app.route("/login", methods=['GET', 'POST'])
def login():
return render_template('login.html', title='Sign In')
二 解决思路
尝试在百度上解决问题,很遗憾,搜索能力有限,没有找到,尝试思考是不是url_map中没有加入这个路由和视图函数,便尝试打印输出:
if __name__ == '__main__':
# 通过url_map可以查看整个flask中的路由信息
print(app.url_map)
# 启动flask程序
app.run(debug=True)
结果如下:
没有问题,它有的,只是不能访问。想要放弃时,gg一下吧
结果还真找到了,把@app.route("/login", methods=['GET', 'POST'])中"/login"变为"/login/" 或者 "/loginxxx"
When I type /login as url,it will go wrong
For example:
from flask import Flask ,url_for,render_template,request
app = Flask(__name__)
@app.route('/login')
def index():
return "index"
if __name__== "__main__":
app.run()
The error turn out to be like this:
Not Found.
The requested URL was not found on the server.
When I replace /login with /login/ or any other words like /log , it will be all right. How does that happen?
三 进一步思考 ,why?
为什么‘/index’可以,而‘/login’会无法访问呢
在flask 文档解释是:
规范URL带有斜杠。 它类似于文件系统中的文件夹或者目录。 如果您访问的URL不带斜杠,Flask会将您重定向到带斜杠的规范URL(/login不能访问的原因)。
about路由 URL不带斜杠。 它类似于文件的路径名。 使用斜杠访问URL会产生404“未找到”错误。 这有助于使这些资源的URL保持唯一,从而有助于搜索引擎避免对同一页面进行两次索引。
不过,我觉得还是解释不够,那为什么/index 或者 /hello又能访问呢?如下:
@app.route('/index')
def index():
return 'Index Page'
@app.route('/hello')
def hello():
return 'Hello, World'
看了不同的人的观点:
感觉解释都很牵强,还是没能回答好第二个问题
自己理解
‘/login’是内置的路由,
在自己写时需要与之不同,
所以我们用‘/login2’, ‘/login3’,‘/login4’, ‘/login/都能访问成功
抓规律,接特殊 ‘/login’是内置的路由 以后在遇到类似情况,慢慢加入进来这个特殊池
欢迎有想法的同行在下方讨论,(主要实质发生了什么,我也没搞明白,只能解决问题)
更多推荐
所有评论(0)