How can I handle static files with Python webapp2 in Heroku?

一笑奈何 提交于 2019-11-29 14:19:07

Below is how I got this working.

I'm guessing that relying on a cascade app isn't the most efficient option, but it works well enough for my needs.

from paste.urlparser import StaticURLParser
from paste.cascade import Cascade
from paste import httpserver
import webapp2
import socket


class HelloWorld(webapp2.RequestHandler):
    def get(self):
        self.response.write('Hello cruel world.')

# Create the main app
web_app = webapp2.WSGIApplication([
    ('/', HelloWorld),
])

# Create an app to serve static files
# Choose a directory separate from your source (e.g., "static/") so it isn't dl'able
static_app = StaticURLParser("static/")

# Create a cascade that looks for static files first, then tries the webapp
app = Cascade([static_app, web_app])

def main():
    httpserver.serve(app, host=socket.gethostname(), port='8080')

if __name__ == '__main__':
    main()

this makes your code more friendly to deploy since you can use nginx to serve your static media in production.

def main():
  application = webapp2.WSGIApplication(routes, config=_config, debug=DEBUG)
  if DEBUG:
    # serve static files on development
    static_media_server = StaticURLParser(MEDIA_ROOT)
    app = Cascade([static_media_server, application])
    httpserver.serve(app, host='127.0.0.1', port='8000')
else:
    httpserver.serve(application, host='127.0.0.1', port='8000')

Consider me late to the game, but I actually like DirectoryApp a little better. It handles things a bit more like AppEngine. I can create a "static" directory in my src directory, and then I can reference those in my HTML (or whatever) like this: http:..localhost:8080/static/js/jquery.js

static_app = DirectoryApp("static")

# Create a cascade that looks for static files first, then tries the webapp
app = Cascade([static_app,wsgi_app])

httpserver.serve(app, host='0.0.0.0',
                 port='8080')
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!