How do I send an integer to POST in Tornado AsyncHTTPTestCase.fetch ()?
I am using python Tornado framework to validate HTTP POST endpoint. I use the fetch method for this .
data = urllib.urlencode({
'integer_arg': 1,
'string_arg': 'hello'
})
resp = AsyncHTTPTestCase.fetch('/endpoint',
method='POST',
headers={'h1': 'H1',
'h2': 'H2',
'Content-Type': 'application/json'},
body=data)
When I do this, the endpoint receives integer_arg
as a string "1"
, although I want it to receive it as an integer. This is understandable because it urllib.urlencode
converts it to a string. So how can I ensure that it receives an integer?
Just deleting the call urllib.urlencode
doesn't work.
By the way, when I hit the same endpoint with the open head as shown below, the endpoint correctly gets integer_arg
as an integer 1
.
curl \
--request POST \
--header "h1: H1" \
--header "h2: H2" \
--header "Content-Type: application/json" \
--data '{
"integer_arg": 1,
"string_arg": "hello"
}' \
"http://localhost:8000/endpoint"
source to share
The body is curl
significantly different from the body in AsyncHTTPClient.fetch
. With python you urlencode the data in curl there is only json. So just change urlencode with json.dumps:
import json
from tornado.ioloop import IOLoop
from tornado.httpclient import AsyncHTTPClient
from tornado.gen import coroutine
@coroutine
def main():
client = AsyncHTTPClient()
body = json.dumps({
'integer_arg': 1,
'string_arg': 'hello'
})
yield client.fetch(
'/endpoint', method='POST', body=body,
headers={'h1': 'H1', 'h2': 'H2', 'Content-Type': 'application/json'}
)
ioloop = IOLoop.instance()
ioloop.run_sync(main)
source to share