如何能使每一个跳转都是一个绝对的url,这里需要使用url管理器。
在common/lib下新建一个UrlManager.py,定义一个UrlManager的类:
# _*_ coding:utf-8 _*_
from application import app
class UrlManager():
@staticmethod
def builder(path):
config_domain = app.config['DOMAIN']
return "%s%s"%(config_domain['www'],path)
@staticmethod
def buildStaticUrl(path):
path = "/static"+path
return UrlManager.builder(path)
这里的config信息需要在配置文件中添加一下,因为不同的环境可能存在不一样的情况,这里在local的配置文件中添加一下:但是实际上我这里在local_setting.py 加了并没有用,是Windows环境,提示找不到这个环境变量,我是把环境变量的ops_config定义为了local了。
# _*_ coding:utf-8 _*_
from base_setting import *
# 下面自由发挥
DOMAIN = {
'www':'http://127.0.0.1:5000'
}
然后,需要在注册文件register.py中添加相关信息,这里使用到了全局函数add_template_global:
from controllers.index import index_page
from controllers.member import member_page
from application import app
from interceptor.auth import *
from interceptor.errorhandler import *
# from flask_debugtoolbar import DebugToolbarExtension
# toolbar = DebugToolbarExtension(app)
app.register_blueprint(index_page,url_prefix='/learning')
app.register_blueprint(member_page,url_prefix='/member')
from controllers.UrlManager import UrlManager
app.add_template_global(UrlManager.builderUrl,'builderUrl')
app.add_template_global(UrlManager.buildStaticUrl,'buildStaticUrl')
接着,需要去静态文件中把相关的链接也都替换掉
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" type="text/css" href="{{buildStaticUrl('/plugins/bootstrap/css/bootstrap.css')}}">
<!-- Bootstrap CSS -->
</head>
<body>
<nav class="navbar navbar-inverse" style="border-radius: 0px">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="{{builderUrl('/')}}">猫影</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li class="active"><a href="{{builderUrl('/')}}">影视<span class="sr-only">(current)</span></a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><a href="{{builderUrl('/member/reg')}}">注册</a></li>
<li><a href="{{builderUrl('/member/login')}}">登录</a> </li>
</ul>
</div><!-- /.navbar-collapse -->
</div><!-- /.container-fluid -->
</nav>
<div class="container" style="min-height: 600px">
{% block content %}
{% endblock%}
</div>
<footer class="text-center">
Copy right Juha
</footer>
<script type="text/javascript" src="{{buildStaticUrl('/plugins/jquery/jquery-3.5.1.min.js')}}"></script>
</body>
</html>
这里很好的一点,就是把链接可以替换为绝对的路径,不用担心改一个而改全部的问题了。