POST-then-redirect 和 MethodViews [英] POST-then-redirect and MethodViews
问题描述
假设我有一个看起来像这样的 MethodView
:
Say I have a MethodView
looking like this:
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
这用这个已知片段注册:
This get registered with this known snippet:
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
调用并引发方法不允许
.
The thing is, that after the post
is successful it'm being redirected the get
function but with a POST
call and it raises 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
调用?
Is there a way to tell redirect
to use a GET
call instead?
推荐答案
看起来 302 重定向可以使用与前一个请求相同的请求方法进行.但是,303 重定向应始终使用 GET(source).
It looks like a 302 redirect can be made with the same request method as the previous request. A 303 redirect, however, should always use GET (source).
重定向功能可以接受状态代码.试试这个:
The redirect function can take a status code. Try this:
return redirect(url_for(
'provider',
provider_id=obj.id,
),
code=303
)
类似讨论:重定向到 Flask 中的 URL
这篇关于POST-then-redirect 和 MethodViews的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!