From f076cca82ef4e52ce66b7d0ecf089bf7de5bfd98 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E0=A4=B6=E0=A4=82=E0=A4=A4=E0=A4=A8=E0=A5=82?= Date: Tue, 19 Nov 2013 22:03:46 +0530 Subject: [PATCH] Made following enhancements: - Instead of using urllib, moved to requests - Added support of python 3.x --- duckduckgo.py | 47 ++++++++++++++++++++++++++--------------------- requirements.txt | 1 + 2 files changed, 27 insertions(+), 21 deletions(-) create mode 100644 requirements.txt diff --git a/duckduckgo.py b/duckduckgo.py index 04ed1a5..4f9f765 100755 --- a/duckduckgo.py +++ b/duckduckgo.py @@ -1,6 +1,4 @@ -import urllib -import urllib2 -import json as j +import requests import sys __version__ = 0.242 @@ -39,24 +37,24 @@ def query(query, useragent='python-duckduckgo '+str(__version__), safesearch=Tru 'no_html': html, 'd': meanings, } + url = 'https://api.duckduckgo.com' params.update(kwargs) - encparams = urllib.urlencode(params) - url = 'http://api.duckduckgo.com/?' + encparams - - request = urllib2.Request(url, headers={'User-Agent': useragent}) - response = urllib2.urlopen(request) - json = j.loads(response.read()) - response.close() - + json = requests.get( + url, + params=params, + headers={'User-Agent': useragent} + ).json() return Results(json) class Results(object): def __init__(self, json): - self.type = {'A': 'answer', 'D': 'disambiguation', - 'C': 'category', 'N': 'name', - 'E': 'exclusive', '': 'nothing'}.get(json.get('Type',''), '') + self.type = { + 'A': 'answer', 'D': 'disambiguation', + 'C': 'category', 'N': 'name', + 'E': 'exclusive', '': 'nothing' + }.get(json.get('Type',''), '') self.json = json self.api_version = None # compat @@ -131,7 +129,7 @@ def get_zci(q, web_fallback=True, priority=['answer', 'abstract', 'related.0', ' '''A helper method to get a single (and hopefully the best) ZCI result. priority=list can be used to set the order in which fields will be checked for answers. Use web_fallback=True to fall back to grabbing the first web result. - passed to query. This method will fall back to 'Sorry, no results.' + passed to query. This method will fall back to 'Sorry, no results.' if it cannot find anything.''' ddg = query('\\'+q, **kwargs) @@ -143,13 +141,13 @@ def get_zci(q, web_fallback=True, priority=['answer', 'abstract', 'related.0', ' index = int(ps[1]) if len(ps) > 1 else None result = getattr(ddg, type) - if index is not None: + if index is not None: if not hasattr(result, '__getitem__'): raise TypeError('%s field is not indexable' % type) result = result[index] if len(result) > index else None if not result: continue if result.text: response = result.text - if result.text and hasattr(result,'url') and urls: + if result.text and hasattr(result,'url') and urls: if result.url: response += ' (%s)' % result.url if response: break @@ -159,7 +157,7 @@ def get_zci(q, web_fallback=True, priority=['answer', 'abstract', 'related.0', ' response = ddg.redirect.url # final fallback - if not response: + if not response: response = 'Sorry, no results.' return response @@ -167,13 +165,20 @@ def get_zci(q, web_fallback=True, priority=['answer', 'abstract', 'related.0', ' def main(): if len(sys.argv) > 1: q = query(' '.join(sys.argv[1:])) - keys = q.json.keys() + keys = list(q.json.keys()) keys.sort() + if sys.version_info >= (3,0,0): + tmp = [str, str] + else: + tmp = [str, unicode] for key in keys: sys.stdout.write(key) - if type(q.json[key]) in [str,unicode]: print(':', q.json[key]) - else: + if type(q.json[key]) in tmp: print(':', q.json[key]) + else: sys.stdout.write('\n') for i in q.json[key]: print('\t',i) else: print('Usage: %s [query]' % sys.argv[0]) + +if __name__ == '__main__': + main() diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..f229360 --- /dev/null +++ b/requirements.txt @@ -0,0 +1 @@ +requests