Search code examples
pythongoogle-app-enginejinja2webapp2

Getting Started with Python in Google App Engine


I'm just getting started in python with google app engine using the webapp2 framework and jinja2 templating. I can't seem to get my first and very simple script up and running. All I want is for the script to serve the index.html file(located in the same directory).

Here is the app.yaml file:

libraries
- name: webapp2
  version: latest
- name: jinja2
  version: latest

application: practice
version: 1
runtime: python27
api_version: 1
threadsafe: true

handlers:
- url: /.*
  script: practice.application

Here is practice.py:

import os
import webapp2
from jinja2 import Enviroment, FileSystemLoader

loader = jinja2.FileSystemLoader(os.path.dirname(__FILE__)
env = jinja2.Enviroment(loader)

class MainPage(webapp2.RequestHandler):
    def get(self):
        template = env.get_template('index.html')
        self.response.write(template.render())

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

Update: I am running this locally from the Google app engine launcher. When I attempt to open the file I receive a server error with the description

The website encountered an error while retrieving http://localhost:9080/. It may be
down for maintenance or configured incorrectly."

Solution

  • Here's why your code won't run:

    • Your app.yaml is malformed
    • Enviroment is spelt wrong
    • Your missing a closing bracket on line 5
    • You haven't imported the jinja2 library
    • The variable __FILE__ is undeclared

    Here's what I think your code should look like:

    app.yaml

    application: practice
    version: 1
    runtime: python27
    api_version: 1
    threadsafe: true
    
    libraries:
    - name: webapp2
      version: latest
    - name: jinja2
      version: latest
    
    handlers:
    - url: /.*
      script: practice.application
    

    practice.py

    import jinja2
    import os
    import webapp2
    
    loader = jinja2.FileSystemLoader(os.path.dirname(__file__))
    env = jinja2.Environment(loader=loader)
    
    class MainPage(webapp2.RequestHandler):
        def get(self):
            template = env.get_template('index.html')
            self.response.write(template.render())
    
    application = webapp2.WSGIApplication([
     ('/', MainPage),
     ], debug=True)
    

    I suggest you do the following to make your life a LOT easier:

    Hope this helps get you on your way.

    Happy coding :)