use*_*455 5 python google-app-engine flask
我遇到了一个奇怪的问题(对于烧瓶中的经验可能并不那么奇怪).
我在Google App Engine的环境中运行了一个烧瓶应用程序 dev_appserver.py
我的烧瓶应用程序中有蓝图
# rest_server.py
rest_api = Blueprint('rest_api', __name__)
app = Flask(__name__)
app.register_blueprint(rest_api, url_prefix='/api') # [1] DOESN'T WORK
@rest_api.route("/")
def hello():
return "Hello World"
app.register_blueprint(rest_api, url_prefix="/api") # [2] WORKS AS EXPECTED
Run Code Online (Sandbox Code Playgroud)
我有以下内容 app.yaml
-url: "/api/.*"
script: rest_server.app
Run Code Online (Sandbox Code Playgroud)
当我localhost:8080/api/在位置[1]处注册蓝图时,我遇到错误,表示没有匹配的端点.
但是,当我在[2]注册bluerpint时,在装饰器之后的任何位置,它都有效.
是否需要在所有装饰者之后注册蓝图?
Sha*_*ghi -1
虽然您已经注册了您的蓝图,但它实际上并未注册!
关键是你的应用程序不知道存在rest_server.py
您必须将其注册在包含以下代码的同一文件中:
app = Flask(__name__)
Run Code Online (Sandbox Code Playgroud)
这应该可以解决你的问题。
我想展示我使用的蓝图的使用模式。
(这对于更好地组织代码很有用):
您的应用程序的蓝图模式
可能如下所示:
/yourapplication
runserver.py
/application #your application is a package containing some blueprints!
__init__.py
models.py
/hello #(blueprint name)
__init__.py
views_file1.py
views_file2.py
Run Code Online (Sandbox Code Playgroud)
你的runserver.py应该看起来像这样:
# runserver.py
from application import app
app.run()
Run Code Online (Sandbox Code Playgroud)
在此示例中,hello 是一个包,也是您的蓝图之一:
# application/hello/__init__.py
from flask import Blueprint
hello = Blueprint('main', __name__)
# import views of this blueprint:
from application.hello import views_file1, views_file2
Run Code Online (Sandbox Code Playgroud)
在 中导入并注册您的蓝图application/__ init__.py。你的 application/__ init__.py 应该看起来像这样:
# application/__init__.py
from flask import Flask
from .hello import hello as hello_blueprint
app = Flask(__name__)
app.register_blueprint(hello_blueprint)
from application.models import * #your models (classes, or *)
Run Code Online (Sandbox Code Playgroud)