2016-02-10 71 views
1

CASE更新日期:2016年2月10日19:45 @ UTC無法註冊的藍圖

我已經研究了好幾個星期的StackOverflow閱讀一對夫婦的相關書籍瓶後,我一直測試和嘗試不同的配置選項,玩幾個代碼,最後我不得不寫信尋求幫助,因爲我完全陷入困境,我無法單獨前進。對此我很抱歉。

問題:我無法在我的應用程序中正確註冊藍圖。我做錯了什麼或者沒有以正確的方式完成。 屬於藍圖的路由不起作用。

收到的錯誤:找不到。在服務器上未找到請求的URL。如果您手動輸入網址,請檢查拼寫並重試。

我正在嘗試使用Flask和Flask-Restful構建一個API。我是Flask的新手,也是Flask-Restful的新手,所以,你可以想象我現在的實際學習曲線有多大。

目前的時間,我的項目有這方面的:

/ 
├── PROJECT 
│   ├── __init__.py 
│   └── api_1_0 
│    ├── __init__.py 
│    ├── resources 
│    │   ├── __init__.py 
│    │   └── users.py 
│    └── routes.py 
├── config.py 
└── run.py 

該計劃 項目(稱爲內部自理)文件夾將在未來兩三包內(用於Web模塊屬於到同一個項目)。到目前爲止,他們中唯一一個是api_1_0。

想法#1是建立一個具有一些基本功能的API。現在,重點是提供簡單的消息(返回'hi hi'),以確認所有塊都在共同工作。

想法#2是構建API作爲SelfCare包內的藍圖。現在我只能有1個API,但後來我migth有兩個並行運行(v1和v2)。

前些日子我設法去上班點子1想法2是我不能去上班。抱歉。

我現在的文件有這樣的內容:

文件:run.py

from SelfCare import create_app 

app = create_app(config_name='development') 

if __name__ == '__main__': 
    app.run() 

文件:config.py

import os 


class Config: 
    SECRET_KEY = 'whatever' 
    APP_DIR = os.path.abspath(os.path.realpath(__file__)) 
    STATIC_DIR = os.path.join(APP_DIR, 'static') 
    IMAGES_DIR = os.path.join(STATIC_DIR, 'images') 
    STYLES_DIR = os.path.join(STATIC_DIR, 'styles') 
    TEMPLATES_DIR = os.path.join(STATIC_DIR, 'templates') 

    # Method with an application instance (for now, just a bypass) 
    @staticmethod 
    def init_app(app): 
     pass 

class DevelopmentConfig(Config): 
    DEBUG = True 

class TestingConfig(Config): 
    DEBUG = True 

class ProductionConfig(Config): 
    DEBUG = False 

# Finally, this is a dead simple configuration dictionary 
config = { 
    # Possible profiles to run under 
    'development': DevelopmentConfig, 
    'testing': TestingConfig, 
    'production': ProductionConfig, 
    # Default application profile 
    'default': DevelopmentConfig 
} 

文件:項目/init的.py

from flask import Flask, render_template 
from flask.ext.moment import Moment 
from config import config 

moment = Moment() 

def create_app(config_name): 
    app = Flask(__name__) 
    app.config.from_object(config[config_name]) 
    config[config_name].init_app(app) 

    # attach routes and custom error pages here 
    @app.route('/') 
    def index(): 
     return 'Here we will start' 

    # HERE IT IS SUPPOSED THE BLUEPRINT IS REGISTERED 
    # AND ROUTES FROM BLUEPRINT ARE INCORPORATED TO MAIN PROGRAM 
    from .api_1_0 import api as api_blueprint 
    app.register_blueprint(api_blueprint) 

    return app 

文件:項目/ api_1_0/__ init__。PY

from flask import Blueprint 

api = Blueprint('api', __name__) 

from .resources import users 

文件:項目/ api_1_0/routes.py

from .api_1_0 import resources 

@resources.route('/user', methods=['GET']) 
def users(): 
    return 'routes.py en blueprint api_1_0' 

文件:項目/ api_1_0 /資源/ __ init__.py

This file is empty (a constructor). 

文件:項目/ api_1_0/resources/user.py

from flask_restful import Resource, reqparse, abort 

# With the following dictionrary I do simulate a database connection 
USERS = { 
    'user1': {'task': 'Build an API'}, 
    'user2': {'task': 'Coordinate development'}, 
    'user3': {'task': 'Build core'}, 
} 

def abort_if_user_doesnt_exist(user): 
    if user not in USERS: 
     abort(404, message="User {} doesn't exist".format(user)) 

parser = reqparse.RequestParser() 
parser.add_argument('task') 


class User(Resource): 

    def get(self, user): 
     abort_if_user_doesnt_exist(user) 
     return USERS[user] 

    def delete(self, user): 
     abort_if_user_doesnt_exist(user) 
     del USERS[callsign] 
     return '', 204 

    def put(self, user): 
     args = parser.parse_args() 
     task = {'task': args['task']} 
     USERS[user] = task 
     return task, 201 

因此,routes.py似乎不起作用,所以我不能進一步在API中。我被卡住了,對不起......可能這個錯誤只是作爲一塊大石頭從我身上出現,我看不到它。抱歉。

任何幫助將遠遠超過讚賞。 此致敬禮。

+0

請[edit]包含[mcve]。什麼不起作用?你會得到什麼錯誤? – davidism

+0

Hi @davidism:編輯帖子以包含更多信息並澄清問題:藍圖未在主應用程序中註冊,藍圖路由無法正常工作。謝謝。 – Jonathan

+0

您可以添加一個http會話,顯示您發送的請求和您收到的回覆?也許從curl輸出? – Miguel

回答

0

您沒有正確註冊flask-restful.Api和REST路由。

安裝Flask-DebugToolbar - 它會幫助你顯示你的註冊路線。

在文件config.py添加以下兩行到配置類::

DEBUG_TOOLBAR_ENABLED = True 
REST_URL_PREFIX = '/api' 

在文件:

如下更改代碼PROJECT/init.py變化:

from flask import Flask, render_template 
from flask.ext.moment import Moment 
from config import config 

moment = Moment() 

def create_app(config_name): 
    app = Flask(__name__) 
    app.config.from_object(config[config_name]) 
    config[config_name].init_app(app) 

    try: 
     from flask_debugtoolbar import DebugToolbarExtension 
     DebugToolbarExtension(app) 
    except: 
     pass 

    # attach routes and custom error pages here 
    @app.route('/') 
    def index(): 
     return render_template('index.html') 

    # HERE IT IS SUPPOSED THE BLUEPRINT IS REGISTERED 
    # AND ROUTES FROM BLUEPRINT ARE INCORPORATED TO MAIN PROGRAM 
    from PROJECT.api_1_0 import api_bp, API_VERSION_V1 
    app.register_blueprint(
     api_bp, 
     url_prefix='{prefix}/v{version}'.format(prefix=app.config['REST_URL_PREFIX'], version=API_VERSION_V1), 
    ) 
    # This registers the actual routes 
    import api_1_0.routes 

    return app 

在文件:PROJECT/api_1_0/__ init__.py更改爲:

from flask import Blueprint 
import flask_restful 

API_VERSION_V1 = 1 

api_bp = Blueprint('api', __name__) 
api_v1 = flask_restful.Api(api_bp) 

將您的資源映射到路由;文件:PROJECT/api_1_0/routes.py變化:

from PROJECT.api_1_0 import api_v1 
from PROJECT.api_1_0.resources.user import User 

api_v1.add_resource(User, '/user/<string:user>') 

你的路線,如今會是這樣的:

http://127.0.0.1:5000/api/v1/user/user1返回:

{ 
    "task": "Build an API" 
} 

http://127.0.0.1:5000/api/v1/user/user2返回:

{ 
    "task": "Coordinate development" 
} 

備註路線如何建立起來的;來自config的REST_URL_PREFIX加上版本號加上routes.py add_resource中的url。

+0

Flask-DebugToolbar是一個非常寶貴的工具。非常感謝! ;) – Jonathan

0

它的工作原理!

我很困惑,藍圖必須註冊的方式。也許是因爲我在使用PyCharm 5 Pro,即使現在代碼運行得像一個魅力,IDE也在文件PROJECT/api_1_0/___ init____中告訴我。PY此消息:

api_v1 = flask_restful.Api(api_bp) 

api_bp - >期望型 '瓶',得到了 '藍圖' 來代替。

檢查檢測函數調用表達式中的類型錯誤。由於 動態調度和鴨打字,這是可能的限制,但 有用的案件數量。函數參數的類型可以在docstrings或Python 3 functon註釋中指定爲 。

不,我知道我不必太在意這條消息(或者我的IDE配置錯誤)。非常感謝所有。

問候。