浏览代码

[enh] image-proxy : handle ETag and date related headers, add hash to URL

dalf 10 年前
父节点
当前提交
b6d27aca59
共有 2 个文件被更改,包括 28 次插入4 次删除
  1. 8
    0
      searx/utils.py
  2. 20
    4
      searx/webapp.py

+ 8
- 0
searx/utils.py 查看文件

@@ -206,3 +206,11 @@ def format_date_by_locale(date_string, locale_string):
206 206
     except:
207 207
         logger.warning('cannot set original locale: {0}'.format(orig_locale))
208 208
     return formatted_date
209
+
210
+
211
+def dict_subset(d, properties):
212
+    result = {}
213
+    for k in properties:
214
+        if k in d:
215
+            result[k] = d[k]
216
+    return result

+ 20
- 4
searx/webapp.py 查看文件

@@ -25,6 +25,7 @@ if __name__ == '__main__':
25 25
 import json
26 26
 import cStringIO
27 27
 import os
28
+import hashlib
28 29
 
29 30
 from datetime import datetime, timedelta
30 31
 from requests import get as http_get
@@ -41,7 +42,7 @@ from searx.engines import (
41 42
 )
42 43
 from searx.utils import (
43 44
     UnicodeWriter, highlight_content, html_to_text, get_themes,
44
-    get_static_files, get_result_templates, gen_useragent
45
+    get_static_files, get_result_templates, gen_useragent, dict_subset
45 46
 )
46 47
 from searx.version import VERSION_STRING
47 48
 from searx.languages import language_codes
@@ -213,11 +214,13 @@ def image_proxify(url):
213 214
     if url.startswith('//'):
214 215
         url = 'https:' + url
215 216
 
217
+    h = hashlib.sha256(url + settings['server']['secret_key']).hexdigest()
218
+
216 219
     if not settings['server'].get('image_proxy') and not request.cookies.get('image_proxy'):
217 220
         return url
218 221
 
219 222
     return '{0}?{1}'.format(url_for('image_proxy'),
220
-                            urlencode(dict(url=url)))
223
+                            urlencode(dict(url=url, h=h)))
221 224
 
222 225
 
223 226
 def render(template_name, override_theme=None, **kwargs):
@@ -562,10 +565,21 @@ def image_proxy():
562 565
     if not url:
563 566
         return '', 400
564 567
 
568
+    h = hashlib.sha256(url + settings['server']['secret_key']).hexdigest()
569
+
570
+    if h != request.args.get('h'):
571
+        return '', 400
572
+
573
+    headers = dict_subset(request.headers, {'If-Modified-Since', 'If-None-Match'})
574
+    headers['User-Agent'] = gen_useragent()
575
+
565 576
     resp = http_get(url,
566 577
                     stream=True,
567 578
                     timeout=settings['server'].get('request_timeout', 2),
568
-                    headers={'User-Agent': gen_useragent()})
579
+                    headers=headers)
580
+
581
+    if resp.status_code == 304:
582
+        return '', resp.status_code
569 583
 
570 584
     if resp.status_code != 200:
571 585
         logger.debug('image-proxy: wrong response code: {0}'.format(resp.status_code))
@@ -586,7 +600,9 @@ def image_proxy():
586 600
             return '', 502  # Bad gateway - file is too big (>5M)
587 601
         img += chunk
588 602
 
589
-    return Response(img, mimetype=resp.headers['content-type'])
603
+    headers = dict_subset(resp.headers, {'Content-Length', 'Length', 'Date', 'Last-Modified', 'Expires', 'Etag'})
604
+
605
+    return Response(img, mimetype=resp.headers['content-type'], headers=headers)
590 606
 
591 607
 
592 608
 @app.route('/stats', methods=['GET'])