本文整理汇总了Python中shortuuid.uuid函数的典型用法代码示例。如果您正苦于以下问题:Python uuid函数的具体用法?Python uuid怎么用?Python uuid使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了uuid函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: registerToken
def registerToken(requester, service, data, androidID = None):
uuid = shortuuid.uuid()
database = connection.safeguard
userData = database.userData
#delete old token
#print data
#print 'service', service
#print 'requester', requester
#print "data", "{'id':" ,data["id"] ,"}}"
query = {'service': service, 'requester': requester,"data.id": data["id"], "data.androidid" : androidID}
userData.remove(query)
while list(userData.find({'token': uuid}).limit(1)):
uuid = shortuuid.uuid()
if androidID:
data["androidid"] = androidID
userData.insert({"token":uuid, "service" : service, 'requester': requester,"data" : data})
return uuid
开发者ID:CCardosoDev,项目名称:Safeguard,代码行数:25,代码来源:databaseLayer.py
示例2: run
def run(**kwargs):
parser = OptionParser(usage="Usage: %prog [options]")
parser.add_option("-v", "--verbose", action="store_true", dest="verbose", default=False, help="make lots of noise")
parser.add_option("--logging", dest="logging", default='info', help="Logging level")
parser.add_option("-H", "--host", dest="host", default='localhost', help="RabbitMQ host")
parser.add_option("-P", "--port", dest="port", default=5672, type=int, help="RabbitMQ port")
(options, args) = parser.parse_args()
logging.basicConfig(
format=u'[%(asctime)s] %(filename)s:%(lineno)d %(levelname)-6s %(message)s',
level=getattr(logging, options.logging.upper(), logging.INFO)
)
Listener(
port=options.port,
host=options.host,
handlers=context.handlers,
context=Context(
options=options,
node_uuid=uuid(getfqdn()),
uuid=uuid(),
**kwargs
)
).loop()
开发者ID:drozdovsky,项目名称:crew,代码行数:25,代码来源:run.py
示例3: create_slug
def create_slug(self, model_instance, add):
# get fields to populate from and slug field to set
if not isinstance(self._populate_from, (list, tuple)):
self._populate_from = (self._populate_from, )
slug_field = model_instance._meta.get_field(self.attname)
if add or self.overwrite:
# slugify the original field content and set next step to 2
slug_for_field = lambda field: self.slugify_func(getattr(model_instance, field))
slug = self.separator.join(map(slug_for_field, self._populate_from))
#next = 2
next = shortuuid.uuid() # universal unique
next = next[:7] # not universal, but probability of collision is still very low
else:
# get slug from the current model instance
slug = getattr(model_instance, self.attname)
# model_instance is being modified, and overwrite is False,
# so instead of doing anything, just return the current slug
return slug
# strip slug depending on max_length attribute of the slug field
# and clean-up
slug_len = slug_field.max_length
if slug_len:
slug = slug[:slug_len]
slug = self._slug_strip(slug)
original_slug = slug
if self.allow_duplicates:
return slug
# exclude the current model instance from the queryset used in finding
# the next valid slug
queryset = self.get_queryset(model_instance.__class__, slug_field)
if model_instance.pk:
queryset = queryset.exclude(pk=model_instance.pk)
# form a kwarg dict used to impliment any unique_together contraints
kwargs = {}
for params in model_instance._meta.unique_together:
if self.attname in params:
for param in params:
kwargs[param] = getattr(model_instance, param, None)
kwargs[self.attname] = slug
# increases the number while searching for the next valid slug
# depending on the given slug, clean-up
while not slug or queryset.filter(**kwargs):
slug = original_slug
end = '%s%s' % (self.separator, next)
end_len = len(end)
if slug_len and len(slug) + end_len > slug_len:
slug = slug[:slug_len - end_len]
slug = self._slug_strip(slug)
slug = '%s%s' % (slug, end)
kwargs[self.attname] = slug
next = shortuuid.uuid() # universal unique
next = next[:7] # not universal, but probability of collision is still very low
return slug
开发者ID:clabra,项目名称:django-extensions,代码行数:59,代码来源:__init__.py
示例4: forwards_func
def forwards_func(apps, schema_editor):
ClowderUser = apps.get_model("clowder_account", "ClowderUser")
db_alias = schema_editor.connection.alias
users = ClowderUser.objects.all()
for user in users:
user.public_key = shortuuid.uuid()
user.secret_key = shortuuid.uuid()
user.save()
开发者ID:nkabir,项目名称:clowder_server,代码行数:8,代码来源:0002_auto_20150224_1853.py
示例5: generate_data
def generate_data(key):
return {
"model": "bookmark.%s" % key,
"pk": shortuuid.uuid(),
"fields": {
"%s" % key: shortuuid.uuid()
}
}
开发者ID:mkouhei,项目名称:shiori,代码行数:8,代码来源:generate_data.py
示例6: generate_data
def generate_data(key):
"""generate data."""
return {
"model": "nenga.%s" % key,
"pk": shortuuid.uuid(),
"fields": {
"%s" % key: shortuuid.uuid()
}
}
开发者ID:mkouhei,项目名称:nenga,代码行数:9,代码来源:generate_data.py
示例7: setUp
def setUp(self):
self.required_fields = getattr(User, 'REQUIRED_FIELDS', [])
self.required_fields.append(
getattr(User, 'USERNAME_FIELD', 'username'))
if 'username' in self.required_fields:
self.inviter = User.objects.create(username=uuid())
self.existing = User.objects.create(
email='[email protected]', username=uuid())
else:
self.inviter = User.objects.create()
self.existing = User.objects.create(email='[email protected]')
开发者ID:laginha,项目名称:django-inviter2,代码行数:11,代码来源:tests.py
示例8: crawling_history
def crawling_history(feed_id):
return {
"model": "bookmark.crawling_history",
"pk": shortuuid.uuid(),
"fields": {
"id": shortuuid.uuid(),
"feed": feed_id,
"update_datetime": datetime.now().strftime(
"%Y-%m-%dT%H:%M:%S+00:00")
}
}
开发者ID:mkouhei,项目名称:shiori,代码行数:11,代码来源:generate_data.py
示例9: feed_subscription
def feed_subscription(owner_id, category_id):
return {
"model": "bookmark.feed_subscription",
"pk": shortuuid.uuid(),
"fields": {
"url": "http://%s.example.org/%s" % (shortuuid.uuid()[:4],
shortuuid.uuid()),
"name": shortuuid.uuid(),
"owner": owner_id,
"default_category": category_id
}
}
开发者ID:mkouhei,项目名称:shiori,代码行数:12,代码来源:generate_data.py
示例10: main
def main():
parser = OptionParser()
parser.add_option("-s", "--service-registry",
dest="registry_nodes",
default=os.getenv('GILLIAM_SERVICE_REGISTRY', ''),
help="service registry nodes", metavar="HOSTS")
parser.add_option('--name', dest="name")
parser.add_option("-p", "--port", dest="port", type=int,
help="listen port", metavar="PORT", default=9000)
parser.add_option('--host', dest="host", default=None,
help="public hostname", metavar="HOST")
(options, args) = parser.parse_args()
assert options.host, "must specify host with --host"
# logging
format = '%(levelname)-8s %(name)s: %(message)s'
logging.basicConfig(level=logging.INFO, format=format)
formation = os.getenv('GILLIAM_FORMATION', 'executor')
service = os.getenv('GILLIAM_SERVICE', 'api')
instance = options.name or shortuuid.uuid()
clock = Clock()
base_url = os.getenv('DOCKER')
docker = DockerClient(base_url) if base_url else DockerClient()
service_registry_cluster_nodes = options.registry_nodes.split(',')
service_registry = ServiceRegistryClient(
clock, service_registry_cluster_nodes)
cont_runtime = partial(PlatformRuntime, service_registry, options.registry_nodes)
cont_store = ContainerStore(partial(Container, docker, cont_runtime,
service_registry, options.host))
# set-up runtime and store for the one-off containers:
proc_runtime = partial(PlatformRuntime, service_registry, options.registry_nodes,
attach=True)
proc_factory = lambda image, command, env, ports, opts, formation, **kw: Container(
docker, proc_runtime, None, None, image, command, env, ports, opts,
formation, None, shortuuid.uuid(), restart=False, **kw)
proc_store = ContainerStore(proc_factory)
register = partial(service_registry.register, formation, service, instance)
announcement = service_registry.build_announcement(
formation, service, instance, ports={options.port: str(options.port)},
host=options.host)
app = App(clock, cont_store, proc_store, docker, register, announcement)
app.start()
pywsgi.WSGIServer(('', options.port), app.create_api(),
handler_class=WebSocketHandler).serve_forever()
开发者ID:pombredanne,项目名称:executor,代码行数:52,代码来源:script.py
示例11: create_uuid
def create_uuid(self):
if not self.version or self.version == 4:
return shortuuid.uuid()
elif self.version == 1:
return shortuuid.uuid()
elif self.version == 2:
raise UUIDVersionError("UUID version 2 is not supported.")
elif self.version == 3:
raise UUIDVersionError("UUID version 3 is not supported.")
elif self.version == 5:
return shortuuid.uuid(name=self.namespace)
else:
raise UUIDVersionError("UUID version %s is not valid." % self.version)
开发者ID:sjlehtin,项目名称:django-extensions,代码行数:13,代码来源:__init__.py
示例12: generate_bookmark
def generate_bookmark(owner_id, category_id, is_hide):
return {
"model": "bookmark.bookmark",
"pk": shortuuid.uuid(),
"fields": {
"url": "http://%s.example.org/%s" % (shortuuid.uuid()[:4],
shortuuid.uuid()),
"title": shortuuid.uuid(),
"category": category_id,
"description": shortuuid.uuid(),
"owner": owner_id,
"is_hide": is_hide
}
}
开发者ID:mkouhei,项目名称:shiori,代码行数:14,代码来源:generate_data.py
示例13: pre_save
def pre_save(self, model_instance, add):
"""
This is used to ensure that we auto-set values if required.
See CharField.pre_save
"""
value = super(ShortUUIDField, self).pre_save(model_instance, add)
if self.auto and not value:
# Assign a new value for this attribute if required.
if sys.version_info < (3, 0):
value = unicode(shortuuid.uuid())
else:
value = str(shortuuid.uuid())
setattr(model_instance, self.attname, value)
return value
开发者ID:alexhawdon,项目名称:django-shortuuidfield,代码行数:14,代码来源:fields.py
示例14: ics
def ics(request, team_id=None, team_name=None):
if team_id:
this_team = Team.objects.get(id=team_id)
elif team_name:
this_team = Team.objects.get(name=team_name)
home_games = Game.objects.filter(home_team=this_team)
away_games = Game.objects.filter(away_team=this_team)
games = home_games | away_games
games = games.order_by("time", "field")
cal = Calendar()
cal.add('prodid', '-//Breakway Schedules//Soccer Calendars//EN')
cal.add('version', '2.0')
cal.add('X-WR-CALNAME', this_team.name)
cal.add('X-WR-TIMEZONE', 'CST6CDT')
cal.add('X-WR-CALDESC', 'Breakaway Team Schedule')
now_dt = datetime.now()
now_string = "%04d%02d%02dT%02d%02d%02d" % (
now_dt.year,
now_dt.month,
now_dt.day,
now_dt.hour,
now_dt.minute,
now_dt.second
)
for game in games:
event = Event()
try:
summary = '%s vs. %s' % (game.home_team, game.away_team)
except Exception:
summary = 'Breakaway game'
if game.color_conflict:
desc = 'Color conflict! (%s vs. %s)' % (game.away_team.color, game.home_team.color)
summary += ' (color conflict)'
event.add('description', desc)
event.add('summary', summary)
event.add('dtstart', game.time)
event.add('dtend', game.time + timedelta(hours=1))
event.add('dtstamp', datetime.now())
event.add('location', "BreakAway Field %s" % game.field)
event['uid'] = '%s/%[email protected]' % (now_string, shortuuid.uuid())
event.add('priority', 5)
alarm = Alarm()
alarm.add("TRIGGER;RELATED=START", "-PT{0}M".format('45'))
alarm.add('action', 'display')
alarm.add('description', 'Breakaway game')
event.add_component(alarm)
cal.add_component(event)
return HttpResponse(cal.to_ical(), content_type='text/calendar')
开发者ID:cooperthompson,项目名称:ct-com,代码行数:60,代码来源:views.py
示例15: short_token
def short_token():
"""
Generate a hash that can be used as an application identifier
"""
hash = hashlib.sha1(shortuuid.uuid())
hash.update(settings.SECRET_KEY)
return hash.hexdigest()[::2]
开发者ID:Perkville,项目名称:django-oauth2-provider,代码行数:7,代码来源:utils.py
示例16: long_token
def long_token():
"""
Generate a hash that can be used as an application secret
"""
hash = hashlib.sha1(shortuuid.uuid())
hash.update(settings.SECRET_KEY)
return hash.hexdigest()
开发者ID:Perkville,项目名称:django-oauth2-provider,代码行数:7,代码来源:utils.py
示例17: downloadAndSaveImages
def downloadAndSaveImages(url_list, socketid):
try:
uuid = shortuuid.uuid()
directory = os.path.join(conf.PIC_DIR, str(uuid))
if not os.path.exists(directory):
os.mkdir(directory)
for url in url_list[""]:
try:
log_to_terminal(str(url), socketid)
file = requests.get(url)
file_full_name_raw = basename(urlparse(url).path)
file_name_raw, file_extension = os.path.splitext(file_full_name_raw)
# First parameter is the replacement, second parameter is your input string
file_name = re.sub('[^a-zA-Z0-9]+', '', file_name_raw)
f = open(os.path.join(conf.PIC_DIR, str(uuid) + file_name + file_extension), 'wb')
f.write(file.content)
f.close()
imgFile = Image.open(os.path.join(conf.PIC_DIR, str(uuid) + file_name + file_extension))
size = (500, 500)
imgFile.thumbnail(size, Image.ANTIALIAS)
imgFile.save(os.path.join(conf.PIC_DIR, str(uuid), file_name + file_extension))
log_to_terminal('Saved Image: ' + str(url), socketid)
except Exception as e:
print str(e)
return uuid, directory
except:
print 'Exception' + str(traceback.format_exc())
开发者ID:virajprabhu,项目名称:CloudCV,代码行数:31,代码来源:decaf_views.py
示例18: wrapExpectationsLocal
def wrapExpectationsLocal(cmd):
script = createScript(cmd)
remoteScript = '/tmp/fexpect_'+shortuuid.uuid()
with open(remoteScript, 'w') as filehandle:
filehandle.write(script)
wrappedCmd = 'python '+remoteScript
return wrappedCmd
开发者ID:ilogue,项目名称:fexpect,代码行数:7,代码来源:internals.py
示例19: save_object
def save_object(collection, obj):
"""Save an object ``obj`` to the given ``collection``.
``obj.id`` must be unique across all other existing objects in
the given collection. If ``id`` is not present in the object, a
*UUID* is assigned as the object's ``id``.
Indexes already defined on the ``collection`` are updated after
the object is saved.
Returns the object.
"""
if 'id' not in obj:
obj.id = uuid()
id = obj.id
path = object_path(collection, id)
temp_path = '%s.temp' % path
with open(temp_path, 'w') as f:
data = _serialize(obj)
f.write(data)
shutil.move(temp_path, path)
if id in _db[collection].cache:
_db[collection].cache[id] = obj
_update_indexes_for_mutated_object(collection, obj)
return obj
开发者ID:fictorial,项目名称:filesysdb,代码行数:25,代码来源:__init__.py
示例20: safe_filename
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
开发者ID:bobosss,项目名称:Flask-Store,代码行数:25,代码来源:__init__.py
注:本文中的shortuuid.uuid函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论