sorin
sorin

Reputation: 170470

How to properly write a python cgi script that receives json data?

My current test python script does something like:

#!/usr/bin/env python
import sys
data = sys.stdin.read()
myjson = json.loads(data)

The problem is that even if this worked in some case, on others it seems to block, probably at the read().

For some other reasons I am forced to use tomcat to the cgi scripts, not sure if this matters anyway.

Upvotes: 3

Views: 1953

Answers (1)

jd.
jd.

Reputation: 10948

You'll need to check the content length before reading and limit the number of byte read by sys.stdin.read(). See cgi.parse_header().

Update:

Your incoming data comes through the environment which is populated by the web server. It is accessible in os.environ.

import os
from cgi import parse_header
os.environ['Content-Type'] = 'text/html; charset=utf-8'
parse_header(os.environ['Content-Type'])
# returns ('text/html', {'charset': 'utf-8'})

So in your CGI script you need (roughly):

import os, cgi, sys
cl, _ = parse_header(os.environ['Content-Length'])
data = sys.stdin.read(int(cl))

Upvotes: 2

Related Questions