Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Made following enhancements: #3

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 26 additions & 21 deletions duckduckgo.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
import urllib
import urllib2
import json as j
import requests
import sys

__version__ = 0.242
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand All @@ -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

Expand All @@ -159,21 +157,28 @@ 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

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()
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
requests