简体   繁体   中英

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]

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!

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"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM