2014-02-12 44 views
7

我正在使用燒瓶寧靜的工作,並且我想在我的項目中利用工廠模式和藍圖。 在app/__init__.py我有一個create_app函數來創建一個燒瓶應用程序並將其返回給外部調用者,因此調用者可以啓動應用程序。python燒瓶寧靜的藍圖和工廠模式一起工作?

def create_app(): 
    app = Flask(__name__) 
    app.config.from_object('app.appconfig.DevelopmentConfig') 
    from app.resource import resource 
    app.register_blueprint(v1, url_prefix='/api') 
    print app.url_map 
    return app 

這個函數裏面我打算註冊一個藍圖,指向帶有前綴url的實現包。

app/resource/__init__.py有下面的代碼

from flask import current_app, Blueprint, render_template 
from flask.ext import restful 
resource = Blueprint('resource', __name__, url_prefix='/api') 

@resource.route('/') 
def index():  
    api = restful.Api(current_app) 
    from resource.HelloWorld import HelloWorld 
    api.add_resource(HelloWorld, '/hello') 

我的目標是,我可以在URL /api/hello訪問的HelloWorld休息服務,但我知道上面的代碼中有一些錯誤在@resource.route('/') ...一部分。我得到了一些錯誤,如AssertionError: A setup function was called after the first request was handled. This usually indicates a bug in the app ...api.add_resource(HelloWorld, '/hello')。 你能否給我正確的方法提示?謝謝!

+0

我想我應該補充一些端點S,但我不知道如何以指示休息資源請求到期望的端點... – jeffrey

回答

15

瓶,寧靜,像所有的正確實施燒瓶擴展,支持註冊本身的兩種方法:

  1. 與實例化的應用程序(如你試圖用Api(current_app)做)
  2. 在以後某個時候使用api.init_app(app)

處理的圓形進口問題的典型方法是使用第二模式和你的create_app功能導入實例化的延伸和註冊擴展使用init_app方法:

# app/resource/__init__.py 
from resource.hello_world import HelloWorld 

api = restful.Api(prefix='/api/v1') # Note, no app 
api.add_resource(HelloWorld, '/hello') 

# We could actually register our API on a blueprint 
# and then import and register the blueprint as normal 
# but that's an alternate we will leave for another day 
# bp = Blueprint('resource', __name__, url_prefix='/api') 
# api.init_app(bp) 

,然後在create_app叫你只會加載和註冊API:

def create_app(): 
    # ... snip ... 
    # We import our extension 
    # and register it with our application 
    # without any circular references 
    # Our handlers can use `current_app`, as you already know 
    from app.resource import api 
    api.init_app(app) 
+2

我得到了異常**屬性錯誤:'nonetype'對象沒有屬性'config'**在'self.app.config.get(「ERROR_404_HELP」,True)from flask_restful在資源中調用'abort(404)'時打包。所以我切換到藍圖基於您的上述評論,這完全解決了這個問題,謝謝! – jeffrey

+0

我在註冊我的擴展後打電話給我的藍圖,所以在我調用init_app之前我不會有藍圖設置,這是錯誤的嗎? – nycynik

+0

我不是100%確定你在描述什麼,但在註冊擴展後創建藍圖肯定沒有錯。 –