1. 程式人生 > 其它 >Python3中tornado高併發框架(4)

Python3中tornado高併發框架(4)

技術標籤:Pythontornado

16.模板

1. 配置模板的路徑

"template_path":os.path.join(BASE_DIRS,"templates"),

2. 渲染並返回給客戶端
返回頁面給客戶端

使用render()方法

class HomeHandler(RequestHandler):
    def get(self,*args,**kwargs):
        self.render("postfile.html")		

3. 變數和表示式
語法:{{var}} 放變數
{{expression}} 放表示式

class HomeHandler(RequestHandler):  #渲染
    def get(self,*args,**kwargs):
        temp = 100
        per={
            "name":"good",
            "age":10
        }
        self.render('upload.html',num=temp,per=per)		#對應用{{per["name"]}}取值,這裡不能用點語法per.name
        # self.render('upload.html', num=temp, **per) #也可以這樣傳遞,只是在頁面中就{{name}},形式取值。
        # 但是為了避免和變數名衝突,一般不用,比如說變數名也為age=20,和字典中的age=10衝突,頁面中{{age}}也就發生衝突

up.html頁面如下


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>上傳檔案</title>
</head>
<body>
    <span>{{num}}</span>#傳值<br/>       
    <span>num+10:{{num+10}}</span>#運算<br/> 
    <span>num*10:{{num*10}}</span> #運算<br/>       
    <span>num==100:{{num==100}}</span>#判斷<br/>     
    <span>num==1000:{{num==1000}}</span>#判斷<br/>
    <span>{{per["name"]}}</span>#字典<br/>   
    <span>{{per["age"]}}</span>#字典<br/> 
    
</body>
</html>

application裡的註冊:

(r"/home", index.HomeHandler),

http://127.0.0.1:9000/home

對應輸出

100#傳值
num+10:110#運算
num*10:1000 #運算
num==100:True#判斷
num==1000:False#判斷
good#字典
10#字典

17.流程控制

if

for

whiile

1. if用法
滿足if-else-end ; if-elif-elif-else-end語句
和django基本類似,少數不一樣
格式:

#html頁面中應用:
{% if 表示式 %}
語句1
{% elif 表示式 %}
語句2
{% elif 表示式 %}
語句3
......
{% else %}
語句n
{% end %}

2.for用法
格式:

{% for 變數 in 集合 %}
語句
{% end %}

index裡的類。

class HomeHandler(RequestHandler):  #渲染
    def get(self,*args,**kwargs):
        stus = [
            {
                "name":"laowang",
                "age":18
            },
            {
                "name":"xiaobai",
                "age":20
            }
        ]
        self.render('up.html',stus=stus)

#templates/up.html中應用,其他的html此處省略

#templates/upload.html中應用,其他的html此處省略
	<ul>
        {% for stu in stus %}
        <li>{{stu["name"]}} : {{stu["age"]}}</li>
        {% end %}
    </ul>

#(瀏覽器輸出)

18.函式

1.	static_url()
2.	自定義函式

1. static_url()
作用:獲取配置的靜態目錄,並肩引數拼接到靜態目錄後面並返回新的路徑
用於:引入檔案css,js等
優點:修改目錄不需要再修改html中的配置檔案路徑,只需要修改config配置檔案中的即可。
--------而且建立了一個基於檔案內容的hash值,並將其新增到URl末尾,這個hash值總能保證載入的都是最新的檔案,而不是快取的版本。不論是開發還是上線階段都是很有必要的。

#templates/staticfile.html中,寫在head標籤裡。

<link rel="stylesheet" href="{{static_url('css/staticfile.css')}">

新建檔案 如圖:存放對應檔案

#需要配置好靜態檔案的路徑"static_path"
setting = {
    "static_path":os.path.join(BASE_DIRS,"static"),			
    "template_path":os.path.join(BASE_DIRS,"templates"),
    "debug":True        #修改完檔案後服務自動啟動
}
#static/css/posfile.css中
div{
    width: 700px;
    height: 100px;
    background-color: aqua;
    font-size: 20px;
}

staticfile.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="{{static_url('css/staticfile.css')}}">

</head>
<body>
<div>
        <!--action如何起名-->
        <form action="/staticfile" method="post">
            <p>
                姓名:<input type="text" name="username"><br>
            </p>
            <p>
                密碼:<input type="password" name="passwd"><br>
            </p>
            <p>
                愛好:<input type="checkbox" value="權利" name="hobby">權利
                 <input type="checkbox" value="書籍" name="hobby">書籍
                 <input type="checkbox" value="金錢" name="hobby">金錢
            </p>
                 <input type="submit" value="login">登入
        </form>
    </div>
</body>
</html>

index的寫法:

class StaticfileHandler(RequestHandler):          #post請求處理
    def get(self, *args, **kwargs):
        # postfile.html ,templates下的postfile.html
        self.render("staticfile.html")  #註冊頁面跳轉

在application註冊類,

(r"/staticfile", index.StaticfileHandler),

http://127.0.0.1:9000/staticfile

2. 自定義函式
作用:自定義函式後,可以再html頁面模板中應用 ;{{mySum(100,89)}}形式應用
tornado在末班中可以引用函式並且能進行傳參

#views/index中配置後,對應新增路由

class FunctionHandler(RequestHandler):  #自定義函式
    def get(self,*args,**kwargs):
        def mySum(n1,n2):
            return n1 + n2
        self.render("staticfile.html",mySum=mySum)  #傳遞函式

#路由新增
(r"/function",index.FunctionHandler),

#對應的template/staticfile.html中
<p>{{mySum(100,89)}}</p>

#(瀏覽器輸出)
189

19.轉義

1.tornado預設開啟了自動轉義功能,能防止網站受到惡意攻擊

#views/index中配置,

class TransferredHandler(RequestHandler):
    def get(self,*args,**kwargs):
        strm="<h1>good job!</h1>"
        self.render("transferred.html",strm=strm)

相應的
application中配置路由:

(r"/transferred",index.TransferredHandler) #轉義

對應的transferred.html中接收:

<body>
{{strm}}
</body>

http://127.0.0.1:9000/transferred

瀏覽器輸出:並不是一個h1標籤,而是個字串:

<h1>good job!</h1>

2.關閉自動轉義

  1. 方法一 :關閉一行
    raw :{% raw strm %}

<body>
{{strm}}
{% raw strm %}
{{strm}}
</body>

就是{{ }}顯示的不進行轉義,而{% %}是進行轉義的

樣的話上面例項:

good job!

就會變成h1標籤,但是隻能關閉一行

2. 方法二:關閉當前文件中的自動轉移
{% autoescape None %}

<body>
{{strm}}
{% autoescape None %}
{{strm}}
</body>

瀏覽器輸出:
在這裡插入圖片描述

3. 在配置檔案中修改

“autoescape”:None, #關閉專案的自動轉移

setting = {
    "static_path":os.path.join(BASE_DIRS,"static"),
    "template_path":os.path.join(BASE_DIRS,"templates"),
    "debug":True ,    #修改完檔案後服務自動啟動
    "autoescape":None,	#關閉自動轉移
}

<body>
{{strm}}
{{strm}}
</body>

4. escape()
{{escape(strm)}}
作用:在關閉自動轉義後,可以用這個方法開啟特定的內容的自動轉義

<body>
    {{strm}}
    {% autoescape None %}
    {{strm}}
    {{escape(strm)}}
</body>

20.繼承

子模板繼承父模板的內容,即例項cart.html繼承與父模板base.html 模板

#父模板挖坑,等著子模板來填坑
 {% block main %}		
        {% end %}
#子模板,填坑的
{% extends "base.html" %}
{% block main %}
<h1>頁面展示</h1>
{% end %}

templates/base.html父模板

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
        {% block main %}		
        {% end %}
</body>
</html>

templates/cart.html中子模板,繼承父模板

{% extends "base.html" %}

{% block main %}
<h1>頁面展示</h1>
{% end %}

views/index中

class  CartHandler(RequestHandler): #繼承測試
    def get(self,*args,**kwargs):
        self.render("cart.html",title="cart")

application中配置路由:

(r"/cart",index.CartHandler), #繼承

訪問路由後http://127.0.0.1:9000/cart,瀏覽器:

21.靜態檔案

1. static_path
2. StaticFileHandler

1. static_path
**作用:**告訴tornado從檔案系統中的莫一個特定的位置提供靜態檔案
示列: “static_path”:os.path.join(BASE_DIRS,“static”), #靜態檔案

#config中配置

BASE_DIRS = os.path.dirname(__file__)
setting = {
    "static_path":os.path.join(BASE_DIRS,"static"),			#靜態檔案
    "template_path":os.path.join(BASE_DIRS,"templates"),	#檢視
    "debug":True ,    #修改完檔案後服務自動啟動
    # "autoescape":None, #關閉自動轉移
}

#static/html/index.html中

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>主頁</title>
</head>
<body>
    <p>靜態頁面 </p>
</body>
</html>

請求方式
直接訪問靜態檔案,不需要配置路由:

http://127.0.0.1:9999/static/html/index.html

引入其他檔案
css檔案

<link rel="stylesheet" href="{{static_url('css/postfile.css')}}">

js檔案

<script type="text/javascript" charset="utf-8" src="{{static_url('js/test1.js')}}"></script>

2. StaticFileHandler
使用原因http://127.0.0.1:9999/static/html/index.html過於的繁瑣,
本質:是tornado預製的,用來提供靜態資原始檔的一個Handler
作用:可以通過 tornado.web.StaticFileHandler 來對映靜態檔案
引數:
path:同來指定提供靜態檔案的根路徑
default_filename:同來指定訪問路由中未指定的檔案,
使用
application中配置路由

# http://127.0.0.1:9000/index.html
(r"/(.*)$", tornado.web.StaticFileHandler, {"path":os.path.join(config.BASE_DIRS,"static/html"),"default_filename":"index.html"}),
# StaticFileHandler應用靜態檔案,注意要放在所有路由的下面。
  1. StaticFileHandler應用靜態檔案,注意要放在所有路由的下面。
  2. 引數 “path”:os.path.join(config.BASE_DIRS,“static/html”)傳參,拼接以下靜態檔案的路徑, 這樣所有在html檔案下的靜態檔案都可以簡單的訪問了
  3. 引數"default_filename":“index.html” 這裡是設定了一個預設值,即http://127.0.0.1:9000情況下訪問index.html頁面(主頁)。有點像 (r"/",index.IndexHandler),這樣的路由。

*這樣,直接訪問http://127.0.0.1:9000/index.html即可,設定預設值後http://127.0.0.1:9000就能直接訪問預設值頁面
**注意:**在設定預設值後, (r"/",index.IndexHandler),這樣的路由要註釋掉,不然他不會訪問我們設定的預設值,出現衝突

https://blog.csdn.net/weixin_43097301/article/details/84981441