2014-07-08 1 views
2

는 I는 python3.x CGI 스크립트에 cgi.FieldStorage()를 호출 할 때 내가받을 다음과 같은 오류 :CGI를 사용하지 않고 python3.x에서 POST "데이터"변수를 얻으려면 어떻게해야합니까?

[Traceback: error in module x on line y]: 
    cgi.FieldStorage() 
File "/usr/lib64/python3.3/cgi.py", line 553, in __init__ 
    self.read_single() 
File "/usr/lib64/python3.3/cgi.py", line 709, in read_single 
    self.read_binary() 
File "/usr/lib64/python3.3/cgi.py", line 731, in read_binary 
    self.file.write(data) 
TypeError: must be str, not bytes 

어떻게 아약스 호출에서 내 POST data 변수를받을 수 있나요?

예 Ajax 호출 :

function (param) { 
    $.ajax({ 
     type: "POST", 
     url: "/cgi-bin/mycgi.py/TestMethod", 
     data: JSON.stringify({"foo": "bar"}), 
     contentType: "application/json; charset=utf-8", 
     dataType: "json", 
     success: function (result) { 
      alert("Success " + result); 
     }, 
     error: function() { 
      alert("Failed"); 
     } 
    }); 
} 
+0

저는 jQuery에 익숙하지 않으므로 이것을 주석으로 게시하겠습니다. 'contentType : "x-www-form-urlencoded"를 시도해보십시오. – Yosh

답변

3

http://lucumr.pocoo.org/2013/7/2/the-updated-guide-to-unicode/에 따르면

"There are also some special cases in the stdlib where strings are 
very confusing. The cgi.FieldStorage module which WSGI applications are 
sometimes still using for form data parsing is now treating QUERY_STRING 
as surrogate escaping, but instead of using utf-8 as charset for the URLs 
(as browsers) it treats it as the encoding returned by 
locale.getpreferredencoding(). I have no idea why it would do that, but 
it's incorrect. As workaround I recommend not using cgi.FieldStorage for 
query string parsing." 


이 문제에 대한 해결책은 POST 데이터 파라미터 읽을 sys.stdin.read을 사용하는 것이다. 그러나 cgi 응용 프로그램 은 뭔가 읽을 예정이고 아무 것도 보내지 않을 경우을 걸어 놓을 수 있습니다. http://oreilly.com/openbook/cgi/ch04_02.html

1

허용 된 대답은 나를 위해 작동하지 않았다

#!/usr/bin/env python3 
import os, sys, json 
data = sys.stdin.read(int(os.environ.get('HTTP_CONTENT_LENGTH', 0))) 
# To get data in a native python dictionary, use json.loads 
if data: 
    print(list(json.loads(data).keys()]) # Prints out keys of json 

# (You need to wrap the .keys() in list() because it would otherwise return 
# "dict_keys([a, b, c])" instead of [a, b, c]) 

당신은 여기 CGI의 내부에 대한 자세한 내용을보실 수 있습니다 :이 작업은 HTTP 헤더에서 발견되는 바이트 수 읽기에 의해 해결된다 데이터를 반환하지 않았습니다 (Windows Server 2012 & Python 3.4 사용).

물론 다른 사람들을 위해 일했을 수도 있지만, 내가 경험 한 것과 동일한 상황을 발견 한 사람들을 돕기 위해 게시하고 싶습니다.

자신을 많은 유사한 질문 & 블로그 게시물 관련을 트롤 어업, 다른 접근 방법 테스트 한 후, 나를 위해 실적이 좋은 조합이었다 :

totalBytes=int(os.environ.get('HTTP_CONTENT_LENGTH')) 
reqbin=io.open(sys.stdin.fileno(),"rb").read(totalBytes) 

사람들이 줄 내가 원시 이진 데이터 (이미지를 수신하기 위해 필요한 모든 것을했다, 오디오 파일 등)을 추출한 다음 파일로 덤프합니다. 당신이 문자열로 수신 된 데이터를 설정하려면

당신이 후 사용할 수 있습니다

reqstr=reqbin.decode("utf-8") 

을 마지막으로, 문제의 요구 사항을 충족하기 위해, 당신은 사용하여 JSON으로 그 구문을 분석 할 수 있습니다

thejson=json.loads(reqstr) 

나는 정말로 이것이 다른 길을 찾을 수 없었던 다른 사람들을 돕기를 희망합니다!

1

새로운 답변을 작성해 주셔서 죄송합니다. 귀하의 질문에 대해 충분한 평판을 얻지 못했습니다. XD

나는 당신과 같은 문제가 있습니다. 나는 여러 가지 해결책을 시도했지만 효과가 없었다.

(https://stackoverflow.com/a/27893309/5392101) GET에 대한

: POST에 대한

raw_data = os.getenv("QUERY_STRING") 

:

그럼 난 @Schien 응답 다음과 같은 질문에서 훨씬 쉬운 방법 (덕분에 많은 사람을) 발견
raw_data = sys.stdin.read() 

그리고 그것은 매력처럼 작동했습니다!

관련 문제