【问题标题】:Changing values on a werkzeug request object更改 werkzeug 请求对象的值
【发布时间】:2012-12-10 02:29:59
【问题描述】:
我有一个来自 werkzeug 的请求对象。我想更改此请求对象的值。这是不可能的,因为 werkzeug 请求对象是不可变的。我理解这个设计决定,但我需要更改一个值。我该怎么做?
>>> request
<Request 'http://localhost:5000/new' [POST]>
>>> request.method
'POST'
>>> request.method = 'GET'
*** AttributeError: read only property
我尝试了deepcopy,但生成的副本也是不可变的。我想我可以创建自己的模拟对象并手动填写值,但这是我最后的解决方案。有没有更好的办法?
【问题讨论】:
标签:
python
immutability
werkzeug
【解决方案1】:
这是我想出的:
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
也许不是最优雅的解决方案,但它确实有效。