Changing values on a werkzeug request object

落花浮王杯 提交于 2019-12-25 07:39:10

问题


I have a request object that comes from werkzeug. I want to change a value on this request object. This is not possible because werkzeug request objects are immutable. I understand this design decision, but I need to change a value. How do I do this?

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

I tried doing a deepcopy, but the resulting copy is immutable also. I guess I could just create my own mock object and fill in the values manually, but that is my last resort solution. Is there a better way?


回答1:


This is what I came up with:

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

Maybe no the most elegant solution, but it works.



来源:https://stackoverflow.com/questions/13784477/changing-values-on-a-werkzeug-request-object

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