Search code examples
python-3.xpyramid

How to read the http post parameters with pyramid?


How to read the http post parameters with pyramid? I know how to do that in case the parameters concern a piece of json, but how should I read it in case it concerns a simple key=value pair? Example of a http post request (testing with hurl.it):

Accept: */*
Accept-Encoding: gzip, deflate
Content-Length: 16
Content-Type: application/x-www-form-urlencoded
Host: test.bydehand.com
User-Agent: runscope/0.1

id=tr_uH4yPGBahB 

If I perform a print 'request.json_body" in code, it complaints, probably because it's not a piece of valid json:

  File "/home/develop/app/daisy/payment/payment_view.py", line 88, in payment_webhook
    logger.debug("Receiving a webhook payment request body: [%s]", str(request.json_body))
  File "/home/develop/env/lib/python3.4/site-packages/pyramid/request.py", line 237, in json_body
    return json.loads(text_(self.body, self.charset))
  File "/usr/lib64/python3.4/json/__init__.py", line 318, in loads
    return _default_decoder.decode(s)
  File "/usr/lib64/python3.4/json/decoder.py", line 343, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib64/python3.4/json/decoder.py", line 361, in raw_decode
    raise ValueError(errmsg("Expecting value", s, err.value)) from None

How can I read these key/value pairs and put them in a dict?


Solution

  • request.body contains the raw body. request.POST is a MultiDict that contains the parsed values.

    In your case, request.POST['id'] would contain the value.

    You can use request.POST.get('id') and request.POST.getall('id') if you're not sure if the value is there or if it may be there many times.