2012-12-09 58 views
0

我有一个来自werkzeug的请求对象。我想改变这个请求对象的值。这是不可能的,因为werkzeug请求对象是不可变的。我理解这个设计决定,但我需要改变一个价值。我该怎么做呢?更改werkzeug请求对象上的值

>>> request 
<Request 'http://localhost:5000/new' [POST]> 
>>> request.method 
'POST' 
>>> request.method = 'GET' 
*** AttributeError: read only property 

我试着做一个deepcopy,但最终的副本也是不可变的。我想我可以创建自己的模拟对象并手动填写值,但这是我最后的解决方案。有没有更好的办法?

回答

0

这是我想出了:

def make_duplicate_request(request): 
    """ 
    Since werkzeug request objects are immutable, this is needed to create an 
    identical request object with mutable values 
    """ 
    class Req(object): 
     method = 'GET' 
     path = '' 
     headers = [] 
     args = [] 
    r = Req() 
    r.path = request.path 
    r.headers = request.headers 
    r.is_xhr = request.is_xhr 
    r.args = request.args 
    return r 

也许没有最完美的解决方案,但它的工作原理。