【发布时间】:2015-10-07 22:03:25
【问题描述】:
我还是 Flask 的新手,所以可能有一种明显的方法可以做到这一点,但到目前为止我还无法从文档中弄清楚。我的应用程序分为几个几乎完全不同的部分,它们共享诸如用户/会话/安全和基本模板之类的东西,但大多数都没有太多交互,并且应该在不同的路径下路由,例如 /part1/...。我认为这几乎正是蓝图的用途。但是,如果我需要在蓝图下进一步对路由和逻辑进行分组怎么办?
例如,我有blueprint1 和url_prefix='/blueprint1',也许在此之下,我希望收集围绕着用户分享照片和其他用户评论它们的视图。我想不出比这更好的方法了:
# app/blueprints/blueprint1/__init__.py
blueprint1 = Blueprint('blueprint1', __name__, template_folder='blueprint1')
@blueprint1.route('/photos')
def photos_index():
return render_template('photos/index.html')
@blueprint.route('/photos/<int:photo_id>')
def photos_show(photo_id):
photo = get_a_photo_object(photo_id)
return render_template('photos/show.html', photo=photo)
@blueprint.route('/photos', methods=['POST'])
def photos_post():
...
这里的问题是与blueprint1 的照片部分相关的所有视图都位于“顶层”,可能带有视频或音频或其他任何东西的蓝图(命名为videos_index()...)。有没有办法以更分层的方式对它们进行分组,例如模板如何放在'blueprint1/photos' 子目录下?当然,我可以将所有照片视图放在它们自己的模块中,以使它们分开组织,但是如果我想将父路径 'blueprint1/photos' 更改为其他路径怎么办?我确定我可以发明一个函数或装饰器,将相关路由分组在同一根路径下,但是我仍然必须使用 photos_ 前缀命名所有函数,并像 url_for('blueprint1.photos_show') 一样引用它们 看起来蓝图是当 Flask 应用程序变大并且您需要将相似的部分组合和划分在一起时回答,但是当蓝图本身变大时您不能做同样的事情。
作为参考,在 Laravel 中,您可以将相关的“视图”分组到 Controller 类下,其中视图是方法。控制器可以驻留在像app\Http\Controllers\Blueprint1\Photocontroller 这样的分层命名空间中,路由可以像这样分组在一起
Route::group(['prefix' => 'blueprint1'], function() {
Route::group(['prefix' => 'photos'], function() {
Route::get('/', ['as' => 'blueprint.photos.index', 'uses' => 'ModelApiController@index']);
Route::post('/', ['as' => 'blueprint.photos.store', 'uses' => 'ModelApiController@store']);
Route::get('/{id}', ['as' => 'blueprint.photos.get', 'uses' => 'ModelApiController@get'])
->where('id', '[0-9]+');
});
});
并且可以像action('Blueprint1\PhotoController@index')一样获取路线。
如果我能做一张照片蓝图,那么就做blueprint1.register_blueprint(photos_blueprint, url_prefix='/photos')之类的,这些问题就基本解决了。不幸的是,Flask 似乎不支持这样的嵌套蓝图。有没有其他方法来处理这个问题?
【问题讨论】:
标签: python design-patterns flask