7

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パラメータは最後の位置引数として指定されますか? その場合、その動作は間違っているようです。

4

1 に答える 1

6

の実装方法render_to_responseにより、mimetype を指定する唯一の方法は、名前付き引数を使用することです。位置引数として渡されたものはすべて に渡されloader.render_to_stringます。

特定の引数を抽出して他の引数を渡す方法の方法論は、実際に何をしているかによって異なります。常にそれを行う「正しい」方法はありません。当然のことながら、さまざまな著者には独自の好みの規則があります。

コメントの代わりに、# Here I need to somehow extract dictionary from args or kwargskwargs を辞書として直接使用し、args をタプルとして使用できます。引数については、各位置の値の意味をアサート (つまり、想定) するしかありません。

個人的には、特定の引数の値を知っているコードを書いている場合は、次のように署名で宣言することをお勧めします。

def spam(session, name, *args, clear=True, **kwargs):
  # do something with session, name, clear
  return eggs(name, *args, **kwargs)  # if eggs requires name
于 2011-05-09T18:42:44.977 に答える