本文整理汇总了Python中shortuuid.uuid函数的典型用法代码示例。如果您正苦于以下问题:Python uuid函数的具体用法?Python uuid怎么用?Python uuid使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了uuid函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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
示例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()
示例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
示例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()
示例5: generate_data
def generate_data(key):
return {
"model": "bookmark.%s" % key,
"pk": shortuuid.uuid(),
"fields": {
"%s" % key: shortuuid.uuid()
}
}
示例6: generate_data
def generate_data(key):
"""generate data."""
return {
"model": "nenga.%s" % key,
"pk": shortuuid.uuid(),
"fields": {
"%s" % key: shortuuid.uuid()
}
}
示例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]')
示例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")
}
}
示例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
}
}
示例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()
示例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)
示例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
}
}
示例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
示例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')
示例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]