webapp.py 4.3KB

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. import ConfigParser
  21. from os import getenv
  22. from searx.engines import search, categories
  23. from searx import settings
  24. import json
  25. cfg = ConfigParser.SafeConfigParser()
  26. cfg.read('/etc/searx.conf')
  27. cfg.read(getenv('HOME')+'/.searxrc')
  28. cfg.read(getenv('HOME')+'/.config/searx/searx.conf')
  29. cfg.read('searx.conf')
  30. app = Flask(__name__)
  31. app.secret_key = settings.secret_key
  32. opensearch_xml = '''<?xml version="1.0" encoding="utf-8"?>
  33. <OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/">
  34. <ShortName>searx</ShortName>
  35. <Description>Search searx</Description>
  36. <InputEncoding>UTF-8</InputEncoding>
  37. <LongName>searx meta search engine</LongName>
  38. <Url type="text/html" method="post" template="{host}">
  39. <Param name="q" value="{{searchTerms}}" />
  40. </Url>
  41. </OpenSearchDescription>
  42. '''
  43. def render(template_name, **kwargs):
  44. global categories
  45. kwargs['categories'] = categories.keys()
  46. if not 'selected_categories' in kwargs:
  47. kwargs['selected_categories'] = []
  48. cookie_categories = request.cookies.get('categories', '').split(',')
  49. for ccateg in cookie_categories:
  50. if ccateg in categories:
  51. kwargs['selected_categories'].append(ccateg)
  52. if not len(kwargs['selected_categories']):
  53. kwargs['selected_categories'] = ['general']
  54. return render_template(template_name, **kwargs)
  55. @app.route('/', methods=['GET', 'POST'])
  56. def index():
  57. global categories
  58. if request.method=='POST':
  59. if not request.form.get('q'):
  60. flash('Wrong post data')
  61. return render('index.html')
  62. selected_engines = []
  63. selected_categories = []
  64. for pd_name,pd in request.form.items():
  65. if pd_name.startswith('category_'):
  66. category = pd_name[9:]
  67. if not category in categories:
  68. continue
  69. selected_categories.append(category)
  70. selected_engines.extend(x.name for x in categories[category])
  71. if not len(selected_engines):
  72. cookie_categories = request.cookies.get('categories', '').split(',')
  73. for ccateg in cookie_categories:
  74. if ccateg in categories:
  75. selected_categories.append(ccateg)
  76. selected_engines.extend(x.name for x in categories[ccateg])
  77. query = request.form['q'].encode('utf-8')
  78. results = search(query, request, selected_engines)
  79. if request.form.get('format') == 'json':
  80. # TODO HTTP headers
  81. return json.dumps({'query': query, 'results': results})
  82. template = render('results.html', results=results, q=query.decode('utf-8'), selected_categories=selected_categories)
  83. resp = make_response(template)
  84. resp.set_cookie('categories', ','.join(selected_categories))
  85. return resp
  86. return render('index.html')
  87. @app.route('/favicon.ico', methods=['GET'])
  88. def fav():
  89. return ''
  90. @app.route('/opensearch.xml', methods=['GET'])
  91. def opensearch():
  92. global opensearch_xml
  93. ret = opensearch_xml.format(host=url_for('index', _external=True))
  94. resp = Response(response=ret,
  95. status=200,
  96. mimetype="application/xml")
  97. return resp
  98. if __name__ == "__main__":
  99. from gevent import monkey
  100. monkey.patch_all()
  101. app.run(debug = settings.debug
  102. ,use_debugger = settings.debug
  103. ,port = settings.port
  104. )