1.在一個文件夾名為www.html3.com的web項目來實現,首先到nginx的配置文件nginx.conf做如下配置

python和html混合編寫的文件,我以文件后綴為.phtml,通過服務器配置讓它重定向到 /rewrite/
2.進去項目目錄下的static/html/ 編寫一個1.phtml 內容如下(內容是隨便寫的,只是為了測試)
<% #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文檔內的那些分隔符,里面只放置一個變量名,用於輸出變量值,因為時間有限,只是簡簡單單實現,請諒解!
3.我該項目是flask項目(核心思想與web框架無關),然后寫個路由,內容如下
@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”
2.result變量用於存放匹配到分隔符內的字符串,是列表
3.content變量用於存放result列表每個元素解釋后的值,而content[0]放空字符串(因為沒有輸出,result[0]只用於通過exec( )來執行字符串語句)
4.測試訪問http://ww.html3.com/static/html/1.phtml


假設訪問不存在的2.phtml
------------------------------------------------------------------------------------------------------------------------------------------------
附:
通配符. 匹配除換行符\n之外的任何單字符
如果要匹配包括換行符的所有字符就不要用(.*),用([\s\S]*)
關於如何解決貪婪匹配,加?
