How Can I Handle Static Files With Python Webapp2 In Heroku?
I am now migrating my small Google App Engine app to Heroku platform. I don't actually use Bigtable, and webapp2 reduces my migration costs a lot. Now I'm stuck on handling the sta
Solution 1:
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()
Solution 2:
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')
Solution 3:
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')
Post a Comment for "How Can I Handle Static Files With Python Webapp2 In Heroku?"