在以下示例中,.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
文件包含一个表单,用户可以填写并发送给我。
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
提供静态文件(图像、js、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
jinja2为您提供了一种向用户提供动态内容的体面而简单的方法:如果您需要动态内容,我建议您使用这种方法。
或者,如果您只需要静态内容,则使用静态页面。(请注意,StackOverflow有关于如何做到这一点的帖子:例如:在谷歌应用程序引擎Python中提供静态html)
如果需要,您也可以动态加载自己的文件,但我不认为这是解决问题的首选途径。