title: Multithreading with Flask
body: <p>I'd like to call <code>generate_async_audio_service</code> from a view and have it asynchronously generate audio files for the list of words using a threading pool and then commit them to a database.</p>
  
  <p>I keep running into an error that I'm working out of the application context even though I'm creating a new polly and s3 instance each time.</p>
  
  <p>How can I generate/upload multiple audio files at once?</p>
  
  <pre><code>from flask import current_app, 
  from multiprocessing.pool import ThreadPool
  from Server.database import db
  import boto3
  import io
  import uuid
  
  
  def upload_audio_file_to_s3(file):
     app = current_app._get_current_object()
     with app.app_context():
        s3 = boto3.client(service_name='s3',
                 aws_access_key_id=app.config.get('BOTO3_ACCESS_KEY'),
                 aws_secret_access_key=app.config.get('BOTO3_SECRET_KEY'))
        extension = file.filename.rsplit('.', 1)[1].lower()
        file.filename = f"{uuid.uuid4().hex}.{extension}"
        s3.upload_fileobj(file,
           app.config.get('S3_BUCKET'),
           f"{app.config.get('UPLOADED_AUDIO_FOLDER')}/{file.filename}",
           ExtraArgs={"ACL": 'public-read', "ContentType": file.content_type})
        return file.filename
  
  def generate_polly(voice_id, text):
     app = current_app._get_current_object()
     with app.app_context():
        polly_client = boto3.Session(
           aws_access_key_id=app.config.get('BOTO3_ACCESS_KEY'),                   
           aws_secret_access_key=app.config.get('BOTO3_SECRET_KEY'),
           region_name=app.config.get('AWS_REGION')).client('polly')
        response = polly_client.synthesize_speech(VoiceId=voice_id,
                       OutputFormat='mp3', Text=text)
        return response['AudioStream'].read()
  
  
  def generate_polly_from_term(vocab_term, gender='m'):
     app = current_app._get_current_object()
     with app.app_context():
        audio = generate_polly('Celine', vocab_term.term)
        file = io.BytesIO(audio)
        file.filename = 'temp.mp3'
        file.content_type = 'mp3'
        return vocab_term.id, upload_audio_file_to_s3(file)
  
  def generate_async_audio_service(terms):
     pool = ThreadPool(processes=12)
     results = pool.map(generate_polly_from_term, terms)
     # do something w/ results
  </code></pre>