Search code examples
pythoncssgoogle-app-enginestaticwebapp2

Serve stylesheet with webapp2 outside of Google App Engine


So I have successfully deployed an app using webapp2/jinja2 and a Paste server, but am having trouble serving static stylesheets.

I have had luck accessing static files via this method, as well as implementing a StaticFileHandler I found with some google-fu:

import os
import mimetypes
import webapp2
import logging

class StaticFileHandler(webapp2.RequestHandler):
    def get(self, path):
        abs_path = os.path.abspath(os.path.join(self.app.config.get('webapp2_static.static_file_path', 'static'), path))
        if os.path.isdir(abs_path) or abs_path.find(os.getcwd()) != 0:
            self.response.set_status(403)
            return
        try:
            f = open(abs_path, 'r')
            self.response.headers.add_header('Content-Type', mimetypes.guess_type(abs_path)[0])
            self.response.out.write(f.read())
            f.close()
        except:
            self.response.set_status(404)

where my main app routing looks like:

app = webapp2.WSGIApplication([('/', HelloWorld),
                               (r'/display', DisplayHandler),
                               (r'/static/(.+)', StaticFileHandler)
                              ], debug=True)

My css files are in a folder under the app root: /static/css/main.css

I can access the file via direct url, and even link it as a stylesheet, but the styles won't apply. Any ideas? Is there another way to serve stylesheets? Some way to implement an app.yaml similar to GAE?


Solution

  • you dont need a static file handler.
    upload the app with the static file folder by adding this to your app.yaml

    - url: /static/
      static_dir: static
    

    docs are here: https://developers.google.com/appengine/docs/python/config/appconfig#Static_Directory_Handlers

    edit: see answer below in comments