CSRF処理を追加するために、Djangoのrender_to_response()のラッパー関数を書いています。
ロジックは次のとおりです。
def some_view (request)
dictionary = {'context_param': some_param}
dictionary.update(csrf(request))
# ... view code here
return render_to_response("a_template.html", dictionary)
render_to_response() には次の署名があります。
def render_to_response(*args, **kwargs)
私は透過的なラッパーを書きたいと思っています - いくつかの機能(前述)を追加し、他のものはそのままにしておきます。私は次のように書くべきだと思います:
def csrf_response (request, *args, **kwargs):
# Here I need to somehow extract dictionary from args or kwargs
if dictionary is None:
dictionary = {}
dictionary.update(csrf(request))
# And here I somehow need to pass dictionary into render_to_response() fot the furher processing
return render_to_response(*args, **kwargs)
質問は - args/kwargs から必要なパラメータを抽出し (それを変更して)、さらに渡すためのベストプラクティスは何ですか?
ところで render_to_response() のコードは少し奇妙に思えました。ここにあります:
def render_to_response(*args, **kwargs):
"""
Returns a HttpResponse whose content is filled with the result of calling
django.template.loader.render_to_string() with the passed arguments.
"""
httpresponse_kwargs = {'mimetype': kwargs.pop('mimetype', None)}
return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs)
誰かがすべての位置引数でそれを呼び出した場合、kwargs は空になりますが、mimetype
パラメータは最後の位置引数として指定されますか? その場合、その動作は間違っているようです。