Whonut
Whonut

Reputation: 288

Serving static HTML with Google App Engine and bottle

I am using Google App Engine with bottle.py and am trying to serve a static HTML file when a user visits /. To that end I have this in my main.py:

bottle = Bottle()

@bottle.route('/')
def index():
    """Serve index.html."""
    return static_file('index.html', root='/static')

I also have the following in my app.yaml:

handlers:
- url: /favicon\.ico
  static_files: static/favicon.ico
  upload: static/favicon\.ico
- url: /static
  static_dir: static
  application-readable: true
- url: /.*
  script: main.bottle

The favicon and a CSS file (both in the static directory) are used fine, although not served directly. However, going to / results in a 404 error. I'm slightly confused about what I should be doing with bottle.route and what I should be doing in app.yaml.

For completeness, my directory structure looks like this:

src
+-- main.py
+-- app.yaml
+-- static
    +-- favicon.ico
    +-- index.html
    +-- stylesheet.css
+-- [other unimportant files]

Upvotes: 3

Views: 337

Answers (2)

Alex Martelli
Alex Martelli

Reputation: 881635

To serve static files in App Engine, it's by far most efficient (faster for your users, and less expensive for you if you pass the free daily quota) to do so directly from app.yaml -- just add

- url: /
  static_files: static/index.html

to app.yaml before the "catch-all" url: /.* directive.

This way, your app won't be queueing up that static file request behind others that might be waiting, nor ever need to spin up and warm up a new instance, nor run any of your code -- it will just serve the static file to the the user pronto, just as fast as Google knows how to (including caching and CDN-like speed-ups "behind the curtains" as/if applicable).

There's really no reason to serve up static files from code, when you can instead so easily leverage Google's own serving infrastructure!

Upvotes: 3

fwu
fwu

Reputation: 369

The code below should work.

bottle = Bottle()

@bottle.route('/')
def index():
    """Serve index.html."""
    return static_file('index.html', root=os.path.join(os.path.dirname(os.path.realpath(__file__)), "/static"))

Upvotes: 0

Related Questions