webapp.py 5.4 KB

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