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 static files.
Is there any good practices? If so, lead me there please.
Thanks in advance.
EDIT
Well, I'm now using paste
for my WSGI server. And paste.StaticURLParser()
should be what I need to implement static file handler. However I have no idea how to integrate it with webapp2.WSGIApplication()
. Could anyone help me?
Maybe I need to override webapp2.RequestHandler
class to load paste.StaticURLParser()
properly;
import os
import webapp2
from paste import httpserver
class StaticFileHandler(webapp2.RequestHandler):
u"""Static file handler"""
def __init__(self):
# I guess I need to override something here to load
# `paste.StaticURLParser()` properly.
pass
app = webapp2.WSGIApplication([(r'/static', StaticFileHandler)], debug=True)
def main():
port = int(os.environ.get('PORT', 5000))
httpserver.serve(app, host='0.0.0.0', port=port)
if __name__ == '__main__':
main()
Any helps would be appreciated!
Your project is ready to be deployed on Heroku. serve is a very minimal node package, that is used to serve static files on node server.
Configuring static filesMake sure that django.contrib.staticfiles is included in your INSTALLED_APPS . In your templates, use the static template tag to build the URL for the given relative path using the configured STATICFILES_STORAGE . Store your static files in a folder called static in your app.
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With