2012-12-09 64 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 

也許沒有最完美的解決方案,但它的工作原理。