1.在一個文件夾名爲www.html3.com的web項目來實現,首先到nginx的配置文件nginx.conf作以下配置
python和html混合編寫的文件,我以文件後綴爲.phtml,經過服務器配置讓它重定向到 /rewrite/html
2.進去項目目錄下的static/html/ 編寫一個1.phtml 內容以下(內容是隨便寫的,只是爲了測試)python
<% #define a variable str_var = "hello world" ############# divide ################ import time if True: str_var2 = str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) else: str_var2 = "nothing" %> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>phtml</title> <script> </script> </head> <body> <p>start</p> <p>I say: <span><% str_var %></span></p> <p>I say: <span><% str_var2 %></span></p> <p>end</p> </body> </html>
注意:博主本人的想法是在html文檔前放一對分隔符且只是一個,專門用於處理數據與邏輯,然後面的分隔符也就是嵌入到html文檔內的那些分隔符,裏面只放置一個變量名,用於輸出變量值,由於時間有限,只是簡簡單單實現,請諒解!nginx
PS:若有須要Python學習資料的小夥伴能夠加點擊下方連接自行獲取
note.youdao.com/noteshare?id=2dce86d0c2588ae7c0a88bee34324d76web
3.我該項目是flask項目(核心思想與web框架無關),而後寫個路由,內容以下flask
@app.route('/rewrite/') def rewite(): url_path = str(request.environ['REQUEST_URI'])[1:] if os.path.exists(url_path): oFile = open(url_path) text = oFile.read() pattern = re.compile('<%([\s\S]*?)%>') result = pattern.findall(text) content = [] flag = 0 while flag < len(result): if flag == 0: exec(result[flag].strip()) content.append('') else: content.append(locals()[result[flag].strip()]) flag += 1 flag = 0 def mysub(matched): nonlocal flag flag2 = flag flag += 1 return content[flag2] res = re.sub('<%[\s\S]*?%>',mysub,text) return res else: return "404 not found"
代碼解釋:服務器
1.若是有看不懂request.environ['REQUEST_URI'],能夠看一下博主以前寫的一篇文章「nginx的rewrite ,如何在flask項目中獲取重寫前的url」app
2.result變量用於存放匹配到分隔符內的字符串,是列表框架
3.content變量用於存放result列表每一個元素解釋後的值,而content[0]放空字符串(由於沒有輸出,result[0]只用於經過exec( )來執行字符串語句)ide
4.測試訪問http://ww.html3.com/static/html/1.phtml
學習
假設訪問不存在的2.phtml
附:
通配符. 匹配除換行符\n以外的任何單字符
若是要匹配包括換行符的全部字符就不要用(.),用([\s\S])
關於如何解決貪婪匹配,加?