Python uuid.uuid1() Examples
The following are 30
code examples of uuid.uuid1().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
uuid
, or try the search function
.
Example #1
Source File: upload.py From video2commons with GNU General Public License v3.0 | 16 votes |
def upload(): f = request.files['file'] assert f, "Where's my file?" filekey = request.form.get('filekey') or str(uuid.uuid1()) assert RE_ALLOWED_FILEKEYS.match('filekey'), 'Unacceptable file key' permpath = getpath(filekey) content_range = (f.headers.get('Content-Range') or request.headers.get('Content-Range')) if content_range: result, kwargs = handle_chunked(f, permpath, content_range) else: result, kwargs = handle_full(f, permpath) kwargs['filekey'] = filekey return jsonify(result=result, **kwargs) # Flask endpoint
Example #2
Source File: paddle_server.py From LearnPaddle2 with Apache License 2.0 | 9 votes |
def infer(): f = request.files['img'] # 保存图片 save_father_path = 'images' img_path = os.path.join(save_father_path, str(uuid.uuid1()) + '.' + secure_filename(f.filename).split('.')[-1]) if not os.path.exists(save_father_path): os.makedirs(save_father_path) f.save(img_path) # 开始预测图片 img = load_image(img_path) result = exe.run(program=infer_program, feed={feeded_var_names[0]: img}, fetch_list=target_var) # 显示图片并输出结果最大的label lab = np.argsort(result)[0][0][-1] names = ['苹果', '哈密瓜', '胡萝卜', '樱桃', '黄瓜', '西瓜'] # 打印和返回预测结果 r = '{"label":%d, "name":"%s", "possibility":%f}' % (lab, names[lab], result[0][0][lab]) print(r) return r
Example #3
Source File: pipeline.py From browserscope with Apache License 2.0 | 7 votes |
def start_test(self, idempotence_key=None, base_path='', **kwargs): """Starts this pipeline in test fashion. Args: idempotence_key: Dummy idempotence_key to use for this root pipeline. base_path: Dummy base URL path to use for this root pipeline. kwargs: Ignored keyword arguments usually passed to start(). """ if not idempotence_key: idempotence_key = uuid.uuid1().hex pipeline_key = db.Key.from_path(_PipelineRecord.kind(), idempotence_key) context = _PipelineContext('', 'default', base_path) future = PipelineFuture(self.output_names, force_strict=True) self._set_values_internal( context, pipeline_key, pipeline_key, future, _PipelineRecord.WAITING) context.start_test(self) # Pipeline control methods.
Example #4
Source File: point.py From StructEngPy with MIT License | 6 votes |
def add_point(self,x,y,z): """ Add point object to model, if the name already exists, an exception will be raised. if a point in same location exists, the name of the point will be returned. param: x,y,z: float-like, coordinates in SI. [name]: str, name, optional. return: str, the new point's name. """ try: pt=Point() pt.x=x pt.y=y pt.z=z pt.uuid=str(uuid.uuid1()) pt.name=pt.uuid self.session.add(pt) return pt.name except Exception as e: logger.info(str(e)) self.session.rollback() return False
Example #5
Source File: element.py From StructEngPy with MIT License | 6 votes |
def __init__(self,dim,dof,name=None): self._name=uuid.uuid1() if name==None else name self._hid=None #hidden id self._dim=dim self._dof=dof self._nodes=[] self._D=None self._L=None self._mass=None self._T=None self._Ke=None self._Me=None self._re=None self._local_csys=None
Example #6
Source File: orderpackage.py From flumine with MIT License | 6 votes |
def __init__( self, client, market_id: str, orders: list, package_type: OrderPackageType, market, async_: bool = False, ): super(BaseOrderPackage, self).__init__(None) self.id = uuid.uuid1() self.client = client self.market_id = market_id self._orders = orders self.package_type = package_type self.market = market self.async_ = async_ self.customer_strategy_ref = config.hostname self.processed = False # used for simulated execution
Example #7
Source File: AzureClassic.py From im with GNU General Public License v3.0 | 6 votes |
def gen_data_disks(system, storage_account): """ Gen the DataVirtualHardDisks part of the XML of the VM creation """ disks = "" cont = 1 while system.getValue("disk." + str(cont) + ".size") and system.getValue("disk." + str(cont) + ".device"): disk_size = system.getFeature( "disk." + str(cont) + ".size").getValue('G') disk_name = "datadisk-1-" + str(uuid.uuid1()) disks += ''' <DataVirtualHardDisks> <DataVirtualHardDisk> <HostCaching>ReadWrite</HostCaching> <Lun>%d</Lun> <LogicalDiskSizeInGB>%d</LogicalDiskSizeInGB> <MediaLink>https://%s.blob.core.windows.net/vhds/%s.vhd</MediaLink> </DataVirtualHardDisk> </DataVirtualHardDisks> ''' % (cont, int(disk_size), storage_account, disk_name) cont += 1 return disks
Example #8
Source File: Collection.py From fullrmc with GNU Affero General Public License v3.0 | 6 votes |
def collect(self, index, dataDict, check=True): """ Collect atom given its index. :Parameters: #. index (int): The atom index to collect. #. dataDict (dict): The atom data dict to collect. #. check (boolean): Whether to check dataDict keys before collecting. If set to False, user promises that collected data is a dictionary and contains the needed keys. """ assert not self.is_collected(index), LOGGER.error("attempting to collect and already collected atom of index '%i'"%index) # add data if check: assert isinstance(dataDict, dict), LOGGER.error("dataDict must be a dictionary of data where keys are dataKeys") assert tuple(sorted(dataDict)) == self.__dataKeys, LOGGER.error("dataDict keys don't match promised dataKeys") self.__collectedData[index] = dataDict # set indexes sorted array idx = np.searchsorted(a=self.__indexesSortedArray, v=index, side='left') self.__indexesSortedArray = np.insert(self.__indexesSortedArray, idx, index) # set state self.__state = str(uuid.uuid1())
Example #9
Source File: Collection.py From fullrmc with GNU Affero General Public License v3.0 | 6 votes |
def release(self, index): """ Release atom from list of collected atoms and return its collected data. :Parameters: #. index (int): The atom index to release. :Returns: #. dataDict (dict): The released atom collected data. """ if not self.is_collected(index): LOGGER.warn("Attempting to release atom %i that is not collected."%index) return index = self.__collectedData.pop(index) # set indexes sorted array idx = np.searchsorted(a=self.__indexesSortedArray, v=index, side='left') self.__indexesSortedArray = np.insert(self.__indexesSortedArray, idx, index) # set state self.__state = str(uuid.uuid1()) # return return index
Example #10
Source File: test_bot_adapter.py From botbuilder-python with MIT License | 6 votes |
def test_pass_resource_responses_through(self): def validate_responses( # pylint: disable=unused-argument activities: List[Activity], ): pass # no need to do anything. adapter = SimpleAdapter(call_on_send=validate_responses) context = TurnContext(adapter, Activity()) activity_id = str(uuid.uuid1()) activity = TestMessage.message(activity_id) resource_response = await context.send_activity(activity) self.assertTrue( resource_response.id != activity_id, "Incorrect response Id returned" )
Example #11
Source File: waterfall_dialog.py From botbuilder-python with MIT License | 6 votes |
def begin_dialog( self, dialog_context: DialogContext, options: object = None ) -> DialogTurnResult: if not dialog_context: raise TypeError("WaterfallDialog.begin_dialog(): dc cannot be None.") # Initialize waterfall state state = dialog_context.active_dialog.state instance_id = uuid.uuid1().__str__() state[self.PersistedOptions] = options state[self.PersistedValues] = {} state[self.PersistedInstanceId] = instance_id properties = {} properties["DialogId"] = self.id properties["InstanceId"] = instance_id self.telemetry_client.track_event("WaterfallStart", properties) # Run first stepkinds return await self.run_step(dialog_context, 0, DialogReason.BeginCalled, None)
Example #12
Source File: rabbitmqtransport.py From waspy with Apache License 2.0 | 6 votes |
def __init__(self, *, url=None, port=5672, virtualhost='/', username='guest', password='guest', ssl=False, verify_ssl=True, heartbeat=20): super().__init__() self._transport = None self._protocol = None self._response_futures = {} self.host = url self.port = port self.virtualhost = virtualhost self.username = username self.password = password self.ssl = ssl self.verify_ssl = verify_ssl self.response_queue_name = str(uuid.uuid1()).encode() self._consumer_tag = None self._closing = False self.channel = None self.heartbeat = heartbeat self._connected = False if not url: raise TypeError("RabbitMqClientTransport() missing 1 required keyword-only argument: 'url'")
Example #13
Source File: parallel.py From dataflow with Apache License 2.0 | 6 votes |
def _get_pipe_name(name): if sys.platform.startswith('linux'): # linux supports abstract sockets: http://api.zeromq.org/4-1:zmq-ipc pipename = "ipc://@{}-pipe-{}".format(name, str(uuid.uuid1())[:8]) pipedir = os.environ.get('TENSORPACK_PIPEDIR', None) if pipedir is not None: logger.warn("TENSORPACK_PIPEDIR is not used on Linux any more! Abstract sockets will be used.") else: pipedir = os.environ.get('TENSORPACK_PIPEDIR', None) if pipedir is not None: logger.info("ZMQ uses TENSORPACK_PIPEDIR={}".format(pipedir)) else: pipedir = '.' assert os.path.isdir(pipedir), pipedir filename = '{}/{}-pipe-{}'.format(pipedir.rstrip('/'), name, str(uuid.uuid1())[:6]) assert not os.path.exists(filename), "Pipe {} exists! You may be unlucky.".format(filename) pipename = "ipc://{}".format(filename) return pipename
Example #14
Source File: common.py From shoogle with GNU General Public License v3.0 | 6 votes |
def get_credentials_path(required_scopes, credentials_profile): """Return the path of the credentials file.""" logger.debug("Searching credentials with scopes: " + str(required_scopes)) basedir = config.credentials_base_dir credentials_dir = os.path.join(basedir, credentials_profile) lib.mkdir_p(credentials_dir) for path in glob.glob(os.path.join(credentials_dir, "*.json")): credentials = json.load(open(path)) credentials_scope = set(credentials.get("scopes", [])) if credentials_scope.issuperset(required_scopes): logger.info("Using credentials: {}".format(path)) return path uuid_value = str(uuid.uuid1()) filename = "credentials-{uuid}.json".format(uuid=uuid_value) new_path = os.path.join(credentials_dir, filename) logger.debug("No credentials for scopes, create new file: " + new_path) return new_path
Example #15
Source File: graph_tests.py From arches with GNU Affero General Public License v3.0 | 6 votes |
def test_graph_validation_of_invalid_ontology_class(self): """ test to make sure invalid ontology classes aren't allowed """ graph = Graph.objects.get(graphid=self.rootNode.graph_id) new_node = graph.add_node( {"nodeid": uuid.uuid1(), "datatype": "semantic", "ontologyclass": "InvalidOntologyClass"} ) # A blank node with an invalid ontology class specified graph.add_edge({"domainnode_id": self.rootNode.pk, "rangenode_id": new_node.pk, "ontologyproperty": None}) with self.assertRaises(GraphValidationError) as cm: graph.save() the_exception = cm.exception self.assertEqual(the_exception.code, 1001)
Example #16
Source File: postgres_ext.py From Quiver-alfred with MIT License | 6 votes |
def execute_sql(self, sql, params=None, require_commit=True, named_cursor=False): logger.debug((sql, params)) use_named_cursor = (named_cursor or ( self.server_side_cursors and sql.lower().startswith('select'))) with self.exception_wrapper(): if use_named_cursor: cursor = self.get_cursor(name=str(uuid.uuid1())) require_commit = False else: cursor = self.get_cursor() try: cursor.execute(sql, params or ()) except Exception as exc: if self.get_autocommit() and self.autorollback: self.rollback() raise else: if require_commit and self.get_autocommit(): self.commit() return cursor
Example #17
Source File: test_serialize.py From Pyro5 with MIT License | 5 votes |
def testUUID(self): data = uuid.uuid1() ser = self.serializer.dumps(data) data2 = self.serializer.loads(ser) uuid_as_str = str(data) assert data2==data or data2==uuid_as_str
Example #18
Source File: OCCI.py From im with GNU General Public License v3.0 | 5 votes |
def create_volume(self, size, name, auth_data, auth_header): """ Creates a volume of the specified data (in GB) returns the OCCI ID of the storage object """ try: volume_id = "im-vol-%s" % str(uuid.uuid1()) body = 'Category: storage; scheme="http://schemas.ogf.org/occi/infrastructure#"; class="kind"\n' body += 'X-OCCI-Attribute: occi.core.id="%s"\n' % volume_id body += 'X-OCCI-Attribute: occi.core.title="%s"\n' % name body += 'X-OCCI-Attribute: occi.storage.size=%d\n' % int(size) headers = {'Accept': 'text/plain', 'Connection': 'close', 'Content-Type': 'text/plain,text/occi'} if auth_header: headers.update(auth_header) resp = self.create_request('POST', self.cloud.path + "/storage/", auth_data, headers, body) if resp.status_code != 201 and resp.status_code != 200: return False, resp.reason + "\n" + resp.text else: occi_id = os.path.basename(resp.text) return True, occi_id except Exception as ex: self.log_exception("Error creating volume") return False, str(ex)
Example #19
Source File: graph_tests.py From arches with GNU Affero General Public License v3.0 | 5 votes |
def test_graph_validation_of_null_ontology_class(self): """ test to make sure null ontology classes aren't allowed """ graph = Graph.objects.get(graphid=self.rootNode.graph_id) new_node = graph.add_node({"nodeid": uuid.uuid1(), "datatype": "semantic"}) # A blank node with no ontology class is specified graph.add_edge({"domainnode_id": self.rootNode.pk, "rangenode_id": new_node.pk, "ontologyproperty": None}) with self.assertRaises(GraphValidationError) as cm: graph.save() the_exception = cm.exception self.assertEqual(the_exception.code, 1000)
Example #20
Source File: graph.py From arches with GNU Affero General Public License v3.0 | 5 votes |
def add_card(self, card): """ Adds a card to this graph Arguments: card -- a dictionary representing a Card instance or an actual models.CardModel instance """ if not isinstance(card, models.CardModel): cardobj = card.copy() card = models.CardModel() card.cardid = cardobj.get("cardid", None) card.name = cardobj.get("name", "") card.description = cardobj.get("description", "") card.instructions = cardobj.get("instructions", "") card.helpenabled = cardobj.get("helpenabled", "") card.helptitle = cardobj.get("helptitle", "") card.helptext = cardobj.get("helptext", "") card.active = cardobj.get("active", "") card.visible = cardobj.get("visible", "") card.sortorder = cardobj.get("sortorder", "") card.component_id = cardobj.get("component_id", uuid.UUID("f05e4d3a-53c1-11e8-b0ea-784f435179ea")) card.nodegroup_id = uuid.UUID(str(cardobj.get("nodegroup_id", ""))) card.nodegroup = self.get_or_create_nodegroup(nodegroupid=card.nodegroup_id) card.config = cardobj.get("config", None) constraints = cardobj.get("constraints", "") for constraint in constraints: self.add_card_contraint(constraint, card) card.graph = self if card.pk is None: card.pk = uuid.uuid1() self.cards[card.pk] = card widgets = list(card.cardxnodexwidget_set.all()) for widget in widgets: self.widgets[widget.pk] = widget return card
Example #21
Source File: compliance.py From data-repository-service-schemas with Apache License 2.0 | 5 votes |
def test_list_objects_with_nonexist_alias(self): """ Test to ensure that looking up a nonexistent alias returns an empty list. """ alias = str(uuid.uuid1()) # An alias that is unlikely to exist body = self.drs_request('GET', self.get_query_url('/objects', alias=alias)) self.assertEqual(len(body['objects']), 0)
Example #22
Source File: graph.py From arches with GNU Affero General Public License v3.0 | 5 votes |
def add_edge(self, edge): """ Adds an edge to this graph will throw an error if the domain or range nodes referenced in this edge haven't already been added to this graph Arguments: edge -- a dictionary representing a Edge instance or an actual models.Edge instance """ if not isinstance(edge, models.Edge): egdeobj = edge.copy() edge = models.Edge() edge.edgeid = egdeobj.get("edgeid", None) edge.rangenode = self.nodes[uuid.UUID(str(egdeobj.get("rangenode_id")))] edge.domainnode = self.nodes[uuid.UUID(str(egdeobj.get("domainnode_id")))] edge.ontologyproperty = egdeobj.get("ontologyproperty", "") edge.graph = self if edge.pk is None: edge.pk = uuid.uuid1() if self.ontology is None: edge.ontologyproperty = None self.edges[edge.pk] = edge return edge
Example #23
Source File: graph.py From arches with GNU Affero General Public License v3.0 | 5 votes |
def new(name="", is_resource=False, author=""): newid = uuid.uuid1() nodegroup = None graph = models.GraphModel.objects.create( name=name, subtitle="", author=author, description="", version="", isresource=is_resource, isactive=not is_resource, iconclass="", ontology=None, slug=None, ) if not is_resource: nodegroup = models.NodeGroup.objects.create(pk=newid) models.CardModel.objects.create(nodegroup=nodegroup, name=name, graph=graph) root = models.Node.objects.create( pk=newid, name=_("Top Node"), description="", istopnode=True, ontologyclass=None, datatype="semantic", nodegroup=nodegroup, graph=graph, ) return Graph.objects.get(pk=graph.graphid)
Example #24
Source File: OCCI.py From im with GNU General Public License v3.0 | 5 votes |
def attach_volume(self, vm, volume_id, device, mount_path, auth_data, auth_header): """ Attach a volume to a running VM """ _, occi_info = self.query_occi(auth_data, auth_header) url = self.get_property_from_category(occi_info, "storagelink", "location") if not url: self.log_error("No location for storagelink category.") return (False, "No location for storagelink category.") try: headers = {'Accept': 'text/plain', 'Connection': 'close', 'Content-Type': 'text/plain,text/occi'} if auth_header: headers.update(auth_header) disk_id = "imdisk-%s" % str(uuid.uuid1()) body = 'Category: storagelink;scheme="http://schemas.ogf.org/occi/infrastructure#";class="kind"\n' body += 'X-OCCI-Attribute: occi.core.id="%s"\n' % disk_id body += 'X-OCCI-Attribute: occi.core.target="%s/storage/%s"\n' % (self.cloud.path, volume_id) body += 'X-OCCI-Attribute: occi.core.source="%s/compute/%s"' % (self.cloud.path, vm.id) if device: body += '\nX-OCCI-Attribute: occi.storagelink.deviceid="/dev/%s"' % device # body += 'X-OCCI-Attribute: occi.storagelink.mountpoint="%s"' % mount_path resp = self.create_request('POST', url, auth_data, headers, body) if resp.status_code != 201 and resp.status_code != 200: self.log_error("Error attaching disk to the VM: " + resp.reason + "\n" + resp.text) return False else: return True except Exception: self.log_exception("Error connecting with OCCI server") return False
Example #25
Source File: x_callback_url.py From pythonista-scripts with MIT License | 5 votes |
def open_url(url, handler): global _handler global _requestID _requestID = uuid.uuid1() _handler = handler url_with_uuid = url + 'xcallbackresponse-' + str(_requestID) webbrowser.open(url_with_uuid)
Example #26
Source File: storage.py From coursys with GNU General Public License v3.0 | 5 votes |
def upload_path(*path_components): """ Builds an upload path that will be unique: upload_path(a, b, c, filename) -> year/month/a/b/c/uuid1/filename """ today = datetime.date.today() filename = path_components[-1] path_components = list(path_components[:-1]) uu = uuid.uuid1(uuid.getnode()) components = [today.strftime('%Y'), today.strftime('%m')] + path_components + [str(uu), filename] # make sure filenames are entirely ASCII components = [c.encode('ascii', 'ignore').decode('ascii') for c in components] return os.path.join(*components)
Example #27
Source File: packaging.py From tf-yarn with Apache License 2.0 | 5 votes |
def _get_tmp_dir(): tmp_dir = f"/tmp/{uuid.uuid1()}" _logger.debug(f"local tmp_dir {tmp_dir}") os.makedirs(tmp_dir, exist_ok=True) return tmp_dir
Example #28
Source File: Docker.py From im with GNU General Public License v3.0 | 5 votes |
def _create_volumes(self, system, auth_data): cont = 1 headers = {'Content-Type': 'application/json'} while system.getValue("disk." + str(cont) + ".mount_path"): # user device as volume name source = system.getValue("disk." + str(cont) + ".device") if not source: source = "d-%s-%d" % (str(uuid.uuid1()), cont) system.setValue("disk." + str(cont) + ".device", source) # if the name of the source starts with / we assume it is a bind, so do not create a volume if not source.startswith("/"): driver = system.getValue("disk." + str(cont) + ".fstype") if not driver: driver = "local" resp = self.create_request('GET', "/volumes/%s" % source, auth_data, headers) if resp.status_code == 200: # the volume already exists self.log_info("Volume named %s already exists." % source) else: body = json.dumps({"Name": source, "Driver": driver}) resp = self.create_request('POST', "/volumes/create", auth_data, headers, body) if resp.status_code != 201: self.log_error("Error creating volume %s: %s." % (source, resp.text)) else: system.setValue("disk." + str(cont) + ".created", "yes") self.log_info("Volume %s successfully created." % source) cont += 1
Example #29
Source File: wray.py From scripts with MIT License | 5 votes |
def set_uuid(config): config[u"inbound"][u"settings"][u"clients"][0][u"id"] = str(uuid.uuid1()) return config
Example #30
Source File: pipeline.py From browserscope with Apache License 2.0 | 5 votes |
def __init__(self, name=None, slot_key=None, strict=False): """Initializer. Args: name: The name of this slot. slot_key: The db.Key for this slot's _SlotRecord if it's already been allocated by an up-stream pipeline. strict: If this Slot was created as an output of a strictly defined pipeline. """ if name is None: raise UnexpectedPipelineError('Slot with key "%s" missing a name.' % slot_key) if slot_key is None: slot_key = db.Key.from_path(_SlotRecord.kind(), uuid.uuid1().hex) self._exists = _TEST_MODE else: self._exists = True self._touched = False self._strict = strict self.name = name self.key = slot_key self.filled = False self._filler_pipeline_key = None self._fill_datetime = None self._value = None