def handle(self, **options):
'''
In this example command, the values that come from the user input are
added up and the result is printed in the screen.
'''
stack = options['path'][0]
output_vector_file = '/Users/agutierrez/%s.gpkg' % get_basename(stack)
segmentation = bis.Model()
shapes, transform, meta = segmentation.predict(stack)
# Vectorize
#shapes = features.shapes(segments.astype(np.uint16), transform=transform)
start_time = time.time()
print 'about to start query'
query = persist_database(shapes, meta)
print 'done'
print time.time() - start_time
start_time = time.time()
with connection.cursor() as cursor:
cursor.execute(query)
transaction.commit()
print time.time() - start_time
#persist_file(shapes, output_vector_file, meta)
python类commit()的实例源码
def test_timeout(self):
"""Test that when a session is established, then left idle
for the timeout period, the http_agent service emits
a termination message on the RX channel."""
session_id = self._open_session()
# No alert to begin with
alerts = HostContactAlert.filter_by_item(self.host)
self.assertEqual(alerts.count(), 0)
time.sleep(HostState.CONTACT_TIMEOUT + HostStatePoller.POLL_INTERVAL + RABBITMQ_GRACE_PERIOD)
# Should be one SESSION_TERMINATE message to AMQP with a matching session ID
message = self._receive_one_amqp()
self.assertDictEqual(message, {
'fqdn': self.CLIENT_NAME,
'type': 'SESSION_TERMINATE',
'plugin': self.PLUGIN,
'session_seq': None,
'session_id': session_id,
'body': None
})
with transaction.commit_manually():
transaction.commit()
alerts = HostContactAlert.filter_by_item(self.host)
self.assertEqual(alerts.count(), 1)
# Should be a message waiting for the agent telling it that its session was terminated
# (timing out doesn't mean the agent is gone, it could just be experiencing network difficulties)
# What's more, the agent doesn't necessarily *know* that it had network difficulties, e.g. if it
# just got real slow and waited too long between GETs.
# This has to cut both ways to be reliable:
# * We have to tell the agent that we thought it went away, by sending a TERMINATE for sessions
# * If the agent finds that a GET fails then it has to assume that we might have put session
# messages in that GET, and terminate all its sessions in case one of those GET messages
# was really a TERMINATE
response = self._get()
self.assertResponseOk(response)
forwarded_messages = response.json()['messages']
self.assertEqual(len(forwarded_messages), 1)
self.assertDictEqual(forwarded_messages[0], {
'fqdn': self.CLIENT_NAME,
'type': 'SESSION_TERMINATE',
'plugin': self.PLUGIN,
'session_seq': None,
'session_id': None,
'body': None
})
def _call(self, fn_name, *args, **kwargs):
with transaction.commit_manually():
transaction.commit()
# If the caller specified rcp_timeout then fetch it from the args and remove.
rpc_timeout = kwargs.pop('rpc_timeout', RESPONSE_TIMEOUT)
request_id = uuid.uuid4().__str__()
request = {
'method': fn_name,
'args': args,
'kwargs': kwargs,
'request_id': request_id}
log.debug("Starting rpc: %s, id: %s " % (fn_name, request_id))
log.debug("_call: %s %s %s %s" % (request_id, fn_name, args, kwargs))
rpc_client = RpcClientFactory.get_client(self.__class__.__name__)
result = rpc_client.call(request, rpc_timeout)
if result['exception']:
log.error("ServiceRpcInterface._call: exception %s: %s \ttraceback: %s" % (result['exception'], result['exception_type'], result.get('traceback')))
raise RpcError(result['exception'], result.get('exception_type'), traceback=result.get('traceback'))
else:
# NB: 'result' can be very large, and almost cripple the various logs where
# rpcs are run: http.log, job_scheduler.log, etc.
# If you want to see response result data from rpcs at the INFO level, consider writing
# log messages into the JobSchedulerClient calls. Leaving this in for DEBUG.
if log.getEffectiveLevel() is not logging.DEBUG:
# Truncate message
result100 = str(result)[:100]
if str(result) != result100:
result100 += "..."
result_str = result100
else:
result_str = result
log.debug("Completed rpc: %s, id: %s, result: %s" % (fn_name, request_id, result_str))
return result['result']
def task_add(request):
'''????'''
if request.method == 'GET':
form = TaskAddForm()
else:
form = TaskAddForm(request.POST)
# end if
if not form.is_valid():
#print 1000*'A'
return render(
request,
'task_add.html',
context_instance = RequestContext(request,
{
'form': form ,
})
# end if
)
target = form.cleaned_data.get('target','')
#?????????
if str(request.path).lower() == '/task/add':
attack_type = form.cleaned_data.get('attack_type', '')
task_name = form.cleaned_data.get('task_name', '')
target = target.strip()
target = target.strip().split('\r\n')
if len(target)>1:
target = ','.join(target)# fnascan ??????
elif len(target)==1:
target = target[0]
# end if
param = dict(form.data)
for k in param.keys():
param[k] = param[k][0]
# end for
param[u'ip_range'] = target
param_str = json.dumps(param)
print ">>>>>>>Staring Single Module ATTACK %s<<<<<<<" ,target
task = Task(attack_target = target, attack_type = attack_type,task_name = task_name, status = 'WAITTING', parameter = param_str)
task.save()
transaction.commit()
# end if
html = '<!doctype html><html><head><script>confirm("%s"); window.location = "/";</script></head><body> </html>'
if len('cc') > 1:
ret = html % '??%s???' % str(target) #?????
else:
ret = html % '??%i???' % str(target) #?????
# end if
return response(ret)
# end def task_add
def create_instance(username, xml_file, media_files,
status=u'submitted_via_web', uuid=None,
date_created_override=None, request=None):
"""
I used to check if this file had been submitted already, I've
taken this out because it was too slow. Now we're going to create
a way for an admin to mark duplicate instances. This should
simplify things a bit.
Submission cases:
If there is a username and no uuid, submitting an old ODK form.
If there is a username and a uuid, submitting a new ODK form.
"""
try:
instance = None
submitted_by = request.user \
if request and request.user.is_authenticated() else None
if username:
username = username.lower()
xml = xml_file.read()
xform = get_xform_from_submission(xml, username, uuid)
check_submission_permissions(request, xform)
existing_instance_count = Instance.objects.filter(
xml=xml, xform__user=xform.user).count()
if existing_instance_count > 0:
existing_instance = Instance.objects.filter(
xml=xml, xform__user=xform.user)[0]
if not existing_instance.xform or\
existing_instance.xform.has_start_time:
# Ignore submission as a duplicate IFF
# * a submission's XForm collects start time
# * the submitted XML is an exact match with one that
# has already been submitted for that user.
raise DuplicateInstance()
# get new and depracated uuid's
new_uuid = get_uuid_from_xml(xml)
duplicate_instances = Instance.objects.filter(uuid=new_uuid)
if duplicate_instances:
for f in media_files:
Attachment.objects.get_or_create(
instance=duplicate_instances[0],
media_file=f, mimetype=f.content_type)
# ensure we have saved the extra attachments
transaction.commit()
raise DuplicateInstance()
instance = save_submission(xform, xml, media_files, new_uuid,
submitted_by, status, date_created_override)
# commit all changes
transaction.commit()
return instance
except Exception:
transaction.rollback()
raise