Skip to main content
 首页 » 编程设计

python之URL 重写之Google App Engine (Python)

2025年05月04日25jpfss

我按照教程为我计划在 Google App Engine (Python) 上托管的网站创建了漂亮的 URL。

问题是它不会显示子目录中的索引页。

我有一个名为 abc.html 的文件,可以在此地址正常加载 http://www.testsite.com/abc

但我在子目录(xyz 和 123)中有索引文件,这些文件不会加载到内容区域(内容区域中的空格)

带有 index.html 的子目录 xyz: http://www.testsite.com/xyz

目录 xyz 中带有 index.html 的子目录 123: http://www.testsite.com/xyz/123

这是我使用的代码

app.yaml

application: testsite 
version: 1 
runtime: python 
api_version: 1 
threadsafe: yes 
 
default_expiration: "1d" 
 
handlers: 
- url: /(.*\.(gif|png|jpg|ico|js|css|swf|xml)) 
  static_files: \1 
  upload: (.*\.(gif|png|jpg|ico|js|css|swf|xml)) 
 
- url: /.* 
  script: main.py 

主.py

import os 
    from google.appengine.ext import webapp 
from google.appengine.ext.webapp.util import run_wsgi_app 
from google.appengine.ext.webapp import template 
 
class MainPage(webapp.RequestHandler): 
   def get(self, p): 
      if p: 
         page = p + ".html" 
      else: 
         p = "main" 
         page = p + ".html" 
 
          if not os.path.exists(page): 
         page = "404.html" 
 
      template_values = { 
            "page" : page, 
                p: "first",  
      }; 
 
      path = os.path.join(os.path.dirname(__file__), 'index.html') 
      self.response.out.write(template.render(path, template_values)) 
 
application = webapp.WSGIApplication([(r'/(.*)', MainPage)],debug=True) 
 
def main(): 
   run_wsgi_app(application) 
 
if __name__ == "__main__": 
   main() 

index.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
   <meta http-equiv="content-type" content="text/html; charset=utf-8" /> 
   <title>TestTitle</title> 
   <link href="/static/style.css" rel="stylesheet" type="text/css" media="screen" /> 
</head> 
<body> 
   <div id="header"> 
            <ul> 
                <li><a href="main">Home</a></li> 
                <li><a href="abc">abc</a></li> 
                <li><a href="xyz/123">xyz</a></li> 
            </ul> 
   </div> 
 
   <div id="content"> 
      <!-- this is where content will be loaded --> 
 
      {% if page %} 
         {% include page %} 
      {% else %} 
         {% include "main.html" %} 
      {% endif %} 
 
   </div> 
 
   <div id="sidebar"> 
      TestSideBar 
   </div> 
 
   <div id="footer"> 
      TestFooter 
   </div> 
</body> 
</html> 

PS:我遵循的教程是动态页面+ URL 重写指南。动态页面方面并不是真正必要的。我只是找不到可以让漂亮的 URL 正常工作的教程。

请您参考如下方法:

首先,您的 app.yaml 或 main.py 是错误的。 由于 Python27 是更现代的运行时,我建议它是 app.yaml 我建议使用以下 app.yaml:

application: testsite 
version: 1 
runtime: python27 
api_version: 1 
threadsafe: yes 
 
handlers: 
- url: .* 
  script: main.application 

然后您谈到了子目录中名为 index.html 的文件,但无法访问它们。相反,您访问“xyz.html”和“xyz/123.html”。

尝试截取以下代码:

        if p: 
            page = os.path.join(p, "index.html") 
        else: 
            p = "main" 
            page = "main.html" 

顺便说一下:你应该考虑模板继承而不是包含标签!