title: Python Django multiprocessing Error: "AttributeError: Can't pickle local object 'Command.handle.<locals>.f'"
body: <p>I'm using python 3.6 django 1.11 windows10 and trying to send email using multiprocessing.</p>
  
  <p>recipients are connected to database(django model) and email contents form is html(by django get_template), also used get_connection to send multi-email. What I'm trying is to use multiprocessing to accelerate sending rate.</p>
  
  <p>My code is here</p>
  
  <pre><code>from django.core.management.base import BaseCommand
  from django.core.mail import get_connection, EmailMessage
  from django.template.loader import get_template
  
  from multiprocessing import Pool
  
  from sending.models import Subscriber
  
  
  class Command(BaseCommand):
      def handle(self, *args, **options):
  
          connection = get_connection()
  
          recipients = [i.email for i in Subscriber.objects.all()]
          num = Subscriber.objects.count()
  
          subject = 'Multiprocessing trying 1'
          body = get_template('Newsletter20171229.html').render()
          from_email = 'info@modoodoc.com'
  
  
          def send(i):
              msg = EmailMessage(subject, body, from_email, [recipients[i]])
              msg.content_subtype = 'html'
  
              print("Sending email to: " + recipients[i] + " No: " + str(i))
              connection.send_messages([msg])
              print("Complete.")
  
          pool = Pool(processes=2)
          pool.map(send, range(0, num))
  
  
          print("Mail have just sent. The program is going to end.")
          connection.close()
  </code></pre>
  
  <p>And I've got an error like this.</p>
  
  <pre><code>  File "c:\python36-32\Lib\multiprocessing\connection.py", line 206, in send
      self._send_bytes(_ForkingPickler.dumps(obj))
    File "c:\python36-32\Lib\multiprocessing\reduction.py", line 51, in dumps
      cls(buf, protocol).dump(obj)
  AttributeError: Can't pickle local object 'Command.handle.&lt;locals&gt;.f'
  </code></pre>
  
  <p>How to fix this?</p>
  
  <p>Thank you.</p>