2016-08-17 2 views
0

짧은 버전 : 이 파이썬 요청은 작동하지 않습니다. Javascript 버전이 있습니다. 왜?Python이 lib가이 Ajax 호출을 복제하도록 요청할 수없는 이유는 무엇입니까?

import json 
import requests 
url = 'https://inputtools.google.com/request?itc=ja-t-i0-handwrit&app=demopage' 

data = '{"app_version":0.4,"api_level":"537.36","device":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36","input_type":0,"options":"enable_pre_space","requests":[{"writing_guide":{"writing_area_width":200,"writing_area_height":200},"pre_context":"","max_num_results":1,"max_completions":0,"ink":[[[100,100],[20,180],[0,1]],[[20,180],[100,100],[2,3]]]}]}' 

headers = {'content-type': 'application/json'} 

r = requests.post(url, json=data, headers=headers) 
print r.json() 

긴 버전 : 나는 성공적으로 아약스 호출을이 자바 스크립트가 있습니다. 콘솔에 응답을 인쇄하고 내가 보낸 입력에서 제안 된 문자 배열을 볼 수 있습니다.

https://jsbin.com/wufesifasa/1/edit?js,console,output

var text = { 
    'app_version' : 0.4, 
    'api_level' : '537.36', 
    'device' : window.navigator.userAgent, 
    'input_type' : 0, // ? 
    'options' : 'enable_pre_space', // ? 
    'requests' : [ { 
    'writing_guide' : { 
     'writing_area_width' : 200, // canvas width 
     'writing_area_height' : 200, // canvas height 
    }, 
    'pre_context' : '', // confirmed preceding chars 
    'max_num_results' : 1, 
    'max_completions' : 0, 
    'ink' : [] 
    } ] 
}; 

// written coordinates to be sent 
text.requests[0].ink = [ 
    [[100,100],[20,180],[0,1]], 
    [[20,180],[100,100],[2,3]], 
]; 

console.log(JSON.stringify(text)) 

$.ajax({ 
    url : 'https://inputtools.google.com/request?itc=ja-t-i0-handwrit&app=demopage', 
    method : 'POST', 
    contentType : 'application/json', 
    data : JSON.stringify(text), 
    dataType : 'json', 
}).done(function(json) { 
    console.log(json); 
}); 

출력 :

[ "SUCCESS"[ "fb02254b519a9da2"[ "+", "十", "t", "T", "ナ","F ","子 " "干 ","1 ","千 "], [], [개체 개체] {is_html_escaped : 거짓}]]]

지금 내가 노력하고있어 파이썬에서 그것을 복제 할 수 있습니다. 위의 코드와 여러 변형을 사용해 보았지만 'FAILED_TO_PARSE_REQUEST_BODY'응답을받을 때마다 요청이 실패하는 Ajax와 Python 호출의 차이점은 무엇입니까?

이 질문은 thisthis과 비슷하지만 동일한 키를 여러 번 사용하고 잘못된 데이터 인코딩을 처리합니다.이 경우에는 적용되지 않습니다.

답변

0

라인 json=datadata=data이어야합니다. json 속성은 data 문자열이 아닌 사전을 허용합니다. 다음은 작동 코드의 모습입니다.

import json 
import requests 
url = 'https://inputtools.google.com/request?itc=ja-t-i0-handwrit&app=demopage' 

data = '{"app_version":0.4,"api_level":"537.36","device":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36","input_type":0,"options":"enable_pre_space","requests":[{"writing_guide":{"writing_area_width":200,"writing_area_height":200},"pre_context":"","max_num_results":1,"max_completions":0,"ink":[[[100,100],[20,180],[0,1]],[[20,180],[100,100],[2,3]]]}]}' 

headers = {'content-type': 'application/json'} 

r = requests.post(url, json=data, headers=headers) 
print r.json() 
관련 문제