Guest User

Untitled

a guest
May 31st, 2017
45
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.26 KB | None | 0 0
  1. def get_trafico_actual_servicio(request):
  2.    
  3.     empresa = request.user.perfilusuario.empresa
  4.     usuario = request.GET['usuario']
  5.     id_servicio = request.GET['id_servicio']
  6.     interface = request.GET['interface']
  7.  
  8.     gibibyte = 1073741824
  9.     mebibyte =  1048576  
  10.    
  11.  
  12.     #cliente = ServiciosCliente.objects.prefetch_related('user__perfilusuario').filter(cliente_rb=servicio, empresa = empresa)
  13.     usuario_cliente = get_object_or_404(User, username = usuario)
  14.     servicio_cliente = get_object_or_404(ServiciosCliente.objects.prefetch_related('user__perfilusuario', 'router_cliente'), user = usuario_cliente, id_servicio = id_servicio, empresa = empresa)
  15.  
  16.     router = servicio_cliente.router_cliente
  17.     try:
  18.         connection = routeros_api.RouterOsApiPool(router.ip, username=router.usuario_router, password=router.password,
  19.                                                   port=router.puerto)
  20.         api = connection.get_api()
  21.     except:
  22.         pass
  23.  
  24.     torch_ip_result = "0/0"
  25.     tx=0
  26.     rx=0
  27.     if connection.connected:
  28.         torch_ip = api.get_resource('/tool')
  29.  
  30.         try:
  31.             torch_ip_promise = torch_ip.call_async('torch', {'interface': interface, 'src_address': servicio_cliente.ip, 'port': 'any'})
  32.         iterator = iter(torch_ip_promise)
  33.         result = next(iterator) # waits for first answer
  34.         if first_result['.section'] == '0': #sometimes mikrotik returns no data in first answer.
  35.                 result = next(iterator) # waits for second answer
  36.         api.get_resource('/').call('cancel') # cancels last command
  37.             try:
  38.         torch_ip_promise.get() # without this there may be some garbage left in memory (This cleanup should be implemented in library but is not yet)
  39.             except RouterOsApiCommunicationError: #command was canceled so exception was raised - it is expected
  40.         pass
  41.             get_torch_success = True
  42.         except RouterOsApiCommunicationError:
  43.             get_torch_success = False
  44.  
  45.         if get_torch_success and len(torch_ip_result) > 0:
  46.             rx= int(result['rx'])/mebibyte
  47.             rx= round(rx, 2)
  48.             tx = int(result['tx']) / mebibyte
  49.             tx = round(tx, 2)
  50.             data_torch_ip = [1,tx, rx ]
  51.  
  52.     return JsonResponse({"tx": tx, "rx": rx})
Add Comment
Please, Sign In to add comment