html调用python_flask之模板html中调用python函数方法
一:html里面可以調(diào)用python寫的函數(shù)
add_template_global(調(diào)用函數(shù)的引用,"調(diào)用函數(shù)的名字")
from common.libs.UrlManager importUrlManager
app.add_template_global(UrlManager.buildStaticUrl,"buildStaticUrl")
app.add_template_global(UrlManager.buildUrl,"buildUrl")
app.add_template_global(UrlManager.buildImageUrl,"buildImageUrl")
作用:這個是為了讓前端界面可以通過這個url找到需要的元素
#-*- coding: utf-8 -*-
importtimefrom application importappclassUrlManager(object):def __init__(self):pass@staticmethoddefbuildUrl( path ):returnpath
@staticmethoddefbuildStaticUrl(path):
release_version= app.config.get( 'RELEASE_VERSION')print("這是什么玩意:",release_version) #訪問login.html一共打印了10次None,源模板7次,本身打印3次
ver = "%s"%( int( time.time())) if not release_version elserelease_version
path= "/static" + path + "?ver=" +ver#對path進(jìn)行拼接,路徑是靜態(tài)文件里面的圖片和css,js等資源
returnUrlManager.buildUrl( path )
@staticmethoddefbuildImageUrl( path ):
app_config= app.config['APP']
url= app_config['domain'] + app.config['UPLOAD']['prefix_url'] +pathreturn url
設(shè)計(jì)藍(lán)圖
from flask importBlueprint,send_from_directoryfrom application importapp
route_static= Blueprint("static",__name__)
@route_static.route("/")defindex(filename):#因?yàn)閟tatic的位置也改變了,因此使用路由的方式來訪問我們靜態(tài)文件
return send_from_directory(app.root_path+"/web/static/",filename)
注冊藍(lán)圖
app.register_blueprint(route_static,url_prefix="/static")
請求成功后,控制臺輸出
111.18.99.43 - - [04/Apr/2020 20:47:50] "GET /static/css/style.css?ver=1586004470 HTTP/1.1" 200 -
111.18.99.43 - - [04/Apr/2020 20:47:52] "GET /static/plugins/jquery-2.1.1.js?ver=1586004470 HTTP/1.1" 200 -
111.18.99.43 - - [04/Apr/2020 20:47:52] "GET /static/images/common/mini_qrcode.jpg?ver=1586004470 HTTP/1.1" 200 -
111.18.99.43 - - [04/Apr/2020 20:47:53] "GET /static/bootstrap/bootstrap.min.js?ver=1586004470 HTTP/1.1" 200 -
111.18.99.43 - - [04/Apr/2020 20:47:53] "GET /static/plugins/layer/layer.js?ver=1586004470 HTTP/1.1" 200 -
111.18.99.43 - - [04/Apr/2020 20:47:53] "GET /static/images/common/qrcode.jpg?ver=1586004470 HTTP/1.1" 200 -
111.18.99.43 - - [04/Apr/2020 20:47:55] "GET /static/js/common.js?ver=1586004470 HTTP/1.1" 200 -
111.18.99.43 - - [04/Apr/2020 20:47:55] "GET /static/js/user/login.js?ver=1586004470 HTTP/1.1" 200 -
send_from_direcorty(文件所在的文件夾,文件名)的作用:就是幫你找到你的所需要的文件,傳入的參數(shù)是路徑和文件名
過程:html里面調(diào)用了 buildStaticUrl(包含路徑),函數(shù)的返回值是一個path,給src賦值為這個path,然后就發(fā)送了請求,按照這個路徑進(jìn)行尋找,然后觸發(fā)了route_static這個藍(lán)圖,進(jìn)入index函數(shù),通過send_from_directory方法,找到文件真實(shí)的路徑,進(jìn)行展示
# TODO
總結(jié)
以上是生活随笔為你收集整理的html调用python_flask之模板html中调用python函数方法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 第一次失效_又到审核季,内审员们,咱如何
- 下一篇: while用法_语法宝典:连词while