All pastes #84557 Raw Edit

Someone

public text v1 · immutable
·published 2006-07-11 01:54 UTC
rendered paste body
# -*- coding: utf-8 -*-

from httplib import HTTPConnection
from urllib import urlencode
import re

TRANS_GATE_URL = 'http://www.gojapan.com/translation/transmsg.php'
TRANS_REFERER = 'http://www.gojapan.com/translation/minitrans.html'

YOMI_GATE_URL = 'http://www.hiragana.jp/cgi-bin/trans2.cgi'
YOMI_REFERER = 'http://www.hiragana.jp/reading/query.php'

_COMMON_HEADERS = {
    'Accept'         : 'image/gif, image/x-xbitmap, image/jpeg, ' 
                       'image/pjpeg, application/vnd.ms-powerpoint, ' 
                       'application/vnd.ms-excel, application/msword, */*', 
    'Content-Type'   : 'application/x-www-form-urlencoded', 
    'Accept-Encoding': 'gzip, deflate', 
    'User-Agent'     : 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)', 
    'Cache-Control'  : 'no-cache', 
    'Connection'     : 'keep-alive', 
}

_COOKIE = {}

def translate(msg):
    result = httppost(
        TRANS_GATE_URL,
        {'data': msg},
        {'Referer': TRANS_REFERER}
    )
    return result['body']

def yomigana(msg):
    result = httppost(
        YOMI_GATE_URL,
        {'html': '1', 'body': msg.decode('utf-8').encode('euc-jp')},
        {'Referer': YOMI_REFERER}
    )
    return result['body']

def httppost(url, data={}, headers={}):
    protocol, host, uri = re.findall('^(https?://)([^/]+)(.*)$',url)[0]

    arr = headers.items()
    arr.extend([('Host',host)])
    arr.extend(_COMMON_HEADERS.items())
    headers = dict(arr)

    conn = HTTPConnection(host, 80)
    conn.request('POST', uri, urlencode(data), headers)
    resp = conn.getresponse()
    return {'header': dict(resp.getheaders()), 'body': resp.read()}