Advertisement
Guest User

Untitled

a guest
Jul 4th, 2017
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.87 KB | None | 0 0
  1. def calculation(request):
  2. # doing some simple calculation depending on request
  3. simple_result, parameter = simple_calculation(request)
  4. # trigger complex asynchronous calculation depending on parameter
  5. Channel('background-calculations').send({
  6. "parameter": parameter,
  7. })
  8. # return results of simple calculation
  9. return render(request, 'simple_reponse.html',{'simple_result': simple_result})
  10.  
  11. channel_routing = [
  12. route("background-calculations", run_background_calculations),
  13. route("websocket.connect", ws_connect),
  14. route("websocket.receive", ws_message),
  15. ]
  16.  
  17. def run_background_calculations(message):
  18. # perform complex calculation depending on parameter from simple calculation
  19. result = complex_calculation(message)
  20. # update frontend via websocket
  21. Group("frontend-updates").send({
  22. "text": json.dumps({
  23. "result": result,
  24. })
  25. })
  26.  
  27. @channel_session
  28. def ws_connect(message):
  29. message.reply_channel.send({"accept": True})
  30. Group("frontend-updates").add(message.reply_channel)
  31.  
  32.  
  33. @channel_session_user
  34. def ws_message(message):
  35. message.reply_channel.send({
  36. "text": message.content['text'],
  37. })
  38.  
  39. from channels.test import Client
  40. from rest_framework.test import APIClient
  41.  
  42. # setup
  43. rest = APIClient()
  44. channelclient = Client()
  45. Group("frontend-updates").add(u"test-channel")
  46. rest.login(username="username",password="password")
  47.  
  48. class CopyTestCase(ChannelTestCase):
  49. def test_end_to_end(self):
  50. # trigger HTTP POST request
  51. response = rest.post("/calculate/")
  52. #...check response...
  53.  
  54. # consume the background-calculation task (has to be done manually)
  55. channelclient.consume(u"background-calculations")
  56.  
  57. # check data sent to the front-end as a result of this calculation
  58. message = testcase.get_next_message(u"test-channel")
  59. #...check message...
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement