如何在App Engine上用Python加载.html页面

2 投票
2 回答
3756 浏览
提问于 2025-05-01 10:10

在下面的例子中,.html 数据和 Python 代码放在同一个文件里(作为变量 MAIN_PAGE_HTML)。

我想把 .html 的内容放到一个单独的文件里。

我该怎么展示这个 HTML 页面呢?我必须总是用 Jinja2 来加载它吗?

或者有没有更简单的方法可以获取我的 .html 内容,并把它传递给 self.response.write 呢?

import cgi from google.appengine.api import users import webapp2

MAIN_PAGE_HTML = """\ <html>   <body>
    <form action="/sign" method="post">
      <div><textarea name="content" rows="3" cols="60"></textarea></div>
      <div><input type="submit" value="Sign Guestbook"></div>
    </form>   </body> </html> """

class MainPage(webapp2.RequestHandler):
    def get(self):
        self.response.write(MAIN_PAGE_HTML)

class Guestbook(webapp2.RequestHandler):
    def post(self):
        self.response.write('<html><body>You wrote:<pre>')
        self.response.write(cgi.escape(self.request.get('content')))
        self.response.write('</pre></body></html>')

application = webapp2.WSGIApplication([
    ('/', MainPage),
    ('/sign', Guestbook), ], debug=True)

我的 .html 文件里有一个表单,用户可以填写并发送给我。

暂无标签

2 个回答

3

是一个很不错的工具,可以简单地为用户提供动态内容。如果你需要动态内容,我推荐你看看这个 方法

不过,如果你只需要静态内容,那就用 静态页面 吧。 (顺便提一下,StackOverflow上有很多关于如何做到这一点的帖子,比如: 在Google App Engine Python中提供静态HTML

如果你想的话,也可以动态加载自己的文件,但我觉得这不是解决你问题的最佳方法。

3

Jinja2 是一个模板引擎,简单来说就是在把内容展示给用户之前,把一些变量合并到一起。不过,webapp2 自带了这个模板引擎。

import webapp2
import os #added
from google.appengine.ext.webapp import template #also added

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

class Guestbook(webapp2.RequestHandler):
    def post(self): #didn't change this
        self.response.write('<html><body>You wrote:<pre>')
        self.response.write(cgi.escape(self.request.get('content')))
        self.response.write('</pre></body></html>')

application = webapp2.WSGIApplication([
    ('/', MainPage),
    ('/sign', Guestbook), ], debug=True)

所以你可以使用 webapp2、jinja 或者其他的模板引擎,但默认情况下,应用引擎只提供 webapp2(类似 Django)和 jinja2。

要提供静态文件(比如图片、JavaScript、CSS 等),你需要在你的 app.yaml 文件中的处理程序部分进行设置。

handlers:
- url: /images # in the html can access from localhost:8080/images
  static_dir: templates/images # folder template, subfolder images
- url: /js
  static_dir: templates/js  
- url: /css
  static_dir: templates/css  
- url: /fonts
  static_dir: templates/fonts  
- url: /assets
  static_dir: templates/assets  

根据这个 yaml 文件,你的项目结构应该是这样的。

-  MyAppFolder
-- Templates
---- images
---- js
---- css
---- fonts
---- assets

撰写回答