POST-then-redirect和MethodViews

时间:2012-08-08 15:37:45

标签: python redirect flask

说我有MethodView看起来像这样:

from flask import jsonify, request, redirect, flash, views, url_for
from models import Provider

class ProviderAPI(views.MethodView):

    def get(self, provider_id):
        if provider_id is not None:
            provs = [Provider.objects.get_by_id(provider_id)]
        else:
            provs = Provider.objects.all()
        return jsonify(dict(objects=[x.attributes_dict for x in provs]))

    def post(self):
        data = request.form.to_dict()
        data['index'] = request.form.getlist('index')
        if data:
            obj = Provider(**data)
            if obj.is_valid():
                obj.save()

                flash('%s created' % obj, )

                return redirect(url_for(
                    'provider',
                    provider_id=obj.id,
                    )
                )
            else:
                return jsonify(obj.errors)

    def put(self, provider_id):
        pass

    def delete(self, provider_id):
        pass

这已在此已知代码段中注册:

def register_api(view, endpoint, url, pk='id', pk_type='int'):
    """
    Helper for the API boilerplate, `view` must inherit from MethodView 

    register_api(UserAPI, 'user', '/user/', pk='provider_id')
    """
    view_func = view.as_view(endpoint)

    app.add_url_rule(url, defaults={pk: None},
                     view_func=view_func, methods=['GET',])
    app.add_url_rule(url, view_func=view_func, methods=['POST',])
    app.add_url_rule('%s<%s:%s>' % (url, pk_type, pk), view_func=view_func,
                     methods=['GET', 'PUT', 'DELETE'])

问题是,在post成功后,它被重定向到get函数,但是POST调用它会引发Method Not Allowed

127.0.0.1 - - [08/Aug/2012 12:35:21] "POST /provider/ HTTP/1.1" 302 -
127.0.0.1 - - [08/Aug/2012 12:35:21] "POST /provider/44 HTTP/1.0" 405 -

有没有办法告诉redirect使用GET来电?

1 个答案:

答案 0 :(得分:2)

看起来可以使用与先前请求相同的请求方法进行302重定向。但是,303重定向应始终使用GET(source)。

重定向功能可以获取状态代码。试试这个:

            return redirect(url_for(
                'provider',
                provider_id=obj.id,
                ),
                code=303
            )

编辑:类似讨论:Redirecting to URL in Flask