Decorator overwriting POST, GET and REQUEST in Django - doing it right?

ぃ、小莉子 提交于 2019-12-11 07:47:48

问题


In Django, I have created a function decorator which can - in this example - create a lowercase version of a supplied POST/GET argument, and it updates the REQUEST before the view handles it all. I have created the following decorator for this:

def force_lowercase(*fields):
    assert isinstance(fields, tuple), "Fields must be of type tuple."

    def wrap_func(fn):
       def wrapper(request):
           post = request.POST.copy()
           get  = request.GET.copy()
           for field in fields:
               if field in post:
                   post[field] = post[field].lower()
               if field in get:
                   get[field]  = get[field].lower()

           request._post = post   
           request._get = get
           request._request = MergeDict(post,get)

           return fn(request)
       return wrapper
   return wrap_func

In my view I would have something like:

@force_lowercase(email,zipcode)
def index(request)
    #blabla

Is this the proper way to do this? I'm a bit concerned I hack Django's WSGIRequest object in such a way, other Django functionality might not see the updated GET/POST/REQUEST objects.


回答1:


If you're using a form, you could do the lowercase in the form itself.

While the implementation works IMO, I have a problem that for every single call, you end up copying the get/post dictionaries, searching through them, converting the fields and appending the result back as request._request which you need to know about to be able to use it. I think it's a bit of overkill...

I'd change it with a simple method called in the view (depending on your situation, you can either overwrite the original values with the lowercase ones or create new elements).

Another solution can be to do it in the HTML page via javascript. You can either (hard)code the template, create a custom widget, or use something like an attribute specified in the widget plus a jquery call...



来源:https://stackoverflow.com/questions/9093299/decorator-overwriting-post-get-and-request-in-django-doing-it-right

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!