4

Is it possible to have a function return data to the caller function but continue its execution?

I'm maintaining a web app that requires a client service to be running in the background on the machine of whomever is using the app. The server connects to the client of the user via RPC. The client is a set of python scripts that are stored on GitHub and it needs to be updatable using a button on the web app. The update requires the client to pull the latest code from GitHub and then restart itself. What I want is for the update method inside of the client to post back information to the server concerning the status of the update, which will then be displayed to the user. So this information would be something like: "Downloading from GitHub...", "Finished downloading. Restarting", "Successfully updated."

Ben Davis
  • 617
  • 2
  • 11
  • 19
  • 1
    You're thinking of multithreaded. – David Robinson Mar 09 '13 at 22:49
  • 3
    You've described the [`yield` keyword](http://stackoverflow.com/questions/231767/the-python-yield-keyword-explained). – Benjamin Hodgson Mar 09 '13 at 22:49
  • 3
    @poorsod `yield` pauses execution, it doesn't continue after "returning" (yielding) some data. – Nick T Mar 09 '13 at 22:50
  • @NickT - the calling code returns control to the generator if it wants to, after it's dealt with whatever was `yield`ed, which in this case may simply be `print`ing it. Seems to me that this is what the OP wants (I may be wrong) - it certainly doesn't seem like he needs the complication of threading. – Benjamin Hodgson Mar 09 '13 at 23:29

2 Answers2

2

Use Python generators, in particular the yield statement does what you're asking.

Óscar López
  • 232,561
  • 37
  • 312
  • 386
  • 1
    I may be reading it differently, but it doesn't seem like he wants it to pause, but continue running. A job for threads of some sort, which could be wrapped in a myriad ways for simplicity. – Nick T Mar 09 '13 at 22:52
  • I'd read about generators before, but it seems like I didn't understand them properly; the're exactly what I was looking for. Would I be right in thinking that it's as simple as the update generator yielding progress information as it executes, which could then be read by the caller by iterating over the generator? – Ben Davis Mar 10 '13 at 01:13
  • Yes, that could work if implemented properly. Notice though, that if asynchronous behaviour is required, it'd be better idea to execute the process in a different thread – Óscar López Mar 10 '13 at 01:23
0

You could make your long-running job in the background with celery or something like this and store somewhere state info. Just pull state updates with AJAX or maybe with websockets and refresh status on page. Also you could find some RabbitMQ interfaces created on JS with which you can get updates if you don't want to store results in DB.

Also this might be helpful: django.http.StreamingHttpResponse

simplylizz
  • 1,686
  • 14
  • 28