如何在Python/Flas中从CatchAll方法重定向而不重新匹配

2024-09-28 22:23:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Python和Flask构建一个Web站点,我希望该站点的运行方式与GrooveShark和Twitter相同:有一个带有$.ajax调用的主页面,它将另一个.html文件的内容附加到母版页的a中。在

目前,我的主页面包含一个$.ajax,它调用我的web服务器传递当前的window.location.href

我想知道如何捕捉Python/Flask web服务器中的所有Url,然后,在特定条件下,不使用begin-recatch方法进行重定向!在

例如。 基于http://flask.pocoo.org/snippets/57/

@app.route('/', defaults={'p_path': ''})
@app.route('/<path:p_path>')
def CatchAll(p_path):
    if(p_path.startswith("page/")):
        #if (route exist...I don't know yet how to do this part...):
            #Call the method routed to the /Page/ route
            #  Without being re-catched by the CatchAll method
    elif (p_path.startswith("api/")):
        #Run a method on my API that will call my controller > DAL > Database
        #  Without being re-catched by the CatchAll method
    else:
        #I render my masterpage
        return render_template("masterPage.html")

因此,如果第一次在浏览器中加载网站,它将加载MasterPage,其中包含ajax调用,该调用将调用web服务器传递的URL,如“/Page/Contact”,该URL将呈现我将附加到<div>中的html

你知道怎么做吗?在

这是我的第一个草稿,请随时给我评论(优化、最佳实践、性能),因为我是Python/Flask的新手


Tags: thepath服务器webappflaskif站点
1条回答
网友
1楼 · 发布于 2024-09-28 22:23:49

你不需要为你的案子抓住所有的请求。 您可以通过GET请求设置主页访问,通过POST设置ajax,例如使用next decorator:

class AjaxApp(Flask or Blueprint):

    def ajax_route(self, rule, **options):
        def decorator(f):
            @functools.wraps(f)
            def wrapper(*args, **kwargs):
                if request.method == 'POST':
                    return f(*args, **kwargs)
                return render_template("masterPage.html")

            endpoint = options.pop('endpoint', None)
            methods = options.pop('methods', ['GET', 'POST'])
            self.add_url_rule(rule, endpoint, wrapper, methods=methods, **options)
            return wrapper
        return decorator

如果不想限制对每个方法的访问,也可以只检查X-Requested-With头:

^{pr2}$

这种方法非常隐式,您应该只对特殊的ajax页面使用ajax_route,但是它增加了复杂性,并且可能更好地使用可插拔视图http://flask.pocoo.org/docs/views/。在

如果您希望按api、页面和其他方式分组逻辑,可以查看蓝图http://flask.pocoo.org/docs/blueprints/

class AjaxBlueprint(Blueprint):
    def route(self, rule, **options):
        # one of examples

ajax = AjaxBlueprint('ajax', __name__)

@ajax.route('/main.html')
def main():
    return render_template('main.html')

app.register_blueprint(ajax)

并使用blueprint的一个示例方法重写route。所以ajaxbluprint在这种情况下会有自定义的逻辑,其他的蓝图会有独立的。在

相关问题 更多 >