webapp.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  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, flash, render_template, url_for, Response, make_response
  20. from searx.engines import search, categories
  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="post" 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. @app.route('/', methods=['GET', 'POST'])
  49. def index():
  50. global categories
  51. if request.method=='POST':
  52. if not request.form.get('q'):
  53. flash('Wrong post data')
  54. return render('index.html')
  55. selected_engines = []
  56. selected_categories = []
  57. for pd_name,pd in request.form.items():
  58. if pd_name.startswith('category_'):
  59. category = pd_name[9:]
  60. if not category in categories:
  61. continue
  62. selected_categories.append(category)
  63. selected_engines.extend(x.name for x in categories[category])
  64. if not len(selected_engines):
  65. cookie_categories = request.cookies.get('categories', '').split(',')
  66. for ccateg in cookie_categories:
  67. if ccateg in categories:
  68. selected_categories.append(ccateg)
  69. selected_engines.extend(x.name for x in categories[ccateg])
  70. if not len(selected_engines):
  71. selected_categories.append('general')
  72. selected_engines.extend(x.name for x in categories['general'])
  73. query = request.form['q'].encode('utf-8')
  74. results = search(query, request, selected_engines)
  75. if request.form.get('format') == 'json':
  76. # TODO HTTP headers
  77. return json.dumps({'query': query, 'results': results})
  78. template = render('results.html'
  79. ,results=results
  80. ,q=query.decode('utf-8')
  81. ,selected_categories=selected_categories
  82. ,number_of_results=len(results)
  83. )
  84. resp = make_response(template)
  85. resp.set_cookie('categories', ','.join(selected_categories))
  86. return resp
  87. return render('index.html')
  88. @app.route('/favicon.ico', methods=['GET'])
  89. def fav():
  90. return ''
  91. @app.route('/opensearch.xml', methods=['GET'])
  92. def opensearch():
  93. global opensearch_xml
  94. ret = opensearch_xml.format(host=url_for('index', _external=True))
  95. resp = Response(response=ret,
  96. status=200,
  97. mimetype="application/xml")
  98. return resp
  99. if __name__ == "__main__":
  100. from gevent import monkey
  101. monkey.patch_all()
  102. app.run(debug = settings.debug
  103. ,use_debugger = settings.debug
  104. ,port = settings.port
  105. )