I am working on a projects that involves making many requests to an api and for each feedback I am making a decision and saving in the db. I am using adbapi to communicate to mysql.
I am receiving the request as a POST containing a list of items that are to be pushed to a remote api and saved.
I have noted that while processing the items in a deferred all the other operations block till one part is done.
The following is an examples that shows something similar to what I am doing.
#!/usr/bin/python2.7
from twisted.web.server import Site
from twisted.web.resource import Resource
from twisted.internet import reactor, defer
from twisted.web.server import NOT_DONE_YET
from utils import send_mail, save_in_db
def get_params(request):
params = {}
for k, v in request.args.items():
if k and v:
params[k] = v[0]
return params
class SendPage(Resource):
def render_POST(self, request):
params = get_params(request)
emails = params['emails']
message = params['message']
self.process_send_mail(message, emails)
request.write('Received')
request.finish()
return NOT_DONE_YET
def process_send_mail(self, message, emails):
defs = []
for email in emails:
d = send_mail(email, message)
defs.append(d)
d1 = defer.DeferredList(defs)
d1.addCallback(self.process_save)
def process_save(self, result):
defs = []
for r in result:
d = save_in_db(r)
defs.append(d)
d1 = defer.DeferredList(defs)
d1.addCallback(self.post_save)
def post_save(self, result):
print "request was completed"
root = Resource()
root.putChild("", SendPage())
factory = Site(root)
reactor.listenTCP(8880, factory)
reactor.run()
In the above examples, when I have a lot of emails in the list like 100,000 when I am doing send_mail
it blocks other operations till its finished. If I try sending another request while that is happening, it blocks till after its done.
My question is, is there a way I can have the operations happen concurrently? Can I send_mail and in a concurrent way save_in_db? can I do that as I receive other requests and handle without having to wait for each other to finish?