路由(route)
簡單來說路由就是一個映射器,利用一個給定的參數來映射到對應的指定路徑或者執行函數等等。
改版miniweb服務器
來把前面一章節自定義的一個mini框架改成路由的版本。
mini_frame.py代碼:
import os
import re
from pymysql import *
# 測試使用
print(os.path.abspath(__file__)) # 顯示當前文件的地址
print(os.getcwd()) # 顯示主程序入口的地址
# 定義一個字典來儲存方法的引用,key=訪問路徑,value=函數引用
route_dict = dict()
def route(url):
def set_func(func):
# 將所有函數的引用保存到字典中,後續調用
route_dict[url] = func
def call_func(*args, **kwargs):
return func(*args, **kwargs)
return call_func
return set_func
@route("/index.py")
def index(info):
with open(info["template"] + "/index.html", encoding="utf-8") as f:
content = f.read()
# 鏈接數據庫
con = connect(host='localhost', port=3306, database='stock_db', user='root', password='root', charset='utf8')
cursor = con.cursor()
sql = "select * from info;"
cursor.execute(sql)
# 查詢數據
data_from_mysql = cursor.fetchall()
html = ""
# 拼接html
for tr_data in data_from_mysql:
print(tr_data)
html += "<tr>"
for td_data in tr_data:
html += f"<td>{td_data}</td>"
html += """<td>
<input type="button" value="添加" id="toAdd" name="toAdd" systemidvaule="000007">
</td>
"""
html += "</tr>"
print(html)
content = re.sub(r"\{%content%\}", html, content)
cursor.close()
con.close()
return content
@route("/center.py")
def center(info):
with open(info["template"] + "/center.html", encoding="utf-8") as f:
content = f.read()
# 鏈接數據庫
con = connect(host='localhost', port=3306, database='stock_db', user='root', password='root', charset='utf8')
cursor = con.cursor()
sql = "select i.code,i.short,i.chg,i.turnover,i.price,i.highs,f.note_info from info as i inner join focus as f on i.id=f.info_id;"
cursor.execute(sql)
# 查詢數據
data_from_mysql = cursor.fetchall()
html = ""
# 拼接html
for tr_data in data_from_mysql:
print(tr_data)
html += "<tr>"
for td_data in tr_data:
html += f"<td>{td_data}</td>"
html += """<td>
<a type="button" class="btn btn-default btn-xs" href="/update/300268.html"> <span class="glyphicon glyphicon-star" aria-hidden="true"></span> 修改 </a>
</td>
<td>
<input type="button" value="刪除" id="toDel" name="toDel" systemidvaule="300268">
</td>
"""
html += "</tr>"
print(html)
content = re.sub(r"\{%content%\}", html, content)
cursor.close()
con.close()
return content
def application(environ, start_response):
start_response('200 OK', [('Content-Type', 'text/html;charset=utf-8')])
filename = environ["PATH_INFO"]
# 這裏就直接使用文件名來通過字典映射出對應的函數引用執行函數
try:
return route_dict[filename](environ["info"])
except Exception as error:
print(error)
return "沒有找到該資源"
源碼查看地址:https://gitee.com/duchaochen/pythonnotecode.git
作者:阿超
原創公衆號:『Python日常筆記』,專注於 Python爬蟲等技術棧和有益的程序人生,會將一些平時的日常筆記都慢慢整理起來,也期待你的關注和阿超一起學習,公衆號回覆【1024】優質資源。