learner learner - 1 month ago 6
HTML Question

How to load .html page with Python on App Engine

In the following example, the

.html
data is in the same file as the Python code (as variable
MAIN_PAGE_HTML
).

I want the
.html
content in its own different file.

How do I present the HTML page? Must I always use
Jinja2
to load it?

Or is there a simpler way to get the content of my
.html
and pass it to
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)


My
.html
file contains a form that user can fill and send to me.

Answer

Jinja2 it's a template engine, basically merge variables before to be served in the client, but webapp2 include the template engine by itself

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)

So basically you can use webapp2, jinja or others templates engines, but out of the box app engine only offers webapp2 (django) and jinja2

To serve static files (images, js, css, etc.) and in the handlers section in you app.yaml file

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  

according to this yaml file, this would be the structure in your project

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