webapp.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  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. if __name__ == "__main__":
  16. from sys import path
  17. from os.path import realpath, dirname
  18. path.append(realpath(dirname(realpath(__file__))+'/../'))
  19. from flask import Flask, request, render_template, url_for, Response, make_response
  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. app = Flask(__name__)
  26. app.secret_key = settings.secret_key
  27. opensearch_xml = '''<?xml version="1.0" encoding="utf-8"?>
  28. <OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/">
  29. <ShortName>searx</ShortName>
  30. <Description>Search searx</Description>
  31. <InputEncoding>UTF-8</InputEncoding>
  32. <LongName>searx meta search engine</LongName>
  33. <Url type="text/html" method="{method}" template="{host}">
  34. <Param name="q" value="{{searchTerms}}" />
  35. </Url>
  36. </OpenSearchDescription>
  37. '''
  38. def render(template_name, **kwargs):
  39. global categories
  40. kwargs['categories'] = sorted(categories.keys())
  41. if not 'selected_categories' in kwargs:
  42. kwargs['selected_categories'] = []
  43. cookie_categories = request.cookies.get('categories', '').split(',')
  44. for ccateg in cookie_categories:
  45. if ccateg in categories:
  46. kwargs['selected_categories'].append(ccateg)
  47. if not len(kwargs['selected_categories']):
  48. kwargs['selected_categories'] = ['general']
  49. return render_template(template_name, **kwargs)
  50. def parse_query(query):
  51. query_engines = []
  52. query_parts = query.split()
  53. if query_parts[0].startswith('-') and query_parts[0][1:] in engines:
  54. query_engines.append({'category': 'TODO', 'name': query_parts[0][1:]})
  55. query = query.replace(query_parts[0], '', 1).strip()
  56. return query, query_engines
  57. @app.route('/', methods=['GET', 'POST'])
  58. def index():
  59. global categories
  60. if request.method=='POST':
  61. request_data = request.form
  62. else:
  63. request_data = request.args
  64. if not request_data.get('q'):
  65. return render('index.html')
  66. selected_categories = []
  67. query, selected_engines = parse_query(request_data['q'].encode('utf-8'))
  68. if not len(selected_engines):
  69. for pd_name,pd in request_data.items():
  70. if pd_name.startswith('category_'):
  71. category = pd_name[9:]
  72. if not category in categories:
  73. continue
  74. selected_categories.append(category)
  75. if not len(selected_categories):
  76. cookie_categories = request.cookies.get('categories', '').split(',')
  77. for ccateg in cookie_categories:
  78. if ccateg in categories:
  79. selected_categories.append(ccateg)
  80. if not len(selected_categories):
  81. selected_categories = ['general']
  82. for categ in selected_categories:
  83. selected_engines.extend({'category': categ, 'name': x.name} for x in categories[categ])
  84. results, suggestions = search(query, request, selected_engines)
  85. for result in results:
  86. if len(result['url']) > 74:
  87. result['pretty_url'] = result['url'][:35] + '[..]' + result['url'][-35:]
  88. else:
  89. result['pretty_url'] = result['url']
  90. if request_data.get('format') == 'json':
  91. return Response(json.dumps({'query': query, 'results': results}), mimetype='application/json')
  92. elif request_data.get('format') == 'csv':
  93. csv = UnicodeWriter(cStringIO.StringIO())
  94. if len(results):
  95. keys = results[0].keys()
  96. csv.writerow(keys)
  97. for row in results:
  98. csv.writerow([row[key] for key in keys])
  99. csv.stream.seek(0)
  100. response = Response(csv.stream.read(), mimetype='application/csv')
  101. response.headers.add('Content-Disposition', 'attachment;Filename=searx_-_{0}.csv'.format(query))
  102. return response
  103. template = render('results.html'
  104. ,results=results
  105. ,q=request_data['q']
  106. ,selected_categories=selected_categories
  107. ,number_of_results=len(results)
  108. ,suggestions=suggestions
  109. )
  110. resp = make_response(template)
  111. resp.set_cookie('categories', ','.join(selected_categories))
  112. return resp
  113. @app.route('/favicon.ico', methods=['GET'])
  114. def fav():
  115. return ''
  116. @app.route('/about', methods=['GET'])
  117. def about():
  118. global categories
  119. return render('about.html', categs=categories.items())
  120. @app.route('/stats', methods=['GET'])
  121. def stats():
  122. global categories
  123. stats = get_engines_stats()
  124. return render('stats.html', stats=stats)
  125. @app.route('/opensearch.xml', methods=['GET'])
  126. def opensearch():
  127. global opensearch_xml
  128. method = 'post'
  129. scheme = 'http'
  130. # chrome/chromium only supports HTTP GET....
  131. if request.headers.get('User-Agent', '').lower().find('webkit') >= 0:
  132. method = 'get'
  133. if request.is_secure:
  134. scheme = 'https'
  135. ret = opensearch_xml.format(method=method, host=url_for('index', _external=True, _scheme=scheme))
  136. resp = Response(response=ret,
  137. status=200,
  138. mimetype="application/xml")
  139. return resp
  140. if __name__ == "__main__":
  141. from gevent import monkey
  142. monkey.patch_all()
  143. app.run(debug = settings.debug
  144. ,use_debugger = settings.debug
  145. ,port = settings.port
  146. )