本文整理汇总了Python中uuid.uuid1方法的典型用法代码示例。如果您正苦于以下问题:Python uuid.uuid1方法的具体用法?Python uuid.uuid1怎么用?Python uuid.uuid1使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类uuid
的用法示例。
在下文中一共展示了uuid.uuid1方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: upload
# 需要导入模块: import uuid [as 别名]
# 或者: from uuid import uuid1 [as 别名]
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
示例2: infer
# 需要导入模块: import uuid [as 别名]
# 或者: from uuid import uuid1 [as 别名]
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
示例3: add_point
# 需要导入模块: import uuid [as 别名]
# 或者: from uuid import uuid1 [as 别名]
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
示例4: __init__
# 需要导入模块: import uuid [as 别名]
# 或者: from uuid import uuid1 [as 别名]
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
示例5: collect
# 需要导入模块: import uuid [as 别名]
# 或者: from uuid import uuid1 [as 别名]
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())
示例6: release
# 需要导入模块: import uuid [as 别名]
# 或者: from uuid import uuid1 [as 别名]
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
示例7: test_pass_resource_responses_through
# 需要导入模块: import uuid [as 别名]
# 或者: from uuid import uuid1 [as 别名]
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"
)
示例8: begin_dialog
# 需要导入模块: import uuid [as 别名]
# 或者: from uuid import uuid1 [as 别名]
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)
示例9: __init__
# 需要导入模块: import uuid [as 别名]
# 或者: from uuid import uuid1 [as 别名]
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'")
示例10: _get_pipe_name
# 需要导入模块: import uuid [as 别名]
# 或者: from uuid import uuid1 [as 别名]
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
示例11: execute_sql
# 需要导入模块: import uuid [as 别名]
# 或者: from uuid import uuid1 [as 别名]
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
示例12: test_graph_validation_of_invalid_ontology_class
# 需要导入模块: import uuid [as 别名]
# 或者: from uuid import uuid1 [as 别名]
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)
示例13: get_credentials_path
# 需要导入模块: import uuid [as 别名]
# 或者: from uuid import uuid1 [as 别名]
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
示例14: start_test
# 需要导入模块: import uuid [as 别名]
# 或者: from uuid import uuid1 [as 别名]
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.
示例15: __init__
# 需要导入模块: import uuid [as 别名]
# 或者: from uuid import uuid1 [as 别名]
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