2011-12-12 65 views
5

我現在正在將我的小型Google App Engine應用程序遷移到Heroku平臺。我實際上並沒有使用Bigtable,並且webapp2大大降低了我的遷移成本。如何在Heroku中使用Python 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() 

任何幫助將不勝感激!

回答

6

下面是我如何得到這個工作。

我猜測依賴級聯應用程序不是最有效的選擇,但它對我的需求足夠好。

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

感謝您的回覆。我會稍後再試!我不知道'Cascade'。 – Japboy

+0

您可以在開發過程中使用如下變量來爲靜態文件提供服務:if DEBUG:etc.和生產用途類似於nginx。 –

+0

謝謝!正在尋找這個答案。 – Amirshk

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

考慮我遲到的遊戲,但我其實喜歡DirectoryApp好一點。它處理的事情更像AppEngine。我可以在我的src目錄「靜態」的目錄,然後我可以引用那些在我的HTML(或其他)都是這個:http:..本地主機:8080 /靜態/ 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') 
相關問題