如何在Heroku上使用Python webapp2处理静态文件?

5 投票
3 回答
3512 浏览
提问于 2025-04-17 08:11

我现在正在把我的小型 Google App Engine 应用迁移到 Heroku 平台。其实我并不使用 Bigtable,而 webapp2 让我迁移的成本大大降低。

现在我遇到了处理静态文件的问题。

有没有什么好的做法?如果有的话,请告诉我。

提前谢谢你们。

编辑

现在我在使用 paste 作为我的 WSGI 服务器。paste.StaticURLParser() 应该是我需要用来处理静态文件的工具。不过我不知道怎么把它和 webapp2.WSGIApplication() 结合起来。有人能帮我吗?

也许我需要重写 webapp2.RequestHandler 类,以便正确加载 paste.StaticURLParser()

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

任何帮助都将不胜感激!

3 个回答

2

虽然我可能来得有点晚,但我其实更喜欢DirectoryApp。它的处理方式有点像AppEngine。我可以在我的src目录里创建一个“静态”目录,然后在我的HTML(或者其他地方)中像这样引用它们: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')
2

这样做可以让你的代码在上线时更容易使用,因为你可以用nginx来提供静态文件,比如图片和样式表。

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

下面是我让这个功能正常工作的方式。

我猜依赖一个级联应用可能不是最有效的选择,但对于我的需求来说,这已经足够好了。

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

撰写回答