装饰者在Django中覆盖POST,GET和REQUEST - 做对吗? [英] Decorator overwriting POST, GET and REQUEST in Django - doing it right?

查看:113
本文介绍了装饰者在Django中覆盖POST,GET和REQUEST - 做对吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Django中,我创建了一个函数装饰器,在这个例子中可以创建一个提供的POST / GET参数的小写版本,并且在视图处理所有这些参数之前更新REQUEST。
我为此创建了以下装饰器:

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

这是正确的方法吗?我有点担心我以这样的方式攻击Django的WSGIRequest对象,其他Django功能可能看不到更新的GET / POST / REQUEST对象。

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.

推荐答案

如果您使用表单,您可以在表单本身做小写。

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

虽然实施工作是IMO,我有一个问题对于每一个电话,您最终复制获取/发布字典,搜索它们,转换字段并将结果追加回 request._request ,您需要了解能够使用它。我认为这有点过分了...

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).

另一个解决方案可以通过javascript在HTML页面中执行。您可以(硬)对模板进行编码,创建自定义窗口小部件,或使用类似于在窗口小部件中指定的属性以及jquery调用...

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...

这篇关于装饰者在Django中覆盖POST,GET和REQUEST - 做对吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆