本文整理汇总了Python中shortuuid.uuid方法的典型用法代码示例。如果您正苦于以下问题:Python shortuuid.uuid方法的具体用法?Python shortuuid.uuid怎么用?Python shortuuid.uuid使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类shortuuid
的用法示例。
在下文中一共展示了shortuuid.uuid方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: save_openness_log
# 需要导入模块: import shortuuid [as 别名]
# 或者: from shortuuid import uuid [as 别名]
def save_openness_log(my_person):
# make a new log
new_openness_log = LogOpenness()
new_openness_log.set_openness_columns(my_person)
# see if we already have a log the same as this. if so, nothing to do, return.
q = LogOpenness.query.filter_by(orcid_id=my_person.orcid_id).order_by(LogOpenness.created.desc())
most_recent_log = q.first()
if most_recent_log:
if new_openness_log.has_same_openness(most_recent_log):
print u"no new openness to log for {}".format(my_person.orcid_id)
return
# nope! is worth logging. finish adding attributes and store in db
new_openness_log.id = shortuuid.uuid()[0:10]
new_openness_log.created = datetime.datetime.utcnow().isoformat()
new_openness_log.orcid_id = my_person.orcid_id
db.session.add(new_openness_log)
commit_success = safe_commit(db)
if not commit_success:
print u"COMMIT fail on new_openness_log {}".format(new_openness_log.orcid_id)
print u"logged new openness for {}".format(my_person.orcid_id)
return
示例2: new
# 需要导入模块: import shortuuid [as 别名]
# 或者: from shortuuid import uuid [as 别名]
def new(user_id, tabs, title):
tabs = json.loads(tabs)
new_tabs = Tab()
new_tabs.user = user_id
new_tabs.id = shortuuid.uuid()
new_tabs.title = title
new_tabs.tabs = tabs
new_tabs.added_on = datetime.datetime.utcnow()
for tab in tabs:
if tab.has_key('title') and tab.has_key('url'): # Each tab MUST have a title and a URL
pass
else:
del new_tabs
return False
db.session.add(new_tabs)
db.session.commit()
示例3: get_conf
# 需要导入模块: import shortuuid [as 别名]
# 或者: from shortuuid import uuid [as 别名]
def get_conf(dbname, db_info):
"""获取SQL配置生产配置文件"""
conf_file = '/tmp/' + uuid() + '.ini'
if len(str(base64.b64decode(db_info)).split(',,,')) < 4:
print('db_info error')
exit(-100)
db_host, db_port, db_user, db_pwd = str(base64.b64decode(db_info), 'utf-8').split(',,,')
if db_pwd == 'null':
db_pwd = ''
with open(conf_file, 'w') as f:
f.write("[sqladvisor]\n"
"username={db_user}\n"
"password={db_pwd}\n"
"host={db_host}\n"
"port={db_port}\n"
"dbname={dbname}\n"
.format(db_user=db_user, db_pwd=db_pwd, db_host=db_host, db_port=db_port, dbname=dbname))
return conf_file, db_host
示例4: safe_filename
# 需要导入模块: import shortuuid [as 别名]
# 或者: from shortuuid import uuid [as 别名]
def safe_filename(self, filename):
""" If the file already exists the file will be renamed to contain a
short url safe UUID. This will avoid overwtites.
Arguments
---------
filename : str
A filename to check if it exists
Returns
-------
str
A safe filenaem to use when writting the file
"""
while self.exists(filename):
dir_name, file_name = os.path.split(filename)
file_root, file_ext = os.path.splitext(file_name)
uuid = shortuuid.uuid()
filename = secure_filename('{0}_{1}{2}'.format(
file_root,
uuid,
file_ext))
return filename
示例5: __init__
# 需要导入模块: import shortuuid [as 别名]
# 或者: from shortuuid import uuid [as 别名]
def __init__(self):
self.__redis_connections = {}
redis_configs = my_configs[const.REDIS_CONFIG_ITEM]
for config_key, redis_config in redis_configs.items():
auth = redis_config[const.RD_AUTH_KEY]
host = redis_config[const.RD_HOST_KEY]
port = redis_config[const.RD_PORT_KEY]
db = redis_config[const.RD_DB_KEY]
return_utf8 = False
if const.RD_DECODE_RESPONSES in redis_config:
return_utf8 = redis_config[const.RD_DECODE_RESPONSES]
password = redis_config[const.RD_PASSWORD_KEY]
if auth:
redis_conn = redis.Redis(host=host, port=port, db=db, password=password, decode_responses=return_utf8)
else:
redis_conn = redis.Redis(host=host, port=port, db=db, decode_responses=return_utf8)
self.__redis_connections[config_key] = redis_conn
self.__salt = str(uuid())
示例6: send_question
# 需要导入模块: import shortuuid [as 别名]
# 或者: from shortuuid import uuid [as 别名]
def send_question(nick):
global USERS
global PENDING
if nick and 'text' in request.args and 'from' in request.args:
if not request.args['from'] in USERS or not USERS.get(request.args['from'], {}).get('verified', False):
reverify(request.args['from'])
return err_resp(error=404, text="Source user not found or not yet verified (verification msg sent if exists)")
if not nick in USERS or not USERS.get(nick, {}).get('verified', False):
return err_resp(error=404, text="Destination user not found or not yet verified")
id = shortuuid.uuid()
PENDING[id] = {'to': nick, 'from': request.args['from'], 'text': request.args['text'], 'ts': time.time()}
first, _f = airgram_send(email=USERS[nick]["email"], msg="Question from {} : No | {}".format(request.args["from"], request.args["text"]), url=URL + "/no/" + id)
second, _s = airgram_send(email=USERS[nick]["email"], msg="Question from {} : Yes | {}".format(request.args["from"], request.args["text"]), url=URL + "/yes/" + id)
if first and second:
return jsonify(status="ok")
elif (first and not second) or (second and not first):
_ = airgram_send(email=USERS[nick]["email"], msg="Oops! Can't send {} message. Please contact {} ASAP.".format("NO" if second else "YES", request.args['from']))
return err_resp(error=504, text="{} message didn't send, please contact {} directly (they may be contacting you also)".format("First" if second else "Second", nick))
else:
return err_resp(error=504, text="Messages could not be sent, please notify blha303 at b3@blha303.com.au and contact {} directly at {}".format(nick, USERS[nick]["email"]))
示例7: add_user
# 需要导入模块: import shortuuid [as 别名]
# 或者: from shortuuid import uuid [as 别名]
def add_user(nick):
global VERIFY
global USERS
if nick and nick in USERS:
return err_resp(error=409, text="Username in use")
if len(nick) > 20:
return err_resp(error=400, text="Username is too long (>20)")
elif 'email' in request.args:
id = shortuuid.uuid()
VERIFY[id] = nick
exists, err = airgram_check(request.args['email'], id)
if exists:
USERS[nick] = {'email': request.args["email"], 'verified': False, 'reg': time.time()}
return jsonify(status="ok")
else:
return err_resp(error=404, text="{} airgramapp.com".format(err))
else:
return err_resp(error=400, text="Invalid or missing email address")
示例8: decafDropbox
# 需要导入模块: import shortuuid [as 别名]
# 或者: from shortuuid import uuid [as 别名]
def decafDropbox(request):
post_dict = parser.parse(request.POST.urlencode())
try:
if 'urls' not in post_dict:
data = {'error': 'NoFileSelected'}
else:
data = {'info': 'ProcessingImages'}
# Download these images. Run Feature Extraction. Post results.
uuid, image_path = downloadAndSaveImages(post_dict['urls'], post_dict['socketid'])
output_path = os.path.join(image_path, 'results')
if not os.path.exists(output_path):
os.makedirs(output_path)
decaf_wrapper_local(image_path, output_path, post_dict['socketid'], os.path.join(conf.PIC_URL, uuid))
log_to_terminal('Processing Images Now', post_dict['socketid'])
response = JSONResponse(data, {}, response_mimetype(request))
response['Content-Disposition'] = 'inline; filename=files.json'
return response
except:
data = {'result': str(traceback.format_exc())}
response = JSONResponse(data, {}, response_mimetype(request))
response['Content-Disposition'] = 'inline; filename=files.json'
return response
示例9: decaf_train
# 需要导入模块: import shortuuid [as 别名]
# 或者: from shortuuid import uuid [as 别名]
def decaf_train(request):
post_dict = parser.parse(request.POST.urlencode())
try:
if 'urls' not in post_dict:
data = {'error': 'NoFileSelected'}
else:
data = {'info': 'ProcessingImages'}
# Download these images. Run Feature Extraction. Post results.
uuid, image_path = downloadAndSaveImages(post_dict['urls'], post_dict['socketid'])
output_path = os.path.join(image_path, 'results')
if not os.path.exists(output_path):
os.makedirs(output_path)
decaf_wrapper_local(image_path, output_path, post_dict['socketid'], os.path.join(conf.PIC_URL, uuid))
log_to_terminal('Processing Images Now', post_dict['socketid'])
response = JSONResponse(data, {}, response_mimetype(request))
response['Content-Disposition'] = 'inline; filename=files.json'
return response
except:
data = {'result': str(traceback.format_exc())}
response = JSONResponse(data, {}, response_mimetype(request))
response['Content-Disposition'] = 'inline; filename=files.json'
return response
示例10: get_conf_v3
# 需要导入模块: import shortuuid [as 别名]
# 或者: from shortuuid import uuid [as 别名]
def get_conf_v3(dbname, db_info):
"""获取SQL配置生产配置文件"""
conf_file = '/tmp/' + uuid() + '.ini'
db_info = base64.b64decode(db_info)
db_info = json.loads(bytes.decode(db_info))
db_host, db_port, db_user, db_pwd = db_info.get('db_host'), db_info.get('3306'), db_info.get(
'db_user'), db_info.get('db_pwd')
with open(conf_file, 'w') as f:
f.write("[sqladvisor]\n"
"username={db_user}\n"
"password={db_pwd}\n"
"host={db_host}\n"
"port={db_port}\n"
"dbname={dbname}\n"
.format(db_user=db_user, db_pwd=db_pwd, db_host=db_host, db_port=db_port, dbname=dbname))
return conf_file, db_host
示例11: __init__
# 需要导入模块: import shortuuid [as 别名]
# 或者: from shortuuid import uuid [as 别名]
def __init__(self):
self.__redis_connections = {}
redis_configs = my_settings['redises']
for config_key, redis_config in redis_configs.items():
auth = redis_config['auth']
host = redis_config['host']
port = redis_config['port']
db = redis_config['db']
return_utf8 = False
if 'decode_responses' in redis_config:
return_utf8 = redis_config['decode_responses']
password = redis_config['password']
if auth:
redis_conn = redis.Redis(host=host,
port=port, db=db,
password=password,
decode_responses=return_utf8)
else:
redis_conn = redis.Redis(host=host, port=port, db=db, decode_responses=return_utf8)
self.__redis_connections[config_key] = redis_conn
self.__salt = str(uuid())
示例12: on_request
# 需要导入模块: import shortuuid [as 别名]
# 或者: from shortuuid import uuid [as 别名]
def on_request(request: Request) -> None:
"""Middleware function that runs prior to processing a request via Sanic."""
# Generate a unique request ID and use it as a field in any logging that
# takes place during the request handling.
req_id = shortuuid.uuid()
request.ctx.uuid = req_id
contextvars.clear_contextvars()
contextvars.bind_contextvars(
request_id=req_id,
)
logger.debug(
'processing HTTP request',
method=request.method,
ip=request.ip,
path=request.path,
headers=dict(request.headers),
args=request.args,
)
示例13: test_message_nack
# 需要导入模块: import shortuuid [as 别名]
# 或者: from shortuuid import uuid [as 别名]
def test_message_nack(
self, channel: aio_pika.Channel, declare_queue
):
queue_name = get_random_name("test_nack_queue")
body = uuid.uuid4().bytes
queue = await declare_queue(queue_name, auto_delete=True)
await channel.default_exchange.publish(
Message(body=body), routing_key=queue_name,
)
message = await queue.get() # type: aio_pika.IncomingMessage
assert message.body == body
message.nack(requeue=True)
message = await queue.get()
assert message.redelivered
assert message.body == body
await message.ack()
示例14: test_on_return_raises
# 需要导入模块: import shortuuid [as 别名]
# 或者: from shortuuid import uuid [as 别名]
def test_on_return_raises(self, connection: aio_pika.Connection):
queue_name = get_random_name("test_on_return_raises")
body = uuid.uuid4().bytes
with pytest.raises(RuntimeError):
await connection.channel(
publisher_confirms=False, on_return_raises=True,
)
channel = await connection.channel(
publisher_confirms=True, on_return_raises=True,
)
for _ in range(100):
with pytest.raises(aio_pika.exceptions.DeliveryError):
await channel.default_exchange.publish(
Message(body=body), routing_key=queue_name,
)
示例15: test_connection_close
# 需要导入模块: import shortuuid [as 别名]
# 或者: from shortuuid import uuid [as 别名]
def test_connection_close(
self, connection: aio_pika.Connection, declare_exchange: Callable
):
routing_key = get_random_name()
channel = await self.create_channel(connection)
exchange = await declare_exchange(
"direct", auto_delete=True, channel=channel,
)
try:
with pytest.raises(aio_pika.exceptions.ChannelPreconditionFailed):
msg = Message(bytes(shortuuid.uuid(), "utf-8"))
msg.delivery_mode = 8
await exchange.publish(msg, routing_key)
channel = await self.create_channel(connection)
exchange = await declare_exchange(
"direct", auto_delete=True, channel=channel,
)
finally:
await exchange.delete()