on master help sign in
[fix] pep/flake8 compatibility
commitb2492c94f422e18cb8954ec983134f4fa5c7cdc0 authorasciimoo <asciimoo@gmail.com> dateMon 20 Jan 2014, 02:31 (13 years ago) parent692c0bf
23 files changed+197−109
searx/engines/__init__.py+1−1 searx/engines/currency_convert.py+5−3 searx/engines/dailymotion.py+5−2 searx/engines/deviantart.py+6−2 searx/engines/duckduckgo.py+7−5 searx/engines/duckduckgo_definitions.py+6−6 searx/engines/filecrop.py+17−8 searx/engines/flickr.py+8−2 searx/engines/github.py+5−2 searx/engines/google_images.py+8−2 searx/engines/json_engine.py+14−6 searx/engines/mediawiki.py+4−4 searx/engines/piratebay.py+18−9 searx/engines/soundcloud.py+5−2 searx/engines/stackoverflow.py+3−1 searx/engines/startpage.py+2−4 searx/engines/twitter.py+8−3 searx/engines/vimeo.py+15−12 searx/engines/xpath.py+15−11 searx/engines/yacy.py+4−2 searx/engines/youtube.py+7−7 searx/utils.py+15−5 searx/webapp.py+19−10
searx/engines/__init__.py+1−1
@@ -66,7 +66,7 @@ for engine_data in settings['engines']:
6666 for engine_attr in dir(engine):
6767 if engine_attr.startswith('_'):
6868 continue
69− if getattr(engine, engine_attr) == None:
69+ if getattr(engine, engine_attr) is None:
7070 print '[E] Engine config error: Missing attribute "{0}.{1}"'.format(engine.name, engine_attr) # noqa
7171 sys.exit(1)
7272 engines[engine.name] = engine
searx/engines/currency_convert.py+5−3
@@ -5,7 +5,7 @@ categories = []
55url = 'http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s={query}=X'
66weight = 100
77
8−parser_re = re.compile(r'^\W*(\d+(?:\.\d+)?)\W*([a-z]{3})\W*(?:in)?\W*([a-z]{3})\W*$', re.I)
8+parser_re = re.compile(r'^\W*(\d+(?:\.\d+)?)\W*([a-z]{3})\W*(?:in)?\W*([a-z]{3})\W*$', re.I) # noqa
99
1010
1111def request(query, params):
@@ -46,9 +46,11 @@ def response(resp):
4646 resp.search_params['ammount'] * conversion_rate
4747 )
4848
49− content = '1 {0} is {1} {2}'.format(resp.search_params['from'], conversion_rate, resp.search_params['to'])
49+ content = '1 {0} is {1} {2}'.format(resp.search_params['from'],
50+ conversion_rate,
51+ resp.search_params['to'])
5052 now_date = datetime.now().strftime('%Y%m%d')
51− url = 'http://finance.yahoo.com/currency/converter-results/{0}/{1}-{2}-to-{3}.html'
53+ url = 'http://finance.yahoo.com/currency/converter-results/{0}/{1}-{2}-to-{3}.html' # noqa
5254 url = url.format(
5355 now_date,
5456 resp.search_params['ammount'],
searx/engines/dailymotion.py+5−2
@@ -6,7 +6,10 @@ categories = ['videos']
66locale = 'en_US'
77
88# see http://www.dailymotion.com/doc/api/obj-video.html
9−search_url = 'https://api.dailymotion.com/videos?fields=title,description,duration,url,thumbnail_360_url&sort=relevance&limit=25&page=1&{query}'
9+search_url = 'https://api.dailymotion.com/videos?fields=title,description,duration,url,thumbnail_360_url&sort=relevance&limit=25&page=1&{query}' # noqa
10+
11+# TODO use video result template
12+content_tpl = '<a href="{0}" title="{0}" ><img src="{1}" /></a><br />'
1013
1114
1215def request(query, params):
@@ -25,7 +28,7 @@ def response(resp):
2528 title = res['title']
2629 url = res['url']
2730 if res['thumbnail_360_url']:
28− content = '<a href="{0}" title="{0}" ><img src="{1}" /></a><br />'.format(url, res['thumbnail_360_url'])
31+ content = content_tpl.format(url, res['thumbnail_360_url'])
2932 else:
3033 content = ''
3134 if res['description']:
searx/engines/deviantart.py+6−2
@@ -7,6 +7,7 @@ categories = ['images']
77base_url = 'https://www.deviantart.com/'
88search_url = base_url+'search?'
99
10+
1011def request(query, params):
1112 global search_url
1213 params['url'] = search_url + urlencode({'q': query})
@@ -22,8 +23,11 @@ def response(resp):
2223 for result in dom.xpath('//div[contains(@class, "tt-a tt-fh")]'):
2324 link = result.xpath('.//a[contains(@class, "thumb")]')[0]
2425 url = urljoin(base_url, link.attrib.get('href'))
25− title_links = result.xpath('.//span[@class="details"]//a[contains(@class, "t")]')
26+ title_links = result.xpath('.//span[@class="details"]//a[contains(@class, "t")]') # noqa
2627 title = ''.join(title_links[0].xpath('.//text()'))
2728 img_src = link.xpath('.//img')[0].attrib['src']
28− results.append({'url': url, 'title': title, 'img_src': img_src, 'template': 'images.html'})
29+ results.append({'url': url,
30+ 'title': title,
31+ 'img_src': img_src,
32+ 'template': 'images.html'})
2933 return results
searx/engines/duckduckgo.py+7−5
@@ -6,8 +6,11 @@ url = 'https://duckduckgo.com/'
66search_url = url + 'd.js?{query}&p=1&s=0'
77locale = 'us-en'
88
9+
910def request(query, params):
10− params['url'] = search_url.format(query=urlencode({'q': query, 'l': locale}))
11+ q = urlencode({'q': query,
12+ 'l': locale})
13+ params['url'] = search_url.format(query=q)
1114 return params
1215
1316
@@ -17,8 +20,7 @@ def response(resp):
1720 for r in search_res:
1821 if not r.get('t'):
1922 continue
20− results.append({'title': r['t']
21− ,'content': html_to_text(r['a'])
22− ,'url': r['u']
23− })
23+ results.append({'title': r['t'],
24+ 'content': html_to_text(r['a']),
25+ 'url': r['u']})
2426 return results
searx/engines/duckduckgo_definitions.py+6−6
@@ -3,8 +3,9 @@ from urllib import urlencode
33
44url = 'http://api.duckduckgo.com/?{query}&format=json&pretty=0&no_redirect=1'
55
6+
67def request(query, params):
7− params['url'] = url.format(query=urlencode({'q': query}))
8+ params['url'] = url.format(query=urlencode({'q': query}))
89 return params
910
1011
@@ -13,11 +14,10 @@ def response(resp):
1314 results = []
1415 if 'Definition' in search_res:
1516 if search_res.get('AbstractURL'):
16− res = {'title' : search_res.get('Heading', '')
17− ,'content' : search_res.get('Definition', '')
18− ,'url' : search_res.get('AbstractURL', '')
19− ,'class' : 'definition_result'
20− }
17+ res = {'title': search_res.get('Heading', ''),
18+ 'content': search_res.get('Definition', ''),
19+ 'url': search_res.get('AbstractURL', ''),
20+ 'class': 'definition_result'}
2121 results.append(res)
2222
2323 return results
searx/engines/filecrop.py+17−8
@@ -2,7 +2,8 @@ from urllib import urlencode
22from HTMLParser import HTMLParser
33
44url = 'http://www.filecrop.com/'
5−search_url = url + '/search.php?{query}&size_i=0&size_f=100000000&engine_r=1&engine_d=1&engine_e=1&engine_4=1&engine_m=1'
5+search_url = url + '/search.php?{query}&size_i=0&size_f=100000000&engine_r=1&engine_d=1&engine_e=1&engine_4=1&engine_m=1' # noqa
6+
67
78class FilecropResultParser(HTMLParser):
89 def __init__(self):
@@ -18,22 +19,28 @@ class FilecropResultParser(HTMLParser):
1819 def handle_starttag(self, tag, attrs):
1920
2021 if tag == 'tr':
21− if ('bgcolor', '#edeff5') in attrs or ('bgcolor', '#ffffff') in attrs:
22+ if ('bgcolor', '#edeff5') in attrs or\
23+ ('bgcolor', '#ffffff') in attrs:
2224 self.__start_processing = True
2325
2426 if not self.__start_processing:
2527 return
2628
2729 if tag == 'label':
28− self.result['title'] = [attr[1] for attr in attrs if attr[0] == 'title'][0]
29− elif tag == 'a' and ('rel', 'nofollow') in attrs and ('class', 'sourcelink') in attrs:
30+ self.result['title'] = [attr[1] for attr in attrs
31+ if attr[0] == 'title'][0]
32+ elif tag == 'a' and ('rel', 'nofollow') in attrs\
33+ and ('class', 'sourcelink') in attrs:
3034 if 'content' in self.result:
31− self.result['content'] += [attr[1] for attr in attrs if attr[0] == 'title'][0]
35+ self.result['content'] += [attr[1] for attr in attrs
36+ if attr[0] == 'title'][0]
3237 else:
33− self.result['content'] = [attr[1] for attr in attrs if attr[0] == 'title'][0]
38+ self.result['content'] = [attr[1] for attr in attrs
39+ if attr[0] == 'title'][0]
3440 self.result['content'] += ' '
3541 elif tag == 'a':
36− self.result['url'] = url + [attr[1] for attr in attrs if attr[0] == 'href'][0]
42+ self.result['url'] = url + [attr[1] for attr in attrs
43+ if attr[0] == 'href'][0]
3744
3845 def handle_endtag(self, tag):
3946 if self.__start_processing is False:
@@ -60,10 +67,12 @@ class FilecropResultParser(HTMLParser):
6067
6168 self.data_counter += 1
6269
70+
6371def request(query, params):
64− params['url'] = search_url.format(query=urlencode({'w' :query}))
72+ params['url'] = search_url.format(query=urlencode({'w': query}))
6573 return params
6674
75+
6776def response(resp):
6877 parser = FilecropResultParser()
6978 parser.feed(resp.text)
searx/engines/flickr.py+8−2
@@ -8,21 +8,27 @@ categories = ['images']
88
99url = 'https://secure.flickr.com/'
1010search_url = url+'search/?{query}'
11+results_xpath = '//div[@id="thumbnails"]//a[@class="rapidnofollow photo-click" and @data-track="photo-click"]' # noqa
12+
1113
1214def request(query, params):
1315 params['url'] = search_url.format(query=urlencode({'q': query}))
1416 return params
1517
18+
1619def response(resp):
1720 global base_url
1821 results = []
1922 dom = html.fromstring(resp.text)
20− for result in dom.xpath('//div[@id="thumbnails"]//a[@class="rapidnofollow photo-click" and @data-track="photo-click"]'):
23+ for result in dom.xpath(results_xpath):
2124 href = urljoin(url, result.attrib.get('href'))
2225 img = result.xpath('.//img')[0]
2326 title = img.attrib.get('alt', '')
2427 img_src = img.attrib.get('data-defer-src')
2528 if not img_src:
2629 continue
27− results.append({'url': href, 'title': title, 'img_src': img_src, 'template': 'images.html'})
30+ results.append({'url': href,
31+ 'title': title,
32+ 'img_src': img_src,
33+ 'template': 'images.html'})
2834 return results
searx/engines/github.py+5−2
@@ -4,12 +4,15 @@ from cgi import escape
44
55categories = ['it']
66
7−search_url = 'https://api.github.com/search/repositories?sort=stars&order=desc&{query}'
7+search_url = 'https://api.github.com/search/repositories?sort=stars&order=desc&{query}' # noqa
8+
9+accept_header = 'application/vnd.github.preview.text-match+json'
10+
811
912def request(query, params):
1013 global search_url
1114 params['url'] = search_url.format(query=urlencode({'q': query}))
12− params['headers']['Accept'] = 'application/vnd.github.preview.text-match+json'
15+ params['headers']['Accept'] = accept_header
1316 return params
1417
1518
searx/engines/google_images.py+8−2
@@ -6,12 +6,14 @@ from json import loads
66categories = ['images']
77
88url = 'https://ajax.googleapis.com/'
9−search_url = url + 'ajax/services/search/images?v=1.0&start=0&rsz=large&safe=off&filter=off&{query}'
9+search_url = url + 'ajax/services/search/images?v=1.0&start=0&rsz=large&safe=off&filter=off&{query}' # noqa
10+
1011
1112def request(query, params):
1213 params['url'] = search_url.format(query=urlencode({'q': query}))
1314 return params
1415
16+
1517def response(resp):
1618 results = []
1719 search_res = loads(resp.text)
@@ -24,5 +26,9 @@ def response(resp):
2426 title = result['title']
2527 if not result['url']:
2628 continue
27− results.append({'url': href, 'title': title, 'content': '', 'img_src': result['url'], 'template': 'images.html'})
29+ results.append({'url': href,
30+ 'title': title,
31+ 'content': '',
32+ 'img_src': result['url'],
33+ 'template': 'images.html'})
2834 return results
searx/engines/json_engine.py+14−6
@@ -2,12 +2,13 @@ from urllib import urlencode
22from json import loads
33from collections import Iterable
44
5−search_url = None
6−url_query = None
5+search_url = None
6+url_query = None
77content_query = None
8−title_query = None
8+title_query = None
99#suggestion_xpath = ''
1010
11+
1112def iterate(iterable):
1213 if type(iterable) == dict:
1314 it = iterable.iteritems()
@@ -17,11 +18,15 @@ def iterate(iterable):
1718 for index, value in it:
1819 yield str(index), value
1920
21+
2022def is_iterable(obj):
21− if type(obj) == str: return False
22− if type(obj) == unicode: return False
23+ if type(obj) == str:
24+ return False
25+ if type(obj) == unicode:
26+ return False
2327 return isinstance(obj, Iterable)
2428
29+
2530def parse(query):
2631 q = []
2732 for part in query.split('/'):
@@ -31,6 +36,7 @@ def parse(query):
3136 q.append(part)
3237 return q
3338
39+
3440def do_query(data, q):
3541 ret = []
3642 if not len(q):
@@ -38,7 +44,7 @@ def do_query(data, q):
3844
3945 qkey = q[0]
4046
41− for key,value in iterate(data):
47+ for key, value in iterate(data):
4248
4349 if len(q) == 1:
4450 if key == qkey:
@@ -54,11 +60,13 @@ def do_query(data, q):
5460 ret.extend(do_query(value, q))
5561 return ret
5662
63+
5764def query(data, query_string):
5865 q = parse(query_string)
5966
6067 return do_query(data, q)
6168
69+
6270def request(query, params):
6371 query = urlencode({'q': query})[2:]
6472 params['url'] = search_url.format(query=query)
searx/engines/mediawiki.py+4−4
@@ -3,10 +3,12 @@ from urllib import urlencode, quote
33
44url = 'https://en.wikipedia.org/'
55
6+search_url = url + 'w/api.php?action=query&list=search&{query}&srprop=timestamp&format=json' # noqa
7+
68number_of_results = 10
79
10+
811def request(query, params):
9− search_url = url + 'w/api.php?action=query&list=search&{query}&srprop=timestamp&format=json'
1012 params['url'] = search_url.format(query=urlencode({'srsearch': query}))
1113 return params
1214
@@ -14,7 +16,5 @@ def request(query, params):
1416def response(resp):
1517 search_results = loads(resp.text)
1618 res = search_results.get('query', {}).get('search', [])
17−
18− return [{'url': url + 'wiki/' + quote(result['title'].replace(' ', '_').encode('utf-8')),
19+ return [{'url': url + 'wiki/' + quote(result['title'].replace(' ', '_').encode('utf-8')), # noqa
1920 'title': result['title']} for result in res[:int(number_of_results)]]
20−
searx/engines/piratebay.py+18−9
@@ -7,13 +7,18 @@ categories = ['videos', 'music']
77
88url = 'https://thepiratebay.se/'
99search_url = url + 'search/{search_term}/0/99/{search_type}'
10−search_types = {'videos': '200'
11− ,'music' : '100'
12− ,'files' : '0'
13− }
10+search_types = {'videos': '200',
11+ 'music': '100',
12+ 'files': '0'}
13+
14+magnet_xpath = './/a[@title="Download this torrent using magnet"]'
15+content_xpath = './/font[@class="detDesc"]//text()'
16+
1417
1518def request(query, params):
16− params['url'] = search_url.format(search_term=quote(query), search_type=search_types.get(params['category']))
19+ search_type = search_types.get(params['category'])
20+ params['url'] = search_url.format(search_term=quote(query),
21+ search_type=search_type)
1722 return params
1823
1924
@@ -27,10 +32,14 @@ def response(resp):
2732 link = result.xpath('.//div[@class="detName"]//a')[0]
2833 href = urljoin(url, link.attrib.get('href'))
2934 title = ' '.join(link.xpath('.//text()'))
30− content = escape(' '.join(result.xpath('.//font[@class="detDesc"]//text()')))
35+ content = escape(' '.join(result.xpath(content_xpath)))
3136 seed, leech = result.xpath('.//td[@align="right"]/text()')[:2]
32− magnetlink = result.xpath('.//a[@title="Download this torrent using magnet"]')[0]
33− results.append({'url': href, 'title': title, 'content': content,
34− 'seed': seed, 'leech': leech, 'magnetlink': magnetlink.attrib['href'],
37+ magnetlink = result.xpath(magnet_xpath)[0]
38+ results.append({'url': href,
39+ 'title': title,
40+ 'content': content,
41+ 'seed': seed,
42+ 'leech': leech,
43+ 'magnetlink': magnetlink.attrib['href'],
3544 'template': 'torrent.html'})
3645 return results
searx/engines/soundcloud.py+5−2
@@ -5,7 +5,8 @@ categories = ['music']
55
66guest_client_id = 'b45b1aa10f1ac2941910a7f0d10f8e28'
77url = 'https://api.soundcloud.com/'
8−search_url = url + 'search?{query}&facet=model&limit=20&offset=0&linked_partitioning=1&client_id='+guest_client_id
8+search_url = url + 'search?{query}&facet=model&limit=20&offset=0&linked_partitioning=1&client_id='+guest_client_id # noqa
9+
910
1011def request(query, params):
1112 global search_url
@@ -21,5 +22,7 @@ def response(resp):
2122 if result['kind'] in ('track', 'playlist'):
2223 title = result['title']
2324 content = result['description']
24− results.append({'url': result['permalink_url'], 'title': title, 'content': content})
25+ results.append({'url': result['permalink_url'],
26+ 'title': title,
27+ 'content': content})
2528 return results
searx/engines/stackoverflow.py+3−1
@@ -7,6 +7,8 @@ categories = ['it']
77
88url = 'http://stackoverflow.com/'
99search_url = url+'search?'
10+result_xpath = './/div[@class="excerpt"]//text()'
11+
1012
1113def request(query, params):
1214 params['url'] = search_url + urlencode({'q': query})
@@ -20,6 +22,6 @@ def response(resp):
2022 link = result.xpath('.//div[@class="result-link"]//a')[0]
2123 href = urljoin(url, link.attrib.get('href'))
2224 title = escape(' '.join(link.xpath('.//text()')))
23− content = escape(' '.join(result.xpath('.//div[@class="excerpt"]//text()')))
25+ content = escape(' '.join(result.xpath(result_xpath)))
2426 results.append({'url': href, 'title': title, 'content': content})
2527 return results
searx/engines/startpage.py+2−4
@@ -1,11 +1,10 @@
11from urllib import urlencode
22from lxml import html
3−from urlparse import urlparse
4−from cgi import escape
53
64base_url = 'https://startpage.com/'
75search_url = base_url+'do/search'
86
7+
98def request(query, params):
109 global search_url
1110 query = urlencode({'q': query})[2:]
@@ -20,11 +19,10 @@ def response(resp):
2019 results = []
2120 dom = html.fromstring(resp.content)
2221 # ads xpath //div[@id="results"]/div[@id="sponsored"]//div[@class="result"]
23− # not ads : div[@class="result"] are the direct childs of div[@id="results"]
22+ # not ads: div[@class="result"] are the direct childs of div[@id="results"]
2423 for result in dom.xpath('//div[@id="results"]/div[@class="result"]'):
2524 link = result.xpath('.//h3/a')[0]
2625 url = link.attrib.get('href')
27− parsed_url = urlparse(url)
2826 title = link.text_content()
2927 content = result.xpath('./p[@class="desc"]')[0].text_content()
3028 results.append({'url': url, 'title': title, 'content': content})
searx/engines/twitter.py+8−3
@@ -7,6 +7,9 @@ categories = ['social media']
77
88base_url = 'https://twitter.com/'
99search_url = base_url+'search?'
10+title_xpath = './/span[@class="username js-action-profile-name"]//text()'
11+content_xpath = './/p[@class="js-tweet-text tweet-text"]//text()'
12+
1013
1114def request(query, params):
1215 global search_url
@@ -21,7 +24,9 @@ def response(resp):
2124 for tweet in dom.xpath('//li[@data-item-type="tweet"]'):
2225 link = tweet.xpath('.//small[@class="time"]//a')[0]
2326 url = urljoin(base_url, link.attrib.get('href'))
24− title = ''.join(tweet.xpath('.//span[@class="username js-action-profile-name"]//text()'))
25− content = escape(''.join(tweet.xpath('.//p[@class="js-tweet-text tweet-text"]//text()')))
26− results.append({'url': url, 'title': title, 'content': content})
27+ title = ''.join(tweet.xpath(title_xpath))
28+ content = escape(''.join(tweet.xpath(content_xpath)))
29+ results.append({'url': url,
30+ 'title': title,
31+ 'content': content})
2732 return results
searx/engines/vimeo.py+15−12
@@ -5,27 +5,31 @@ from lxml import html
55
66base_url = 'http://vimeo.com'
77search_url = base_url + '/search?{query}'
8−url_xpath = None
8+url_xpath = None
99content_xpath = None
10−title_xpath = None
10+title_xpath = None
1111results_xpath = ''
12+content_tpl = '<a href="{0}"> <img src="{2}"/> </a>'
1213
13−# the cookie set by vimeo contains all the following values, but only __utma seems to be requiered
14+# the cookie set by vimeo contains all the following values,
15+# but only __utma seems to be requiered
1416cookie = {
1517 #'vuid':'918282893.1027205400'
1618 # 'ab_bs':'%7B%223%22%3A279%7D'
17− '__utma':'00000000.000#0000000.0000000000.0000000000.0000000000.0'
19+ '__utma': '00000000.000#0000000.0000000000.0000000000.0000000000.0'
1820 # '__utmb':'18302654.1.10.1388942090'
1921 #, '__utmc':'18302654'
20− #, '__utmz':'18#302654.1388942090.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)'
22+ #, '__utmz':'18#302654.1388942090.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)' # noqa
2123 #, '__utml':'search'
2224}
2325
26+
2427def request(query, params):
25− params['url'] = search_url.format(query=urlencode({'q' :query}))
28+ params['url'] = search_url.format(query=urlencode({'q': query}))
2629 params['cookies'] = cookie
2730 return params
2831
32+
2933def response(resp):
3034 results = []
3135 dom = html.fromstring(resp.text)
@@ -36,10 +40,9 @@ def response(resp):
3640 url = base_url + result.xpath(url_xpath)[0]
3741 title = p.unescape(extract_text(result.xpath(title_xpath)))
3842 thumbnail = extract_text(result.xpath(content_xpath)[0])
39− content = '<a href="{0}"> <img src="{2}"/> </a>'.format(url, title, thumbnail)
40− results.append({'url': url
41− , 'title': title
42− , 'content': content
43− , 'template':'videos.html'
44− , 'thumbnail': thumbnail})
43+ results.append({'url': url,
44+ 'title': title,
45+ 'content': content_tpl.format(url, title, thumbnail),
46+ 'template': 'videos.html',
47+ 'thumbnail': thumbnail})
4548 return results
searx/engines/xpath.py+15−11
@@ -1,21 +1,24 @@
11from lxml import html
22from urllib import urlencode, unquote
33from urlparse import urlparse, urljoin
4−from cgi import escape
54from lxml.etree import _ElementStringResult
65
7−search_url = None
8−url_xpath = None
6+search_url = None
7+url_xpath = None
98content_xpath = None
10−title_xpath = None
9+title_xpath = None
1110suggestion_xpath = ''
1211results_xpath = ''
1312
13+
1414'''
1515if xpath_results is list, extract the text from each result and concat the list
16−if xpath_results is a xml element, extract all the text node from it ( text_content() method from lxml )
16+if xpath_results is a xml element, extract all the text node from it
17+ ( text_content() method from lxml )
1718if xpath_results is a string element, then it's already done
1819'''
20+
21+
1922def extract_text(xpath_results):
2023 if type(xpath_results) == list:
2124 # it's list of result : concat everything using recursive call
@@ -60,7 +63,8 @@ def normalize_url(url):
6063 url += '/'
6164
6265 # FIXME : hack for yahoo
63− if parsed_url.hostname == 'search.yahoo.com' and parsed_url.path.startswith('/r'):
66+ if parsed_url.hostname == 'search.yahoo.com'\
67+ and parsed_url.path.startswith('/r'):
6468 p = parsed_url.path
6569 mark = p.find('/**')
6670 if mark != -1:
@@ -82,15 +86,15 @@ def response(resp):
8286 if results_xpath:
8387 for result in dom.xpath(results_xpath):
8488 url = extract_url(result.xpath(url_xpath))
85− title = extract_text(result.xpath(title_xpath)[0 ])
89+ title = extract_text(result.xpath(title_xpath)[0])
8690 content = extract_text(result.xpath(content_xpath)[0])
8791 results.append({'url': url, 'title': title, 'content': content})
8892 else:
8993 for url, title, content in zip(
90− map(extract_url, dom.xpath(url_xpath)), \
91− map(extract_text, dom.xpath(title_xpath)), \
92− map(extract_text, dom.xpath(content_xpath)), \
93− ):
94+ map(extract_url, dom.xpath(url_xpath)),
95+ map(extract_text, dom.xpath(title_xpath)),
96+ map(extract_text, dom.xpath(content_xpath))
97+ ):
9498 results.append({'url': url, 'title': title, 'content': content})
9599
96100 if not suggestion_xpath:
searx/engines/yacy.py+4−2
@@ -4,10 +4,12 @@ from urllib import urlencode
44url = 'http://localhost:8090'
55search_url = '/yacysearch.json?{query}&maximumRecords=10'
66
7+
78def request(query, params):
8− params['url'] = url + search_url.format(query=urlencode({'query':query}))
9+ params['url'] = url + search_url.format(query=urlencode({'query': query}))
910 return params
1011
12+
1113def response(resp):
1214 raw_search_results = loads(resp.text)
1315
@@ -25,7 +27,7 @@ def response(resp):
2527 tmp_result['content'] = ''
2628
2729 if len(result['description']):
28− tmp_result['content'] += result['description'] +"<br/>"
30+ tmp_result['content'] += result['description'] + "<br/>"
2931
3032 if len(result['pubDate']):
3133 tmp_result['content'] += result['pubDate'] + "<br/>"
searx/engines/youtube.py+7−7
@@ -5,6 +5,7 @@ categories = ['videos']
55
66search_url = 'https://gdata.youtube.com/feeds/api/videos?alt=json&{query}'
77
8+
89def request(query, params):
910 params['url'] = search_url.format(query=urlencode({'q': query}))
1011 return params
@@ -30,17 +31,16 @@ def response(resp):
3031 thumbnail = ''
3132 if len(result['media$group']['media$thumbnail']):
3233 thumbnail = result['media$group']['media$thumbnail'][0]['url']
33− content += '<a href="{0}" title="{0}" ><img src="{1}" /></a>'.format(url, thumbnail)
34+ content += '<a href="{0}" title="{0}" ><img src="{1}" /></a>'.format(url, thumbnail) # noqa
3435 if len(content):
3536 content += '<br />' + result['content']['$t']
3637 else:
3738 content = result['content']['$t']
3839
39− results.append({'url': url
40− , 'title': title
41− , 'content': content
42− , 'template':'videos.html'
43− , 'thumbnail':thumbnail})
40+ results.append({'url': url,
41+ 'title': title,
42+ 'content': content,
43+ 'template': 'videos.html',
44+ 'thumbnail': thumbnail})
4445
4546 return results
46−
searx/utils.py+15−5
@@ -1,14 +1,15 @@
11from HTMLParser import HTMLParser
22#import htmlentitydefs
33import csv
4−import codecs
4+from codecs import getincrementalencoder
55import cStringIO
66import re
77
88
99def gen_useragent():
1010 # TODO
11− return "Mozilla/5.0 (X11; Linux x86_64; rv:26.0) Gecko/20100101 Firefox/26.0"
11+ ua = "Mozilla/5.0 (X11; Linux x86_64; rv:26.0) Gecko/20100101 Firefox/26.0"
12+ return ua
1213
1314
1415def highlight_content(content, query):
@@ -46,7 +47,10 @@ class HTMLTextExtractor(HTMLParser):
4647 self.result.append(d)
4748
4849 def handle_charref(self, number):
49− codepoint = int(number[1:], 16) if number[0] in (u'x', u'X') else int(number)
50+ if number[0] in (u'x', u'X'):
51+ codepoint = int(number[1:], 16)
52+ else:
53+ codepoint = int(number)
5054 self.result.append(unichr(codepoint))
5155
5256 def handle_entityref(self, name):
@@ -75,10 +79,16 @@ class UnicodeWriter:
7579 self.queue = cStringIO.StringIO()
7680 self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
7781 self.stream = f
78− self.encoder = codecs.getincrementalencoder(encoding)()
82+ self.encoder = getincrementalencoder(encoding)()
7983
8084 def writerow(self, row):
81− self.writer.writerow([(s.encode("utf-8").strip() if type(s) == str or type(s) == unicode else str(s)) for s in row])
85+ unicode_row = []
86+ for col in row:
87+ if type(col) == str or type(col) == unicode:
88+ unicode_row.append(col.encode('utf-8').strip())
89+ else:
90+ unicode_row.append(col)
91+ self.writer.writerow(unicode_row)
8292 # Fetch UTF-8 output from the queue ...
8393 data = self.queue.getvalue()
8494 data = data.decode("utf-8")
searx/webapp.py+19−10
@@ -18,7 +18,8 @@ along with searx. If not, see < http://www.gnu.org/licenses/ >.
1818'''
1919
2020from searx import settings
21−from flask import Flask, request, render_template, url_for, Response, make_response, redirect
21+from flask import Flask, request, render_template
22+from flask import url_for, Response, make_response, redirect
2223from searx.engines import search, categories, engines, get_engines_stats
2324import json
2425import cStringIO
@@ -70,7 +71,8 @@ def get_base_url():
7071def render(template_name, **kwargs):
7172 global categories
7273 kwargs['categories'] = ['general']
73− kwargs['categories'].extend(x for x in sorted(categories.keys()) if x != 'general')
74+ kwargs['categories'].extend(x for x in
75+ sorted(categories.keys()) if x != 'general')
7476 if not 'selected_categories' in kwargs:
7577 kwargs['selected_categories'] = []
7678 cookie_categories = request.cookies.get('categories', '').split(',')
@@ -114,7 +116,8 @@ def index():
114116 continue
115117 selected_categories.append(category)
116118 if not len(selected_categories):
117− cookie_categories = request.cookies.get('categories', '').split(',')
119+ cookie_categories = request.cookies.get('categories', '')
120+ cookie_categories = cookie_categories.split(',')
118121 for ccateg in cookie_categories:
119122 if ccateg in categories:
120123 selected_categories.append(ccateg)
@@ -122,7 +125,9 @@ def index():
122125 selected_categories = ['general']
123126
124127 for categ in selected_categories:
125− selected_engines.extend({'category': categ, 'name': x.name} for x in categories[categ])
128+ selected_engines.extend({'category': categ,
129+ 'name': x.name}
130+ for x in categories[categ])
126131
127132 results, suggestions = search(query, request, selected_engines)
128133
@@ -137,7 +142,8 @@ def index():
137142 result['content'] = html_to_text(result['content']).strip()
138143 result['title'] = html_to_text(result['title']).strip()
139144 if len(result['url']) > 74:
140− result['pretty_url'] = result['url'][:35] + '[..]' + result['url'][-35:]
145+ url_parts = result['url'][:35], result['url'][-35:]
146+ result['pretty_url'] = '{0}[...]{1}'.format(*url_parts)
141147 else:
142148 result['pretty_url'] = result['url']
143149
@@ -146,7 +152,8 @@ def index():
146152 result['favicon'] = engine
147153
148154 if request_data.get('format') == 'json':
149− return Response(json.dumps({'query': query, 'results': results}), mimetype='application/json')
155+ return Response(json.dumps({'query': query, 'results': results}),
156+ mimetype='application/json')
150157 elif request_data.get('format') == 'csv':
151158 csv = UnicodeWriter(cStringIO.StringIO())
152159 keys = ('title', 'url', 'content', 'host', 'engine', 'score')
@@ -157,7 +164,8 @@ def index():
157164 csv.writerow([row.get(key, '') for key in keys])
158165 csv.stream.seek(0)
159166 response = Response(csv.stream.read(), mimetype='application/csv')
160− response.headers.add('Content-Disposition', 'attachment;Filename=searx_-_{0}.csv'.format('_'.join(query.split())))
167+ content_disp = 'attachment;Filename=searx_-_{0}.csv'.format(query)
168+ response.headers.add('Content-Disposition', content_disp)
161169 return response
162170 elif request_data.get('format') == 'rss':
163171 response_rss = render(
@@ -240,15 +248,16 @@ def opensearch():
240248 base_url = get_base_url()
241249 ret = opensearch_xml.format(method=method, host=base_url)
242250 resp = Response(response=ret,
243− status=200,
244− mimetype="application/xml")
251+ status=200,
252+ mimetype="application/xml")
245253 return resp
246254
247255
248256@app.route('/favicon.ico')
249257def favicon():
250258 return send_from_directory(os.path.join(app.root_path, 'static/img'),
251− 'favicon.png', mimetype='image/vnd.microsoft.icon')
259+ 'favicon.png',
260+ mimetype='image/vnd.microsoft.icon')
252261
253262
254263def run():