コード例 #1
0
ファイル: google_search.py プロジェクト: pbx/kupfer
 def get_items(self):
     try:
         query = urllib.urlencode({'q': self.query})
         if ssl_support.is_supported():
             conn = ssl_support.VerifiedHTTPSConnection(SEARCH_HOST,
                                                        timeout=5)
             self.output_debug("Connected to", SEARCH_HOST, "using SSL")
         else:
             conn = httplib.HTTPConnection(SEARCH_HOST, timeout=5)
         conn.request("GET", SEARCH_PATH + query)
         response = conn.getresponse()
         ctype = response.getheader("content-type", default="")
         parts = ctype.split("charset=", 1)
         encoding = parts[-1] if len(parts) > 1 else "UTF-8"
         search_results = response.read().decode(encoding)
         response.close()
     except (IOError, httplib.HTTPException) as exc:
         raise OperationError(unicode(exc))
     results = json_decoder(search_results)
     data = results['responseData']
     more_results_url = data['cursor']['moreResultsUrl']
     total_results = data['cursor'].get('estimatedResultCount', 0)
     for h in data['results']:
         uq_url = urllib.unquote(h['url'])
         uq_title = _xml_unescape(h['titleNoFormatting'])
         yield UrlLeaf(uq_url, uq_title)
     yield CustomDescriptionUrl(more_results_url,
             _('Show More Results For "%s"') % self.query,
             _("%s total found") % total_results)
コード例 #2
0
ファイル: google_translate.py プロジェクト: jchtt/kupfer-adds
def _translate(text, lang):
    ''' Translate @text to @lang. '''
    query_param = urllib.urlencode(
        dict(v="1.0", langpair="|" + lang, q=text.encode('utf-8')))
    try:
        if ssl_support.is_supported():
            conn = ssl_support.VerifiedHTTPSConnection(_GOOGLE_TRANSLATE_HOST,
                                                       timeout=5)
            pretty.print_debug(__name__, "Connected to",
                               _GOOGLE_TRANSLATE_HOST, "using SSL")
        else:
            conn = httplib.HTTPConnection(_GOOGLE_TRANSLATE_HOST, timeout=5)
        conn.request("POST", _GOOGLE_TRANSLATE_PATH, query_param, _HEADER)
        resp = conn.getresponse()
        if resp.status != 200:
            raise ValueError('invalid response %d, %s' %
                             (resp.status, resp.reason))

        response_data = resp.read()
        encoding = _parse_encoding_header(resp)
        response_data = response_data.decode(encoding, 'replace')
        pretty.print_debug(__name__, "Translate response:",
                           repr(response_data))
        try:
            resp = json_decoder(response_data)
            yield resp['responseData']['translatedText'], ''
        except:
            pretty.print_exc(__name__)
            yield text, ''

    except socket.timeout:
        yield _("Google Translate connection timed out"), ""
    except (httplib.HTTPException, ValueError), err:
        pretty.print_error(__name__, '_translate error', repr(text), lang, err)
        yield _("Error connecting to Google Translate"), ""
コード例 #3
0
ファイル: google_translate.py プロジェクト: CharString/kupfer
def _translate(text, lang):
	''' Translate @text to @lang. '''
	query_param = urllib.urlencode(dict(v="1.0",langpair="|"+lang,
		                                q=text.encode('utf-8')))
	try:
		if ssl_support.is_supported():
			conn = ssl_support.VerifiedHTTPSConnection(_GOOGLE_TRANSLATE_HOST,
			                                           timeout=5)
			pretty.print_debug(__name__, "Connected to",
			                   _GOOGLE_TRANSLATE_HOST, "using SSL")
		else:
			conn = httplib.HTTPConnection(_GOOGLE_TRANSLATE_HOST, timeout=5)
		conn.request("POST", _GOOGLE_TRANSLATE_PATH, query_param, _HEADER)
		resp = conn.getresponse()
		if resp.status != 200:
			raise ValueError('invalid response %d, %s' % (resp.status,
					resp.reason))

		response_data = resp.read()
		encoding = _parse_encoding_header(resp)
		response_data = response_data.decode(encoding, 'replace')
		pretty.print_debug(__name__, "Translate response:", repr(response_data))
		try:
			resp = json_decoder(response_data)
			yield resp['responseData']['translatedText'], ''
		except:
			pretty.print_exc(__name__)
			yield text, ''

	except socket.timeout:
		yield  _("Google Translate connection timed out"), ""
	except (httplib.HTTPException, ValueError), err:
		pretty.print_error(__name__, '_translate error', repr(text), lang, err)
		yield  _("Error connecting to Google Translate"), ""
コード例 #4
0
ファイル: shorten_links.py プロジェクト: CharString/kupfer
	def get_items(self):
		yield TinyUrl()
		yield IsGd()
		yield VGd()
		yield BitLy()
		if ssl_support.is_supported():
			yield BitLySSL()
コード例 #5
0
ファイル: google_search.py プロジェクト: jchtt/kupfer-adds
 def get_items(self):
     try:
         query = urllib.urlencode({'q': self.query})
         if ssl_support.is_supported():
             conn = ssl_support.VerifiedHTTPSConnection(SEARCH_HOST,
                                                        timeout=5)
             self.output_debug("Connected to", SEARCH_HOST, "using SSL")
         else:
             conn = httplib.HTTPConnection(SEARCH_HOST, timeout=5)
         conn.request("GET", SEARCH_PATH + query)
         response = conn.getresponse()
         ctype = response.getheader("content-type", default="")
         parts = ctype.split("charset=", 1)
         encoding = parts[-1] if len(parts) > 1 else "UTF-8"
         search_results = response.read().decode(encoding)
         response.close()
     except (IOError, httplib.HTTPException) as exc:
         raise OperationError(unicode(exc))
     results = json_decoder(search_results)
     data = results['responseData']
     more_results_url = data['cursor']['moreResultsUrl']
     total_results = data['cursor'].get('estimatedResultCount', 0)
     for h in data['results']:
         uq_url = urllib.unquote(h['url'])
         uq_title = _xml_unescape(h['titleNoFormatting'])
         yield UrlLeaf(uq_url, uq_title)
     yield CustomDescriptionUrl(
         more_results_url,
         _('Show More Results For "%s"') % self.query,
         _("%s total found") % total_results)
コード例 #6
0
ファイル: shorten_links.py プロジェクト: jchtt/kupfer-adds
 def get_items(self):
     yield TinyUrl()
     yield IsGd()
     yield VGd()
     yield BitLy()
     if ssl_support.is_supported():
         yield BitLySSL()
コード例 #7
0
ファイル: shorten_links.py プロジェクト: CharString/kupfer
	def process(self, url):
		"""Shorten @url or raise ValueError"""
		query_string = urllib.urlencode({self.url_key : url})
		try:
			if self.use_https and ssl_support.is_supported():
				conn = ssl_support.VerifiedHTTPSConnection(self.host, timeout=5)
				pretty.print_debug(__name__, "Connected SSL to", self.host)
			else:
				conn = httplib.HTTPConnection(self.host, timeout=5)
			conn.request("GET", self.path+query_string)
			resp = conn.getresponse()
			if resp.status != 200:
				raise ValueError('Invalid response %d, %s' % (resp.status,
					resp.reason))
			
			result = resp.read()
			return result.strip()

		except (httplib.HTTPException, IOError, ValueError) as exc:
			raise ValueError(exc)
		return _('Error')
コード例 #8
0
ファイル: shorten_links.py プロジェクト: jchtt/kupfer-adds
    def process(self, url):
        """Shorten @url or raise ValueError"""
        query_string = urllib.urlencode({self.url_key: url})
        try:
            if self.use_https and ssl_support.is_supported():
                conn = ssl_support.VerifiedHTTPSConnection(self.host,
                                                           timeout=5)
                pretty.print_debug(__name__, "Connected SSL to", self.host)
            else:
                conn = httplib.HTTPConnection(self.host, timeout=5)
            conn.request("GET", self.path + query_string)
            resp = conn.getresponse()
            if resp.status != 200:
                raise ValueError('Invalid response %d, %s' %
                                 (resp.status, resp.reason))

            result = resp.read()
            return result.strip()

        except (httplib.HTTPException, IOError, ValueError) as exc:
            raise ValueError(exc)
        return _('Error')