from threading import Lock
from os import environ as ENV
import logging.config

from flask import Flask, request

from selenium import webdriver


logging.basicConfig()


app = Flask(__name__)


Driver = getattr(webdriver, ENV.get("WEBDRIVER", "Chrome"))


class Engine():

    def __init__(self):
        self.driver = Driver()
        self.lock = Lock()

    def render(self, url):
        with self.lock:
            self.driver.get(url)
            return self.driver.get_screenshot_as_png()


engine = Engine()


@app.route('/')
def screenshot():
    url = request.args.get('url')
    logging.info("Got request for url: %s", url)
    return engine.render(url), 200, {
        'Content-Type': 'image/png',
    }


if __name__ == '__main__':
    app.run(debug=True)

@@ -15,20 +15,72 @@
  import 
+R
 Lock
+, local%0Afrom multiprocessing.pool import ThreadPool
 %0Afrom os
@@ -302,16 +302,57 @@
 me%22))%0A%0A%0A
+class RetryFailed(Exception):%0A    pass%0A%0A%0A
 class En
@@ -435,16 +435,17 @@
 .lock = 
+R
 Lock()%0A%0A
@@ -468,19 +468,82 @@
 elf, url
+, retry=0
 ):%0A
+        if retry %3E 3:%0A            raise RetryFailed()%0A
         
@@ -558,16 +558,37 @@
 f.lock:%0A
+            try:%0A    
         
@@ -608,24 +608,28 @@
 er.get(url)%0A
+    
             
@@ -675,26 +675,349 @@
 g()%0A
-%0A%0Aengine = Engine(
+            except:%0A                self.driver = Driver()%0A                return self.render(url, retry + 1)%0A%0A%0Athread_local = local()%0A%0A%0Adef thread_init():%0A    thread_local.engine = Engine()%0A%0A%0Apool = ThreadPool(int(ENV.get(%22SCREENSHOT_WORKERS%22, 4)),%0A                  thread_init)%0A%0A%0Adef render(url):%0A    return thread_local.engine.render(url
 )%0A%0A%0A
@@ -1144,33 +1144,41 @@
  return 
-engine.
+pool.apply(
 render
+, 
 (url
+,)
 ), 200, 

Use worker pool