Python shortuuid.uuid() Examples
The following are 30
code examples of shortuuid.uuid().
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
shortuuid
, or try the search function
.
Example #1
Source File: exec_sql_optimization.py From codo-task with GNU General Public License v3.0 | 6 votes |
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
Example #2
Source File: cache.py From ops_sdk with GNU General Public License v3.0 | 6 votes |
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())
Example #3
Source File: app.py From synse-server with GNU General Public License v3.0 | 6 votes |
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, )
Example #4
Source File: question.py From question with BSD 2-Clause "Simplified" License | 6 votes |
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"]))
Example #5
Source File: question.py From question with BSD 2-Clause "Simplified" License | 6 votes |
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")
Example #6
Source File: log_openness.py From impactstory-tng with MIT License | 6 votes |
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
Example #7
Source File: __init__.py From Flask-Store with MIT License | 6 votes |
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
Example #8
Source File: exec_sqladvisor.py From codo-check with GNU General Public License v3.0 | 6 votes |
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
Example #9
Source File: tab.py From crestify with BSD 3-Clause "New" or "Revised" License | 6 votes |
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()
Example #10
Source File: cache.py From k8sMG with GNU General Public License v3.0 | 6 votes |
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())
Example #11
Source File: decaf_views.py From CloudCV-Old with MIT License | 6 votes |
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
Example #12
Source File: deploy.py From dynamodb-continuous-backup with Apache License 2.0 | 6 votes |
def create_lambda_cwe_target(lambda_arn): existing_targets = cwe_client.list_targets_by_rule( Rule=DDB_CREATE_DELETE_RULE_NAME ) if 'Targets' not in existing_targets or len(existing_targets['Targets']) == 0: cwe_client.put_targets( Rule=DDB_CREATE_DELETE_RULE_NAME, Targets=[ { 'Id': shortuuid.uuid(), 'Arn': lambda_arn } ] ) print "Created CloudWatchEvents Target for Rule %s" % (DDB_CREATE_DELETE_RULE_NAME) else: print "Existing CloudWatchEvents Rule has correct Target Function"
Example #13
Source File: test_amqp.py From aio-pika with Apache License 2.0 | 6 votes |
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()
Example #14
Source File: test_amqp.py From aio-pika with Apache License 2.0 | 6 votes |
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, )
Example #15
Source File: test_amqp.py From aio-pika with Apache License 2.0 | 6 votes |
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()
Example #16
Source File: decaf_views.py From CloudCV-Old with MIT License | 6 votes |
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
Example #17
Source File: web_logs.py From k8sMG with GNU General Public License v3.0 | 5 votes |
def write_log(self, log_level, log_message): ###创建一个logger ###创建一个logger if self.progress_id == '': Logger().progress_id = str(uuid()) else: Logger().progress_id = self.progress_id logger = logging.getLogger(self.__log_key) logger.addFilter(ProgressLogFilter()) logger.setLevel(logging.DEBUG) ###建立日志目录 log_dir = os.path.dirname(self.log_file) if not os.path.isdir(log_dir): os.makedirs(log_dir) ###创建一个handler用于写入日志文件 fh = logging.FileHandler(self.log_file) fh.setLevel(logging.DEBUG) ###定义handler的输出格式 formatter = logging.Formatter(log_fmt) fh.setFormatter(formatter) ###给logger添加handler logger.addHandler(fh) ###记录日志 level_dic = {'debug': logger.debug, 'info': logger.info, 'warning': logger.warning, 'error': logger.error, 'critical': logger.critical} level_dic[log_level](log_message) ###删除重复记录 fh.flush() logger.removeHandler(fh)
Example #18
Source File: product.py From impactstory-tng with MIT License | 5 votes |
def __init__(self, **kwargs): self.id = shortuuid.uuid()[0:10] self.created = datetime.datetime.utcnow().isoformat() super(Product, self).__init__(**kwargs)
Example #19
Source File: badge.py From impactstory-tng with MIT License | 5 votes |
def __init__(self, assigned=True, **kwargs): self.id = shortuuid.uuid()[0:10] self.created = datetime.datetime.utcnow().isoformat() self.assigned = assigned self.products = {} super(Badge, self).__init__(**kwargs)
Example #20
Source File: models.py From bridge-adaptivity with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _add_suffix(self): """ Add suffix to the SequenceItem if activity repetition is allowed. """ if self.suffix: return self.suffix = hashlib.sha1(shortuuid.uuid().encode('utf-8')).hexdigest()[::4] # Return 10 character uuid suffix
Example #21
Source File: utils.py From bridge-adaptivity with BSD 3-Clause "New" or "Revised" License | 5 votes |
def short_token(): """Generate a hash that can be used as lti consumer key.""" hash = hashlib.sha1(shortuuid.uuid().encode('utf-8')) hash.update(settings.SECRET_KEY.encode('utf-8')) return hash.hexdigest()[::2]
Example #22
Source File: web_logs.py From k8sMG with GNU General Public License v3.0 | 5 votes |
def read_log(self, log_level, log_message): ###创建一个logger if self.progress_id == '': Logger().progress_id = str(uuid()) else: Logger().progress_id = self.progress_id logger = logging.getLogger(self.__log_key) logger.addFilter(ProgressLogFilter()) logger.setLevel(logging.DEBUG) ###创建一个handler用于输出到终端 th = logging.StreamHandler() th.setLevel(logging.DEBUG) ###定义handler的输出格式 formatter = logging.Formatter(log_fmt) th.setFormatter(formatter) ###给logger添加handler logger.addHandler(th) ###记录日志 level_dic = {'debug': logger.debug, 'info': logger.info, 'warning': logger.warning, 'error': logger.error, 'critical': logger.critical} level_dic[log_level](log_message) th.flush() logger.removeHandler(th)
Example #23
Source File: base_handler.py From k8sMG with GNU General Public License v3.0 | 5 votes |
def __init__(self, *args, **kwargs): self.new_csrf_key = str(shortuuid.uuid()) super(BaseHandler, self).__init__(*args, **kwargs)
Example #24
Source File: person.py From impactstory-tng with MIT License | 5 votes |
def make_temporary_person_from_orcid(orcid_id): my_person = Person() my_person.id = "u_is{}".format(shortuuid.uuid()[0:5]) my_person.created = datetime.datetime.utcnow() print u"starting make_temporary_person_from_orcid: made new person for {}".format(my_person) my_person.orcid_id = orcid_id my_person.refresh() print u"finished make_temporary_person_from_orcid: made new person for {}".format(my_person) return my_person
Example #25
Source File: test_amqp_robust_proxy.py From aio-pika with Apache License 2.0 | 5 votes |
def test_context_process_abrupt_channel_close( connection: aio_pika.RobustConnection, declare_exchange: Callable, declare_queue: Callable, ): # https://github.com/mosquito/aio-pika/issues/302 queue_name = get_random_name("test_connection") routing_key = get_random_name("rounting_key") channel = await connection.channel() exchange = await declare_exchange( "direct", auto_delete=True, channel=channel, ) queue = await declare_queue(queue_name, auto_delete=True, channel=channel) await queue.bind(exchange, routing_key) body = bytes(shortuuid.uuid(), "utf-8") await exchange.publish( Message(body, content_type="text/plain", headers={"foo": "bar"}), routing_key, ) incoming_message = await queue.get(timeout=5) # close aiormq channel to emulate abrupt connection/channel close await channel.channel.close() with pytest.raises(aiormq.exceptions.ChannelInvalidStateError): async with incoming_message.process(): # emulate some activity on closed channel await channel.channel.basic_publish( "dummy", exchange="", routing_key="non_existent", ) # emulate connection/channel restoration of connect_robust await channel.reopen() # cleanup queue incoming_message = await queue.get(timeout=5) async with incoming_message.process(): pass await queue.unbind(exchange, routing_key)
Example #26
Source File: test_amqp.py From aio-pika with Apache License 2.0 | 5 votes |
def test_wrong_credentials( self, connection_fabric: Callable, amqp_url ): amqp_url = amqp_url.with_user(uuid.uuid4().hex).with_password( uuid.uuid4().hex, ) with pytest.raises(ProbableAuthenticationError): await connection_fabric(amqp_url)
Example #27
Source File: test_amqp.py From aio-pika with Apache License 2.0 | 5 votes |
def test_consuming( self, loop, channel: aio_pika.Channel, declare_exchange: Callable, declare_queue: Callable, add_cleanup: Callable, ): queue_name = get_random_name("tc2") routing_key = get_random_name() exchange = await declare_exchange("direct", auto_delete=True) queue = await declare_queue(queue_name, auto_delete=True) await queue.bind(exchange, routing_key) add_cleanup(queue.unbind, exchange, routing_key) body = bytes(shortuuid.uuid(), "utf-8") f = loop.create_future() async def handle(message): message.ack() assert message.body == body assert message.routing_key == routing_key f.set_result(True) await queue.consume(handle) await exchange.publish( Message(body, content_type="text/plain", headers={"foo": "bar"}), routing_key, ) if not f.done(): await f
Example #28
Source File: test_amqp.py From aio-pika with Apache License 2.0 | 5 votes |
def test_consuming_not_coroutine( self, loop, channel: aio_pika.Channel, declare_exchange: Callable, declare_queue: Callable, add_cleanup: Callable, ): queue_name = get_random_name("tc2") routing_key = get_random_name() exchange = await declare_exchange("direct", auto_delete=True) queue = await declare_queue(queue_name, auto_delete=True) add_cleanup(queue.unbind, exchange, routing_key) await queue.bind(exchange, routing_key) body = bytes(shortuuid.uuid(), "utf-8") f = loop.create_future() def handle(message): message.ack() assert message.body == body assert message.routing_key == routing_key f.set_result(True) await queue.consume(handle) await exchange.publish( Message(body, content_type="text/plain", headers={"foo": "bar"}), routing_key, ) if not f.done(): await f
Example #29
Source File: test_amqp.py From aio-pika with Apache License 2.0 | 5 votes |
def test_purge_queue( self, declare_queue: Callable, declare_exchange: Callable, channel: aio_pika.Channel, ): queue_name = get_random_name("test_connection4") routing_key = get_random_name() exchange = await declare_exchange("direct", auto_delete=True) queue = await declare_queue(queue_name, auto_delete=True) await queue.bind(exchange, routing_key) try: body = bytes(shortuuid.uuid(), "utf-8") await exchange.publish( Message( body, content_type="text/plain", headers={"foo": "bar"}, ), routing_key, ) await queue.purge() with pytest.raises(asyncio.TimeoutError): await queue.get(timeout=1) except aio_pika.exceptions.QueueEmpty: await queue.unbind(exchange, routing_key) await queue.delete()
Example #30
Source File: test_message.py From aio-pika with Apache License 2.0 | 5 votes |
def test_message_info(): body = bytes(shortuuid.uuid(), "utf-8") info = { "headers": {"foo": b"bar"}, "content_type": "application/json", "content_encoding": "text", "delivery_mode": DeliveryMode.PERSISTENT.value, "priority": 0, "correlation_id": "1", "reply_to": "test", "expiration": 1.5, "message_id": shortuuid.uuid(), "timestamp": datetime.utcfromtimestamp(int(time.time())), "type": "0", "user_id": "guest", "app_id": "test", "body_size": len(body), } msg = Message( body=body, headers={"foo": b"bar"}, content_type="application/json", content_encoding="text", delivery_mode=DeliveryMode.PERSISTENT, priority=0, correlation_id=1, reply_to="test", expiration=1.5, message_id=info["message_id"], timestamp=info["timestamp"], type="0", user_id="guest", app_id="test", ) assert info == msg.info()