ソースを参照

[enh] image proxy base

Adam Tauber 10 年 前
コミット
60eb831966
共有1 個のファイルを変更した36 個の追加1 個の削除を含む
  1. 36
    1
      searx/webapp.py

+ 36
- 1
searx/webapp.py ファイルの表示

@@ -27,6 +27,7 @@ import cStringIO
27 27
 import os
28 28
 
29 29
 from datetime import datetime, timedelta
30
+from requests import get as http_get
30 31
 from itertools import chain
31 32
 from flask import (
32 33
     Flask, request, render_template, url_for, Response, make_response,
@@ -39,7 +40,7 @@ from searx.engines import (
39 40
 )
40 41
 from searx.utils import (
41 42
     UnicodeWriter, highlight_content, html_to_text, get_themes,
42
-    get_static_files, get_result_templates
43
+    get_static_files, get_result_templates, gen_useragent
43 44
 )
44 45
 from searx.version import VERSION_STRING
45 46
 from searx.languages import language_codes
@@ -531,6 +532,40 @@ def preferences():
531 532
                   theme=get_current_theme_name())
532 533
 
533 534
 
535
+@app.route('/image_proxy', methods=['GET'])
536
+def image_proxy():
537
+    url = request.args.get('url')
538
+
539
+    if not url:
540
+        return '', 400
541
+
542
+    resp = http_get(url,
543
+                    stream=True,
544
+                    timeout=settings['server'].get('request_timeout', 2),
545
+                    headers={'User-Agent': gen_useragent()})
546
+
547
+    if resp.status_code != 200:
548
+        logger.debug('image-proxy: wrong response code: {0}'.format(resp.status_code))
549
+        if resp.status_code >= 400:
550
+            return '', resp.status_code
551
+        return '', 400
552
+
553
+    if not resp.headers.get('content-type', '').startswith('image/'):
554
+        logger.debug('image-proxy: wrong content-type: {0}'.format(resp.get('content-type')))
555
+        return '', 400
556
+
557
+    img = ''
558
+    chunk_counter = 0
559
+
560
+    for chunk in resp.iter_content(1024*1024):
561
+        chunk_counter += 1
562
+        if chunk_counter > 5:
563
+            return '', 502  # Bad gateway - file is too big (>5M)
564
+        img += chunk
565
+
566
+    return Response(img, mimetype=resp.headers['content-type'])
567
+
568
+
534 569
 @app.route('/stats', methods=['GET'])
535 570
 def stats():
536 571
     """Render engine statistics page."""