webapp.py 7.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. #!/usr/bin/env python
  2. '''
  3. searx is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU Affero General Public License as published by
  5. the Free Software Foundation, either version 3 of the License, or
  6. (at your option) any later version.
  7. searx is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU Affero General Public License for more details.
  11. You should have received a copy of the GNU Affero General Public License
  12. along with searx. If not, see < http://www.gnu.org/licenses/ >.
  13. (C) 2013- by Adam Tauber, <asciimoo@gmail.com>
  14. '''
  15. import os
  16. if __name__ == "__main__":
  17. from sys import path
  18. path.append(os.path.realpath(os.path.dirname(os.path.realpath(__file__))+'/../'))
  19. from flask import Flask, request, render_template, url_for, Response, make_response, redirect
  20. from searx.engines import search, categories, engines, get_engines_stats
  21. from searx import settings
  22. import json
  23. import cStringIO
  24. from searx.utils import UnicodeWriter
  25. from flask import send_from_directory
  26. app = Flask(__name__)
  27. app.secret_key = settings.secret_key
  28. opensearch_xml = '''<?xml version="1.0" encoding="utf-8"?>
  29. <OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/">
  30. <ShortName>searx</ShortName>
  31. <Description>Search searx</Description>
  32. <InputEncoding>UTF-8</InputEncoding>
  33. <LongName>searx meta search engine</LongName>
  34. <Url type="text/html" method="{method}" template="{host}">
  35. <Param name="q" value="{{searchTerms}}" />
  36. </Url>
  37. </OpenSearchDescription>
  38. '''
  39. def render(template_name, **kwargs):
  40. global categories
  41. kwargs['categories'] = sorted(categories.keys())
  42. if not 'selected_categories' in kwargs:
  43. kwargs['selected_categories'] = []
  44. cookie_categories = request.cookies.get('categories', '').split(',')
  45. for ccateg in cookie_categories:
  46. if ccateg in categories:
  47. kwargs['selected_categories'].append(ccateg)
  48. if not len(kwargs['selected_categories']):
  49. kwargs['selected_categories'] = ['general']
  50. return render_template(template_name, **kwargs)
  51. def parse_query(query):
  52. query_engines = []
  53. query_parts = query.split()
  54. if query_parts[0].startswith('-') and query_parts[0][1:] in engines:
  55. query_engines.append({'category': 'TODO', 'name': query_parts[0][1:]})
  56. query = query.replace(query_parts[0], '', 1).strip()
  57. return query, query_engines
  58. @app.route('/', methods=['GET', 'POST'])
  59. def index():
  60. global categories
  61. if request.method=='POST':
  62. request_data = request.form
  63. else:
  64. request_data = request.args
  65. if not request_data.get('q'):
  66. return render('index.html')
  67. selected_categories = []
  68. query, selected_engines = parse_query(request_data['q'].encode('utf-8'))
  69. if not len(selected_engines):
  70. for pd_name,pd in request_data.items():
  71. if pd_name.startswith('category_'):
  72. category = pd_name[9:]
  73. if not category in categories:
  74. continue
  75. selected_categories.append(category)
  76. if not len(selected_categories):
  77. cookie_categories = request.cookies.get('categories', '').split(',')
  78. for ccateg in cookie_categories:
  79. if ccateg in categories:
  80. selected_categories.append(ccateg)
  81. if not len(selected_categories):
  82. selected_categories = ['general']
  83. for categ in selected_categories:
  84. selected_engines.extend({'category': categ, 'name': x.name} for x in categories[categ])
  85. results, suggestions = search(query, request, selected_engines)
  86. for result in results:
  87. if len(result['url']) > 74:
  88. result['pretty_url'] = result['url'][:35] + '[..]' + result['url'][-35:]
  89. else:
  90. result['pretty_url'] = result['url']
  91. if request_data.get('format') == 'json':
  92. return Response(json.dumps({'query': query, 'results': results}), mimetype='application/json')
  93. elif request_data.get('format') == 'csv':
  94. csv = UnicodeWriter(cStringIO.StringIO())
  95. keys = ('title', 'url', 'content', 'host', 'engine', 'score')
  96. if len(results):
  97. csv.writerow(keys)
  98. for row in results:
  99. row['host'] = row['parsed_url'].netloc
  100. csv.writerow([row.get(key, '') for key in keys])
  101. csv.stream.seek(0)
  102. response = Response(csv.stream.read(), mimetype='application/csv')
  103. response.headers.add('Content-Disposition', 'attachment;Filename=searx_-_{0}.csv'.format('_'.join(query.split())))
  104. return response
  105. return render('results.html'
  106. ,results=results
  107. ,q=request_data['q']
  108. ,selected_categories=selected_categories
  109. ,number_of_results=len(results)
  110. ,suggestions=suggestions
  111. )
  112. @app.route('/about', methods=['GET'])
  113. def about():
  114. global categories
  115. return render('about.html', categs=categories.items())
  116. @app.route('/preferences', methods=['GET', 'POST'])
  117. def preferences():
  118. if request.method=='POST':
  119. selected_categories = []
  120. for pd_name,pd in request.form.items():
  121. if pd_name.startswith('category_'):
  122. category = pd_name[9:]
  123. if not category in categories:
  124. continue
  125. selected_categories.append(category)
  126. if selected_categories:
  127. resp = make_response(redirect('/'))
  128. # cookie max age: 4 weeks
  129. resp.set_cookie('categories', ','.join(selected_categories), max_age=60*60*24*7*4)
  130. return resp
  131. return render('preferences.html')
  132. @app.route('/stats', methods=['GET'])
  133. def stats():
  134. global categories
  135. stats = get_engines_stats()
  136. return render('stats.html', stats=stats)
  137. @app.route('/robots.txt', methods=['GET'])
  138. def robots():
  139. return Response("""User-agent: *
  140. Allow: /
  141. Allow: /about
  142. Disallow: /stats
  143. """, mimetype='text/plain')
  144. @app.route('/opensearch.xml', methods=['GET'])
  145. def opensearch():
  146. global opensearch_xml
  147. method = 'post'
  148. scheme = 'http'
  149. # chrome/chromium only supports HTTP GET....
  150. if request.headers.get('User-Agent', '').lower().find('webkit') >= 0:
  151. method = 'get'
  152. if request.is_secure:
  153. scheme = 'https'
  154. if settings.base_url:
  155. hostname = settings.base_url
  156. else:
  157. hostname = url_for('index', _external=True, _scheme=scheme)
  158. ret = opensearch_xml.format(method=method, host=hostname)
  159. resp = Response(response=ret,
  160. status=200,
  161. mimetype="application/xml")
  162. return resp
  163. @app.route('/favicon.ico')
  164. def favicon():
  165. return send_from_directory(os.path.join(app.root_path, 'static/img'),
  166. 'favicon.png', mimetype='image/vnd.microsoft.icon')
  167. if __name__ == "__main__":
  168. from gevent import monkey
  169. monkey.patch_all()
  170. app.run(debug = settings.debug
  171. ,use_debugger = settings.debug
  172. ,port = settings.port
  173. )