【问题标题】:How to setup dynamic URL in GAE?如何在 GAE 中设置动态 URL?
【发布时间】:2012-06-13 15:13:48
【问题描述】:

我是 GAE 的新手。我现在在 GAE 上托管一个网站。 我想把http://abc.com/about.html的网址改成http://abc.com/about/ 我应该怎么做?谢谢。

这是我的 main.py:

import webapp2
from google.appengine.ext.webapp2 import template
from google.appengine.ext.webapp2 import util
import os

class MainHandler(webapp2.RequestHandler):
    def get(self):
        template_values = {}
        path = os.path.join(os.path.dirname(__file__), 'index.html')
        self.response.out.write(template.render(path, template_values))

class About(webapp2.RequestHandler):
    def get(self):
        self.response.our.write(template.render('about.html',None))

def main()
    application = webapp2.WSGIApplication([(
        '.', MainHandler),
        ('about', About),
        ])
    util.run_wsgi_app(application)

app = webapp2.WSGIApplication([('/', MainHandler)],
                              debug=True)

这是我的 app.yaml:

application: nienyiho-test
version: 1
runtime: python27
api_version: 1
threadsafe: yes

handlers:
- url: /favicon\.ico
  static_files: favicon.ico
  upload: favicon\.ico

- url: .*
  script: main.app

- url: /about
  static_files: about.html
  upload: about.html

libraries:
- name: webapp2
  version: "2.5.1"

【问题讨论】:

  • 你为什么不展示使用你的app.yaml 文件和实现你的网络处理程序的代码。
  • 嗨亚当,我已经上传了我的 main.py。谢谢。

标签: python google-app-engine url


【解决方案1】:

您需要更改路线。您没有向我们提供创建路由的代码,但如果您基本上提供静态 HTML 文件,那么正如 @AdamCrossland 评论所述,您可以使用 app.yaml 文件来做到这一点。

您的 app.yaml 文件应如下所示:

application: your_app
version: 1
runtime: python27
api_version: 1
default_expiration: "1d"
threadsafe: True

- url: /about.html
  static_files: static/html/about.html
  upload: static/html/about.html
  secure: never

- url: /about
  script: main.app

- url: /.*
  script: main.app

您也可以按照@NickJohnson 的建议使用正则表达式here,如果您愿意,您可以删除安全行,但我在某些应用程序中使用 https 并使用该行来强制执行哪些路由是安全的还是不安全的。

main.py

import webapp2
from google.appengine.ext.webapp2 import template
from google.appengine.ext.webapp2 import util
import os

class MainHandler(webapp2.RequestHandler):
    def get(self):
        template_values = {}
        path = os.path.join(os.path.dirname(__file__), 'index.html')
        self.response.out.write(template.render(path, template_values))

class AboutHandler(webapp2.RequestHandler):
    def get(self):
        self.response.our.write(template.render('about.html',None)

#  Setup the Application & Routes
app = webapp2.WSGIApplication([
    webapp2.Route(r'/', MainHandler),
    webapp2.Route(r'/about', AboutHandler)
], debug=True)

编辑:20120610 - 添加了 main.py 并更新了 app.yaml 以显示如何路由生成的内容。

【讨论】:

  • 谢谢马克。我已经用我的 app.yaml 上传了
  • 你想要一个尾随的 / 吗?如果是这样,那么您需要将其添加到 - url: /about/ 中的 url,以便 webapp2 匹配器能够匹配路由。另外,您现在需要在 main.py 文件中添加一条路线,因为我正在再次查看它。我将使用示例 main.py 更新我的答案以路由 / 和 /about。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-03-30
  • 1970-01-01
  • 2023-03-22
  • 1970-01-01
  • 2023-01-04
  • 2015-11-10
  • 2016-07-08
相关资源
最近更新 更多