Web 服務器css
每一個頁面都以 HTML 的形式傳送到你的瀏覽器中,HTML 是一種瀏覽器用來描述頁面內容和結構的語言。那些負責發送 HTML 到瀏覽器的應用稱之爲「Web 服務器」,會讓你迷惑的是,這些應用運行的機器一般也叫作 web 服務器。html
然而,最重要的是要理解,到最後全部的 web 應用要作的事情就是發送 HTML 到瀏覽器。無論應用的邏輯多麼複雜,最終的結果老是將 HTML 發送到瀏覽器(我故意將應用能夠響應像 JSON
或者 CSS
等不一樣類型的數據忽略掉,由於在概念上是相同的)。前端
HTTP GETpython
web 應用在 GET 請求的結果中,不該該改變應用的狀態(好比,不能基於 GET 請求建立一個新賬號)。正是由於這個緣由,GET 請求一般認爲是「安全」的,由於他們不會致使應用的改變。web
HTTP POST數據庫
POST 請求一般攜帶由用戶輸入的數據,web 應用收到以後會產生一些行爲。經過在表單裏輸入你的信息登陸一個網站,就是 POST 表單的數據給 web 應用的。json
框架的概念:瀏覽器
特指爲解決一個開放性問題而設計的具備必定約束性的支撐結構。在此結構上能夠根據具體問題擴展、安插更多的組成部分,從而更迅速和方便地構建完整的解決問題的方案緩存
python中web框架按是否包含socket分爲倆類:安全
一、tornado--------socket + 業務邏輯處理
二、Django,bottle,flack-----業務邏輯處理 (自己包含) + 第三方模塊(wsgiref)(其中包含socket)
1、初識tornado
tornado web server 是使用python編寫出來的一個輕量級、高可伸縮性和非阻塞IO的Web服務器軟件,其特色是採用epoll非阻塞IO,相應快速,可處理數千併發鏈接,特別適用於實時的Web服務。
MVC和MTV框架------(其實就是文件夾的分類)
MVC:Models 數據相關操做(數據庫) Views 模板HTML文件 Controllers 業務邏輯(url)
MTV:Models 數據相關操做(數據庫) Templates 模板HTML文件 Views 業務邏輯(url)
web框架的本質
經典的hello world 案例:
import tornado.ioloop import tornado.web class MainHandler(tornado.web.RequestHandler): def get(self): self.write("Hello, world") application = tornado.web.Application([ (r"/index", MainHandler), #路由映射(路由系統) ]) if __name__ == "__main__": application.listen(8888) tornado.ioloop.IOLoop.instance().start()
第一步:執行腳本,監聽 8888 端口
第二步:瀏覽器客戶端訪問 /index --> http://127.0.0.1:8888/index
第三步:服務器接受請求,並交由對應的類處理該請求
第四步:類接受到請求以後,根據請求方式(post / get / delete ...)的不一樣調用並執行相應的方法
第五步:方法返回值的字符串內容發送瀏覽器
具體分析後
import tornado.ioloop import tornado.web class MainHandler(tornado.web.RequestHandler): def get(self): # self.render("s1.html") #render方法,表示會自動找到文件並打開,返回給你 #render找的時候默認從當前的目錄下面去找,若是想讓其從別的地方找,咱們就能夠 #爲其作一個settings配置(也能夠把絕對路徑寫上去), self.write("Hello, world") settings={ #若是想讓配置文件生效,須要在下面application後面加一個**settings "tempalte_path":"xxx", #模板路徑的匹配,其中xxx爲放HTML的文件夾 "static_path":"xxx" #靜態文件的配置(靜態文件就是css和JavaScript),其中xxx爲存放靜態文件的文件夾 } #路由映射(路由系統) application = tornado.web.Application([ (r"/index", MainHandler), #檢測用戶的url是否匹配,若是匹配則,執行其後面類中的莫一種方法 #同一個url以不一樣的方式訪問,執行不一樣的方法 ],**settings) if __name__ == "__main__": application.listen(8888) tornado.ioloop.IOLoop.instance().start()
前端與後臺互動實例
#!/usr/bin/env python # -*- coding:utf-8 -*- import tornado.ioloop import tornado.web list = [] class MainHandler(tornado.web.RequestHandler): def get(self): #一、打開s.html,讀取內容(含有特殊語法-----模板語言) #二、xxx = list和特殊的語法進行結合, #三、獲得一個新的通過渲染後的字符串返回給用戶 self.render('s.html' ,xxx = list) def post(self, *args, **kwargs): data = self.get_argument("xxx") #用於經過鍵值獲取後臺以鍵值對提交的數據 print(data) list.append(data) self.render("s.html",xxx = list) #xxx = list 表示用於渲染時的值 settings={ "template_path":"ttt", "static_path":"static" } application = tornado.web.Application([ (r"/index", MainHandler), ],**settings) if __name__ == "__main__": application.listen(8080) tornado.ioloop.IOLoop.instance().start()
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="../static/commons.css"> </head> <body> <h1>提交內容</h1> <form action="/index" method="post"> <!--以post方式提交會執行post方法-,/index 表示提交的url地址--> <input type="text" name="xxx"> <input type="submit"> </form> <h1>顯示內容</h1> <ul> {% for item in xxx %} <li>{{item}}</li> {% end %} </ul> </body> </html>
總結點:
self.get_argument("xxx",None)----------------用於獲取後臺提交的數據,其中None爲默認值
提交方式:get 和 post提交方式的不一樣點 ---------get能夠經過url方式提交
模板語言裏經過for循環展現數據:
{% for item in xxx %} -------必須是{% %}的格式
<li>{{item}}</li> --------item必須{{}}包裹起來
{% end %} --------結束必須有{% end %}
模板語言(3種):
一、{{xxx}}-------------self.render("s.html",xxx = "yyy")
二、代碼塊的方式
{% for item in xxx %}-------------- self.render("s.html",xxx = yyy) {% if item == "alex"%} .....................
<li>{{item}}</li> {% else %}
{% end %} {% end %}
三、自定義
1>uimethods
---------------->在HTML中<span>{{fun(arg)}}</span>
---------------->新建一個uimethods文件,並在其中定義方法 def fun(self,arg): return xxx
---------------->主程序中須要導入 import uimethods as mt 並配置文件 'ui_methods': mt, 在render中傳參 self.render("s.html",xxx = yyy,arg = "aaaa")
settings = {
'template_path': 'template',
'static_path': 'static',
'static_url_prefix': '/static/',
'ui_methods': mt,
'ui_modules': md,
}
# uimethods.py
def tab(self):
return 'UIMethod'
2>uimodules
---------------->在HTML中<span>{% module 類名()%}</span>
---------------->新建一個uimodules文件,並在其中類等的一些東西
---------------->主程序中須要導入 import uimodules as md 並配置文件 'ui_modules: md,
#!/usr/bin/env python # -*- coding:utf-8 -*- from tornado.web import UIModule from tornado import escape class custom(UIModule): def render(self, *args, **kwargs): return escape.xhtml_escape('<h1>wupeiqi</h1>') #return escape.xhtml_escape('<h1>wupeiqi</h1>')
註冊和使用
#!/usr/bin/env python # -*- coding:utf-8 -*- #!/usr/bin/env python # -*- coding:utf-8 -*- import tornado.ioloop import tornado.web from tornado.escape import linkify import uimodules as md import uimethods as mt class MainHandler(tornado.web.RequestHandler): def get(self): self.render('index.html') settings = { 'template_path': 'template', 'static_path': 'static', 'static_url_prefix': '/static/', 'ui_methods': mt, 'ui_modules': md, } application = tornado.web.Application([ (r"/index", MainHandler), ], **settings) if __name__ == "__main__": application.listen(8009) tornado.ioloop.IOLoop.instance().start()
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <link href="{{static_url("commons.css")}}" rel="stylesheet" /> </head> <body> <h1>hello</h1> {% module custom(123) %} {{ tab() }} </body>
在模板中默認提供了一些函數、字段、類以供模板使用:
escape
: tornado.escape.xhtml_escape
的別名----------------------------------------------用來作轉譯的
xhtml_escape
: tornado.escape.xhtml_escape
的別名------------------------------------用來作轉譯的url_escape
: tornado.escape.url_escape
的別名------------------------------------------用來作轉譯的json_encode
: tornado.escape.json_encode
的別名---------------------------------------用來作json處理的squeeze
: tornado.escape.squeeze
的別名linkify
: tornado.escape.linkify
的別名--------------------------------------------------用來生成a標籤的datetime
: Python 的 datetime
模組handler
: 當前的 RequestHandler
對象request
: handler.request
的別名current_user
: handler.current_user
的別名locale
: handler.locale
的別名_
: handler.locale.translate
的別名static_url
: for handler.static_url
的別名--------------------用於css文件或js的緩存做用(v=675645434545,這是文件的md5值) xsrf_form_html
: handler.xsrf_form_html
的別名cookie
Cookie是當你瀏覽某網站時,網站存儲在你機器上的一個小文本文件,它記錄了你的用戶ID,密碼、瀏覽過的網頁、停留的時間等信息,當你再次來到該網站時,網站經過讀取Cookie,得知你的相關信息,就能夠作出相應的動做,如在頁面顯示歡迎你的標語,或者讓你不用輸入ID、密碼就直接登陸等。
登陸設置cookie實例:
import tornado.ioloop import tornado.web from controller import index from controller import login settings={ "template_path":"views", "static_path":"statics", 'cookie_secret':"wdfsdfsfsd" } application = tornado.web.Application([ (r"/index", index.IndexHandler), (r"/login", login.LoginHandler), ],**settings) if __name__ == "__main__": application.listen(8080) tornado.ioloop.IOLoop.instance().start()
import tornado.web class IndexHandler(tornado.web.RequestHandler): def get(self, *args, **kwargs): cook = self.get_secure_cookie("auto") #獲取cookie if cook: #若是之前登陸成功過,會得到cookie,未登陸成功直接訪問,默認爲None self.render("index.html") #若是有cookie,則返回須要頁 else: self.write("訪問失敗") def post(self, *args, **kwargs): user = self.get_argument("username") #獲取登陸頁輸入的用戶名 pwd = self.get_argument("pwd") #獲取登陸頁的密碼 if user == "alex" and pwd =="123": self.set_secure_cookie("auto","666") #若是登陸成功,則設置cookie self.render("index.html") #登陸成功返回須要訪問頁碼 else: self.redirect("/login") #登陸不正確,跳轉登陸頁
import tornado import tornado.web class LoginHandler(tornado.web.RequestHandler): def get(self, *args, **kwargs): self.render("login.html") def post(self, *args, **kwargs): pass
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>活躍288天,已升級</h1> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/index" method="post"> <input type="text" name="username"> <input type="password" name="pwd"> <input type="submit" value="提交"> </form> </body> </html>