本文整理汇总了Python中sender.Sender.sendData方法的典型用法代码示例。如果您正苦于以下问题:Python Sender.sendData方法的具体用法?Python Sender.sendData怎么用?Python Sender.sendData使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类sender.Sender
的用法示例。
在下文中一共展示了Sender.sendData方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: postIpDel
# 需要导入模块: from sender import Sender [as 别名]
# 或者: from sender.Sender import sendData [as 别名]
def postIpDel(request):
form = IpForm(request.REQUEST, request.FILES)
if not form.is_valid():
return json_response({"status": FORM_ERR, "result": 'Ошибка формы'})
login = form.cleaned_data['user_login']
del_ips = json.loads(form.cleaned_data['ip_list'])
kwargs = {'action': 'del_ip', 'user': login, 'ip_list': '{ip_list:' + json.dumps(del_ips) + '}'}
from models import WebApiSetting
web_api_settings = WebApiSetting.objects.all();
if len(web_api_settings)>0:
sd = Sender(web_api_settings[0].host,web_api_settings[0].port, web_api_settings[0].users_url)
status, reason, resp = sd.sendData(kwargs)
if status == ERROR400:
return json_response({"status":LOGIN_ERR, "result": "Неверное указано имя пользователя"})
elif status != SUCCESS:
logging.error("videoclient.configuration.web_api_users.wiews.postIpDel(connection failed) :" + 'Ошибка соединения при получении списка ip адресов пользователя')
return json_response({"status":ERROR, "result": "Повторите запрос позже"})
else:
logging.error("videoclient.configuration.web_api_users.wiews.postIpDel(connection failed) :" + 'Отсутствуют настройки для WEB API')
return json_response({"status":ERROR, "result": "Повторите запрос позже"})
return json_response({"status": OK, "result": "IP-адреса удалены (" + str(len(del_ips)) + ')'})
示例2: postTableStatistics
# 需要导入模块: from sender import Sender [as 别名]
# 或者: from sender.Sender import sendData [as 别名]
def postTableStatistics(request):
form = StatisticForm(request.REQUEST, request.FILES)
if not form.is_valid():
return json_response({"status": FORM_ERR, "result": 'Повторите запрос позже'})
data = dict()
login = form.cleaned_data['user_login']
s_date = form.cleaned_data['start_date']
e_date = form.cleaned_data['end_date']
query = form.cleaned_data['query']
sorto = form.cleaned_data["sorto"]
data['sorto'] = sorto
data['up'] = form.cleaned_data['up']
kwargs = {'user': login, 'query': query, 'start_date': s_date, 'end_date': e_date}
from models import WebApiSetting
web_api_settings = WebApiSetting.objects.all();
if len(web_api_settings)==0:
logging.error("videoclient.configuration.web_api_users.wiews.postIpDel(connection failed) :" + 'Отсутствуют настройки для WEB API')
return json_response({"status": ERROR, "result": 'Стастистика временно недоступна. Повторите запрос позже.'})
sd = Sender(web_api_settings[0].host,web_api_settings[0].port, web_api_settings[0].stat_url)
status, reason, resp = sd.sendData(kwargs)
del sd
if status == ERROR400:
return json_response({"status": LOGIN_ERR, "result": 'Неизвестный пользователь'})
if status != SUCCESS:
return json_response({"status": ERROR, "result": 'Стастистика временно недоступна. Повторите запрос позже.'})
ipstat = json.loads(resp)
#вычисляем суммы столбцов и строк таблицы
total = {}
column_list = ['detect', 'detect_and_identification', 'fanstudio']
for column_name in column_list:
total[column_name] = 0
total['total'] = 0
for host in ipstat:
host['total'] = 0
for column_name in column_list:
total[column_name] += host[column_name]
total['total'] += host[column_name]
host['total'] += host[column_name]
#сортируем
sort_fields = ["ip", 'detect', 'detect_and_identification', 'fanstudio', 'total']
if sorto > 0 and sorto <= len(sort_fields):
sort = [[sort_fields[sorto - 1]]]
ipstat = GlobalSortUser(ipstat, sort, 1, up=form.cleaned_data["up"])
data['table'] = ipstat
data['total'] = total
from django.template import loader
if ipstat:
result = loader.render_to_string('stat_table.html', data)
else:
result = False
return json_response({'result': result, 'status': OK})
示例3: getTableIp
# 需要导入模块: from sender import Sender [as 别名]
# 或者: from sender.Sender import sendData [as 别名]
def getTableIp(request):
form = UserForm(request.REQUEST, request.FILES)
data = dict()
ips = []
if form.is_valid():
login = form.cleaned_data["user_login"]
sorto = form.cleaned_data["sorto"]
up = form.cleaned_data["up"]
data.update(form.cleaned_data)
kwargs = {'action': 'get_ip', 'user': login}
from models import WebApiSetting
web_api_settings = WebApiSetting.objects.all();
if len(web_api_settings)>0:
sd = Sender(web_api_settings[0].host,web_api_settings[0].port, web_api_settings[0].users_url)
status, reason, resp_str = sd.sendData(kwargs)
if status == ERROR400:
data["error"] = LOGIN_ERR
elif status != SUCCESS:
data["error"] = ERROR
else:
resp = json.loads(resp_str)
if 'ip_list' in resp:
ips = resp['ip_list']
else:
logging.error("videoclient.configuration.web_api_users.wiews.getTableIp(connection failed) :" + 'Отсутствуют настройки для WEB API')
data["error"] = ERROR
else:
data["user_login"] = ''
data["error"] = FORM_ERR
if 'error' in data:
return json_response({'status': data["error"], 'result': ''})
#сортируем
sort_fields = ["ip"]
sorto = form.cleaned_data["sorto"]
if sorto > 0 and sorto <= len(sort_fields):
ips = sorted(ips, reverse=(up == 0))
data["ip_list"] = ips
from django.template import loader
result = loader.render_to_string('ip_table.html', data, context_instance=RequestContext(request))
return json_response({'status': OK, 'result': result})
示例4: postChangeKeyAccess
# 需要导入模块: from sender import Sender [as 别名]
# 或者: from sender.Sender import sendData [as 别名]
def postChangeKeyAccess(request):
form = UserForm(request.REQUEST, request.FILES)
if not form.is_valid():
return json_response({"status": FORM_ERR, "result": 'Ошибка формы'})
login = form.cleaned_data["user_login"]
new_key = passgen(16)
kwargs = {'action': 'change_password', 'login': login, 'new_password': new_key}
from models import WebApiSetting
web_api_settings = WebApiSetting.objects.all();
if len(web_api_settings)==0:
logging.error("videoclient.configuration.web_api_users.wiews.postChangeKeyAccess(connection failed) :" + 'Отсутствуют настройки для WEB API')
return json_response({"status": ERROR, "result": 'Повторите запрос позже'})
sd = Sender(web_api_settings[0].host,web_api_settings[0].port, web_api_settings[0].users_url)
status, reason, resp = sd.sendData(kwargs)
if status == ERROR400:
return json_response({"status":LOGIN_ERR, "result": "Неверное указано имя пользователя"})
elif status != SUCCESS:
logging.error("videoclient.configuration.web_api_users.wiews.changeKeyAccess(connection failed) :" + 'Ошибка соединения при получении списка ip адресов пользователя')
return json_response({"status":ERROR, "result": "Повторите запрос позже"})
return json_response({'status': OK, 'result': str(new_key)})
示例5: postDataStatistics
# 需要导入模块: from sender import Sender [as 别名]
# 或者: from sender.Sender import sendData [as 别名]
def postDataStatistics(request):
form = StatisticForm(request.REQUEST, request.FILES)
data = dict()
if not form.is_valid():
return json_response({"status": FORM_ERR, "result": 'Повторите запрос позже'})
login = form.cleaned_data["user_login"]
s_date = form.cleaned_data['start_date']
e_date = form.cleaned_data['end_date']
query = form.cleaned_data['query']
data["user_login"] = login
kwargs = {'user': login, 'query': query, 'start_date': s_date, 'end_date': e_date}
from models import WebApiSetting
web_api_settings = WebApiSetting.objects.all();
if len(web_api_settings)==0:
logging.error("videoclient.configuration.web_api_users.wiews.postDataStatistics(connection failed) :" + 'Отсутствуют настройки для WEB API')
return json_response({"status": ERROR, "result": 'Стастистика временно недоступна. Повторите запрос позже.'})
sd = Sender(web_api_settings[0].host,web_api_settings[0].port, web_api_settings[0].stat_url)
status, reason, resp = sd.sendData(kwargs)
del sd
if status == ERROR400:
return json_response({"status": LOGIN_ERR, "result": 'Неизвестный пользователь'})
if status != SUCCESS:
return json_response({"status": ERROR, "result": 'Стастистика временно недоступна. Повторите запрос позже.'})
stat = json.loads(resp)
#если данных для отображения на графике нет, то выводим сообщение
if not filter(lambda x: len(filter(lambda x:x[1] > 0, x['data'])) > 0, stat):
return json_response({"status": NO_DATA, "result": 'Отсутствуют данные за указанный период'})
e = {}
e['resp'] = resp
return json_response({'result': e, 'status': OK})
示例6: getUsersList
# 需要导入模块: from sender import Sender [as 别名]
# 或者: from sender.Sender import sendData [as 别名]
def getUsersList():
from models import WebApiSetting
web_api_settings = WebApiSetting.objects.all();
if len(web_api_settings)>0:
sd = Sender(web_api_settings[0].host,web_api_settings[0].port, web_api_settings[0].users_url)
kwargs = {'action': 'get_users'}
status, reason, resp_str = sd.sendData(kwargs)
#print '>>',resp_str
#resp_str = '{"users":[{"login": "farLogin", "daemon_restrictions":{"detect":{"rpsec":10,"rpmin":10},"detect_and_identification":{"rpsec":10,"rpmin":10},"fanstudio":{"rpsec":10,"rpmin":10}},"ip_list":["192.168.0.166","192.168.0.152"]},{"login": "apicon", "daemon_restrictions":{"detect":{"rpsec":10,"rpmin":10},"detect_and_identification":{"rpsec":10,"rpmin":10},"fanstudio":{"rpsec":10,"rpmin":10}},"ip_list":["192.168.0.166","192.168.0.152","192.168.0.6","192.168.1.1","192.168.0.55","192.168.0.2","192.16.0.166","19.16.0.1","192.168.0.3","192.168.0.152","192.168.1.166","192.168.1.2"]}]}'
if status != SUCCESS:
resp = {}
else:
resp = json.loads(resp_str)
if 'users' in resp:
users = resp["users"]
else:
users = []
else:
users = []
return users
示例7: Peer
# 需要导入模块: from sender import Sender [as 别名]
# 或者: from sender.Sender import sendData [as 别名]
#.........这里部分代码省略.........
logging.error( 'Invalid msgType: ' + msgType )
elif package['packageType'] == 'command':
# Handle command from user input
command = package['command']
if command == 'insert':
logging.info( 'Processing insert file command: ' + package['filename'] )
self.status.insertFile( package['filename'], package['filepath'],\
package['filesize'] )
elif command == 'leave':
logging.info( 'Processing leave request' )
self.peerTCPServer.shutdown()
for p in self.activePeers:
peer = self.getPeerTuple( p )
result = self.sender.sendMessage( peer[0], peer[1], 'goodbye' )
if not result:
logging.error( 'Failed to send goodbye message to: ' + p )
self.joined = False # mark self as unjoined
self.rQueue = Queue() # Create new Queue to throw away pending requets
if self.shutdownFlag:
self.rQueue.put( 'shutdown' )
for p in self.activePeers:
# clear peer from status
self.status.removePeer( p )
self.activePeers = {}
elif command == 'remove':
fName = package['filename']
context = { 'type': 'remove' }
for p in self.activePeers:
peer = self.getPeerTuple( p )
result = self.sender.sendData( peer[0], peer[1], context, fName )
if not result:
logging.error( 'Failed to send delete message to: ' + p )
self.status.removeFile( fName )
else:
logging.error( 'Invalid command: ' + command )
else:
logging.error( 'Invalid packageType; package ignored' )
def shareChunks( self ):
"""Send out a chunk to each registered peer"""
for p in self.activePeers:
peer = self.getPeerTuple( p )
context, data = self.status.getChunkToSend( p )
if data is None:
continue # no chunks to share with that peer
context['type'] = 'chunk'
if self.sender.sendData( peer[0], peer[1], context, data ):
self.status.markChunkSent( p,context['filename'], context['chunkNum'] )
self.activePeers[ p ] = 0
else:
logging.error( 'Failed to send packet to: ' + p )
# increment number of failures
self.activePeers[ p ] += 1
# Remove any peers that failed too many times
self.checkPeerFailures()
示例8: postIpAdd
# 需要导入模块: from sender import Sender [as 别名]
# 或者: from sender.Sender import sendData [as 别名]
def postIpAdd(request):
form = IpForm(request.REQUEST, request.FILES)
if not form.is_valid():
return json_response({"status": FORM_ERR, "result": 'Ошибка формы'})
try:
#получаем список адресов данного пользователя:
login = form.cleaned_data['user_login']
kwargs = {'action': 'get_ip', 'user': login}
from models import WebApiSetting
web_api_settings = WebApiSetting.objects.all();
if len(web_api_settings)>0:
sd = Sender(web_api_settings[0].host,web_api_settings[0].port, web_api_settings[0].users_url)
status, reason, resp = sd.sendData(kwargs)
if status == ERROR400:
return json_response({"status":LOGIN_ERR, "result": "Неверное указано имя пользователя"})
elif status != SUCCESS:
logging.error("videoclient.configuration.web_api_users.wiews.post_ip_add(connection failed) :" + 'Ошибка соединения при получении списка ip адресов пользователя')
return json_response({"status":ERROR, "result": "Повторите запрос позже"})
ips = json.loads(resp)['ip_list']
#IP добавляемые пользователем:
add_ips = json.loads(form.cleaned_data['ip_list'])
#IP которые будут добавлены:
ip_list = []
for ip in add_ips:
a = ip.split('.')
add_ip = ''
if len(a) == 4:
err = False
for i in a:
try:
octet = int(i)
except:
octet = 256
if not (0 <= octet and octet < 256):
err = True
add_ip += '%s' % ('.' if add_ip else '') + str(octet)
if not err and not add_ip in ips and not add_ip in ip_list:
ip_list.append(add_ip)
if not ip_list:
return json_response({"status":IP_ERR, "result": "Новых IP-адресов не добавлено."})
#добавляем адреса
kwargs = {'action':'add_ip', 'user': login, 'ip_list': '{ip_list:' + json.dumps(ip_list) + '}'}
status, reason, resp = sd.sendData(kwargs)
if status != SUCCESS:
return json_response({"status":ERROR, "result": "Повторите запрос позже"})
return json_response({"status":OK, "result": ip_list})
else:
logging.error("videoclient.configuration.web_api_users.wiews.postIpAdd(connection failed) :" + 'Отсутствуют настройки для WEB API')
return json_response({"status":ERROR, "result": "Повторите запрос позже"})
except:
logging.error("addIpList" + str(sys.exc_info()))
return json_response({"status":ERROR, "result": "Повторите запрос позже"})