问题
Let's assume the first ajax call is immediately made, the controller-called function loops until something is read, for example:
def FirstAjax():
while True:
if something is read:
val = something
break
return val
Before something is read the user presses the "Back" button and a new ajax request is sent, for example:
def SecondAjax():
print "Response from second ajax"
The second ajax call is really called (obviously, we're talking about async stuff :) ) but the text is not printed until the FirstAjax loop is completely done.
I want the second request to tell python to stop the action from the first request but don't know how it could be done!
回答1:
Use Celery.
Here's the process:
Make
FirstAjax
request. Python queues the task using celery. You can have the task start immediately or in a few minutes/hours/days. FirstAjax sends back the id of the task created, while the task itself is queued to be executed in the background. Using celery task idsMake
SecondAjax
, sending along the task id. Use that task id to cancel the task. How to cancel a celery task.
回答2:
It's possible that the second Ajax request is being blocked until the first completes because the session file may be locked. Assuming the first Ajax request doesn't need to use the session, you can have it unlock the session:
def FirstAjax():
session.forget(response) # unlock the session file
[rest of code]
See here for more details.
回答3:
Problem resolved, it was a specific web2py problem.
def FirstAjax():
session.forget(response) # unlock the session file
[rest of code]
Talks web2py to don't lock session files, so that second ajax can start immediately. An other way is to set:
session.connect(request, response, db)
in your models, it means session will not be saved in files but in your DAL "db", so that session will not be locked.
These two solutions are the same for what I need.
In my case I also need to do a device release when the back button is pressed, just added a flag to be checked in the polling cycle, for example:
def FirstAjax():
session.forget(response) # unlock the session file
HSCAN.SetLeave(False)
HSCAN.PollingCycle()
#Rest of code
def SecondAjax():
HSCAN.SetLeave(True)
#Rest of code
class myHandScanner():
def __init__(self):
self.leave = False
def SetLeave(self, leave):
self.leave = leave
def PollingCycle(self):
while True:
if self.leave:
#Do device release
return
if something is read:
val = something
break
#Do device release
return val
Thanks everybody and hope this helps!
来源:https://stackoverflow.com/questions/10520954/different-ajax-calls-with-polling-cycle