本文整理汇总了Python中utils.is_string函数的典型用法代码示例。如果您正苦于以下问题:Python is_string函数的具体用法?Python is_string怎么用?Python is_string使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了is_string函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: insert_alumno
def insert_alumno(alumno):
try:
if not alumno.username:
raise NameError("Error en el nombre del alumno")
else:
res = Alumno.objects.filter(username=alumno.username)
if res.count() != 0:
raise NameError("El alumno ya existe")
if not alumno.first_name or not utils.is_string(alumno.first_name):
raise NameError("Nombre incorrecto")
if not alumno.last_name or not utils.is_string(alumno.last_name):
raise NameError("Apellidos incorrectos")
# exp reg para saber si el nick corresponde al correo de la ugr (@correo.ugr.es)
if not re.match(r'^[a-z][_a-z0-9]+(@correo\.ugr\.es)$', alumno.username):
raise NameError("El correo no es correcto")
grupo_alumnos = Group.objects.get(name='Alumnos')
alumno.save()
grupo_alumnos.user_set.add(alumno)
return dict(status=True, data=Alumno.objects.get(username=alumno.username))
except NameError as e:
return dict(status=False, message=e.message)
示例2: update
def update(self, usuario, validated_data):
try:
# comprobando email
if 'email' in validated_data.keys():
new_email = validated_data.get('email')
res = Usuario.objects.filter(email=new_email)
if res.count() == 0:
if not utils.is_string(new_email) or not \
re.match(r'^[a-z][_a-z0-9]+(@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,4}))$', new_email):
raise NameError("El email no es correcto")
else:
usuario.email = new_email
else:
raise NameError("El usuario indicado ya existe")
# comprobando dni
if 'dni' in validated_data.keys() and not validated_data.get('creado'):
new_dni = validated_data.get('dni')
res = Usuario.objects.filter(dni=new_dni)
if res.count() == 0:
if not utils.is_string(new_dni) or not \
re.match(r'(\d{8})([-]?)([A-Z]{1})', new_dni):
raise NameError("El dni no es correcto")
else:
usuario.email = new_dni
else:
raise NameError("El usuario indicado ya existe")
# comprobando nombre
if 'first_name' in validated_data.keys():
new_first_name = validated_data.get('first_name')
if new_first_name == '' or not utils.is_string(new_first_name):
raise NameError("Nombre incorrecto")
else:
usuario.first_name = new_first_name
# comprobando apellidos
if 'last_name' in validated_data.keys():
new_last_name = validated_data.get('last_name')
if new_last_name == '' or not utils.is_string(new_last_name):
raise NameError("Nombre incorrecto")
else:
usuario.new_last_name = new_last_name
# if 'password' in validated_data.keys() and 'confirm_password' in validated_data.keys():
# password = validated_data.get('password')
# confirm_password = validated_data.get('confirm_password')
# if password and confirm_password and password == confirm_password:
# alumno.set_password(password)
usuario.save()
if validated_data.get('creado'):
utils.enviar_email_reset_password(usuario.email)
return dict(status=True, data=usuario)
except NameError as e:
return dict(status=False, message=e.message)
except:
return dict(status=False, message="Error en los parametros")
示例3: create_user
def create_user(self, password=None, **kwargs):
try:
if kwargs.get('email'):
# exp reg para saber si el nick corresponde al correo de la ugr (@correo.ugr.es)
if not re.match(r'^[_a-z0-9]+(@correo\.ugr\.es)$', kwargs.get('email')):
raise NameError("El email no es correcto o no pertenece a la UGR")
res = Alumno.objects.filter(email=kwargs.get('email'))
if res.count() != 0:
raise NameError("El alumno ya existe")
if kwargs.get('dni'):
# exp reg para saber si el nick corresponde al correo de la ugr (@correo.ugr.es)
if not re.match(r'(([X-Z]{1})([-]?)(\d{7})([-]?)([A-Z]{1}))|((\d{8})([-]?)([A-Z]{1}))', kwargs.get('dni')):
raise NameError("Error en el DNI del alumno")
if kwargs.get('first_name') and not utils.is_string(kwargs.get('first_name')):
raise NameError("Nombre incorrecto")
if kwargs.get('last_name') and not utils.is_string(kwargs.get('last_name')):
raise NameError("Apellidos incorrectos")
usuario = self.model.objects.create(email=kwargs.get('email'), dni=kwargs.get('dni'),
first_name=kwargs.get('first_name'), last_name=kwargs.get('last_name'))
grupo_alumnos = Grupos.objects.get(name='Alumnos')
usuario.set_password(password)
usuario.save()
grupo_alumnos.user_set.add(usuario)
if usuario.email:
utils.enviar_email_reset_password(usuario.email)
return dict(status=True, data=usuario)
except NameError as e:
return dict(status=False, message=e.message)
示例4: insert_profesor
def insert_profesor(profesor):
try:
if not profesor.username or not (re.match(r'^[a-z][_a-z0-9]+(@ugr\.es)$', profesor.username)):
raise NameError("El correo no es correcto")
else:
res = Profesor.objects.filter(username=profesor.username)
if res.count() != 0:
raise NameError("El profesor ya existe")
if not profesor.first_name or not utils.is_string(profesor.first_name):
raise NameError("Error en el nombre del profesor")
if not profesor.last_name or not utils.is_string(profesor.last_name):
raise NameError("Error en los apellidos del profesor")
if not profesor.departamento or not utils.is_string(profesor.departamento):
raise NameError("Error en el departamento")
grupo_profesores = Group.objects.get(name='Profesores')
profesor.save()
grupo_profesores.user_set.add(profesor)
return dict(status=True, data=Profesor.objects.get(username=profesor.username))
except NameError as e:
return dict(status=False, message=e.message)
示例5: popstack
def popstack(stack, oq):
tok = stack.pop()
if tok in unary:
a = oq.pop()
oq.append(astnode([tok, a]))
elif tok in precedence and tok != ',':
a, b = oq.pop(), oq.pop()
oq.append(astnode([tok, b, a]))
elif tok in closers:
if openers[opener_stack[-1]] != tok:
raise Exception('Did not close with same kind as opened with!',
tok, 'vs', openers[opener_stack[-1]])
opener_stack.pop()
args = []
while not utils.is_string(oq[-1]) or oq[-1] not in openers:
args.insert(0, oq.pop())
lbrack = oq.pop()
if tok == ']' and args[0] != 'id':
oq.append(astnode(['access'] + args))
elif tok == ']':
oq.append(astnode(['array_lit'] + args[1:]))
elif tok == ')' and len(args) and args[0] != 'id':
if utils.is_string(args[0]):
oq.append(astnode(args))
else:
oq.append(astnode(args, *args[0].metadata))
else:
oq.append(args[1])
示例6: enc
def enc(n):
if utils.is_numeric(n):
return ''.join(map(chr, utils.tobytearr(n, 32)))
elif utils.is_string(n) and len(n) == 40:
return '\x00' * 12 + n.decode('hex')
elif utils.is_string(n):
return '\x00' * (32 - len(n)) + n
elif n is True:
return 1
elif n is False or n is None:
return 0
示例7: write_lll_stream
def write_lll_stream(self, stream, ast, n):
if is_string(ast):
write_str(stream, ast)
elif isinstance(ast, astnode):
if is_string(ast.fun):
name = ast.fun.lower()
if name in self.config: # It is a special statement.
c = self.config[name]
if c != 'sexpr': # (Unless config tells us to use s-expressions.)
return self.write_lll_special_stream(stream, ast, name, c, n)
self.write_lll_list_stream(stream, ast.args, '(', ')', ' ', n)
else:
raise Exception('What is', ast, type(ast))
示例8: create_reply
def create_reply(reply, message=None):
if isinstance(reply, WeChatReply):
return reply.render()
elif is_string(reply):
reply = TextReply(message=message, content=reply)
return reply.render()
elif isinstance(reply, list) and all([len(x) == 4 for x in reply]):
if len(reply) > 10:
raise AttributeError("Can't add more than 10 articles"
" in an ArticlesReply")
r = ArticlesReply(message=message)
for article in reply:
article = Article(*article)
r.add_article(article)
return r.render()
elif isinstance(reply, list) and 3 <= len(reply) <= 4:
if len(reply) == 3:
# 如果数组长度为3, 那么高质量音乐链接的网址和普通质量的网址相同。
reply.append(reply[-1])
title, description, url, hq_url = reply
reply = MusicReply(
message=message,
title=title,
description=description,
url=url,
hq_url=hq_url
)
return reply.render()
示例9: _declare_command
def _declare_command (self,
name, callback_function, doc, overwrite, is_pre_flight):
if (not utils.is_string(name)):
raise ValueError(
"Invalid value for magic command name: "
"Must be a string")
if (not utils.is_callable(callback_function)):
raise ValueError(
"Invalid value for magic command callback function: "
"Must be a callable")
if (doc is None):
doc = callback_function.__doc__
if (self.has_command(name) and (not overwrite)):
raise Exception(
"Invalid value for magic command name: "
"Name '%s' already taken" % name)
def _wrapper (doc, mc_args, *args_from_kernel):
if (doc is None):
kwargs = {}
else:
# we parse the arguments using docopt
try:
if (mc_args is None):
mc_args = ''
kwargs = docopt.docopt(doc, mc_args, help = True)
except docopt.DocoptExit as exception:
usage = ' '.join(map(
lambda x: x.strip(), str(exception).splitlines()))
raise Exception("Invalid syntax, %s" % usage)
# we explicitly remove keys without values
for (key, value) in kwargs.items():
if (value is None):
del kwargs[key]
else:
# remove any surrounding quotes
# and whitespaces from the value
kwargs[key] = re.sub(r"^['\"\s]|['\"\s]$", '', value)
_logger.debug(
"executing %s-flight command '%s' "
"(callback function: %s)" % (
"pre" if is_pre_flight else "post",
name.lower(), callback_function))
return callback_function(*args_from_kernel, **kwargs)
self._magic_commands[name.lower()] = (
functools.partial(_wrapper, doc), is_pre_flight)
_logger.debug(
"added %s-flight command '%s' (callback function: %s)" % (
"pre" if is_pre_flight else "post",
name.lower(), callback_function))
示例10: __issue_parse_summary
def __issue_parse_summary(issue, dom):
''' Parse the current comic's summary details from the DOM. '''
# grab the issue description, and do a bunch of modifications and
# replaces to massage it into a nicer "summary" text
# PARAGRAPH = re.compile(r'<br />')
OVERVIEW = re.compile('Overview')
PARAGRAPH = re.compile(r'<[bB][rR] ?/?>|<[Pp] ?>')
NBSP = re.compile(' ?')
MULTISPACES = re.compile(' {2,}')
STRIP_TAGS = re.compile('<.*?>')
LIST_OF_COVERS = re.compile('(?is)list of covers.*$')
if is_string(dom.results.description):
summary_s = OVERVIEW.sub('', dom.results.description)
summary_s = PARAGRAPH.sub('\n', summary_s)
summary_s = STRIP_TAGS.sub('', summary_s)
summary_s = MULTISPACES.sub(' ', summary_s)
summary_s = NBSP.sub(' ' , summary_s)
summary_s = PARAGRAPH.sub('\n', summary_s)
summary_s = summary_s.replace(r'&', '&')
summary_s = summary_s.replace(r'"', '"')
summary_s = summary_s.replace(r'<', '<')
summary_s = summary_s.replace(r'>', '>')
summary_s = LIST_OF_COVERS.sub('', summary_s);
issue.summary_s = summary_s.strip()
示例11: serialize_expr
def serialize_expr(ast, open='(', close=')', between=', ', precscore=-1):
if is_string(ast):
return ast
elif type(ast) is list:
if len(ast) > 0:
ret = open + serialize_expr(ast[0])
for el in ast[1:]:
ret += between + serialize_expr(el, open, close, between)
return ret + close
else:
return open + close
assert isinstance(ast, astnode)
if ast.fun in precedence:
between = ast.fun if (ast.fun in dont_space_it) else ' ' + ast.fun + ' '
open, close = ('', '') if precscore < precedence[ast.fun] else ('(',')')
return serialize_expr(ast.args[1:], open, close, between, precedence[ast.fun])
elif ast.fun == 'access': # TODO do this fancier.
return serialize_expr(ast[1]) + '[' + serialize_expr(ast[2]) + ']'
elif ast.fun == 'array_lit':
return serialize_expr(ast.args[1:], '[', ']')
elif ast.fun == 'str':
assert len(ast) == 2
return '"' + ast[1] + '"'
else:
return ast.fun + serialize_expr(ast.args[1:])
示例12: analyze
def analyze(ast):
if utils.is_string(ast):
ast = parse(ast)
ast = rewrite(preprocess(ast))
data = {"varhash": {}, "inner": []}
analyze_and_varify_ast(ast, data)
return data
示例13: __issue_parse_series_details
def __issue_parse_series_details(issue, dom):
""" Parses the current comic's series details out of the DOM """
series_id = dom.results.volume.id
# if the start year and publisher_s have been cached (because we already
# accessed them once this session) use the cached values. else
# grab those values from comicvine, and cache em so we don't have to
# hit comic vine for them again (at least not in this session)
global __series_details_cache
if __series_details_cache == None:
raise Exception(__name__ + " module isn't initialized!")
cache = __series_details_cache
if series_id in cache:
volume_year_n = cache[series_id][0]
publisher_s = cache[series_id][1]
else:
# contact comicvine to extract details for this comic book
series_dom = cvconnection._query_series_details_dom(__api_key, series_id)
if series_dom is None:
raise Exception("can't get details about series " + series_id)
# start year
volume_year_n = -1
if "start_year" in series_dom.results.__dict__ and is_string(series_dom.results.start_year):
try:
volume_year_n = int(series_dom.results.start_year)
except:
pass # bad start year format...just keep going
# publisher
publisher_s = ""
if (
"publisher" in series_dom.results.__dict__
and "name" in series_dom.results.publisher.__dict__
and is_string(series_dom.results.publisher.name)
):
publisher_s = series_dom.results.publisher.name
cache[series_id] = (volume_year_n, publisher_s)
# check if there's the current publisher really is the true publisher, or
# if it's really an imprint of another publisher.
issue.publisher_s = cvimprints.find_parent_publisher(publisher_s)
if issue.publisher_s != publisher_s:
issue.imprint_s = publisher_s
issue.volume_year_n = volume_year_n
示例14: notify
def notify(title, description, icon):
if icon and not is_string(icon):
icon = growl_raw_image(icon)
growler.notify(noteType="Now Playing",
title=title,
description=description,
icon=icon)
示例15: __parse_image_url
def __parse_image_url(dom):
""" Grab the image for this issue out of the given DOM fragment. """
imgurl_s = None
if "image" in dom.__dict__:
if "small_url" in dom.image.__dict__ and is_string(dom.image.small_url):
imgurl_s = dom.image.small_url
elif "medium_url" in dom.image.__dict__ and is_string(dom.image.medium_url):
imgurl_s = dom.image.medium_url
elif "large_url" in dom.image.__dict__ and is_string(dom.image.large_url):
imgurl_s = dom.image.large_url
elif "super_url" in dom.image.__dict__ and is_string(dom.image.super_url):
imgurl_s = dom.image.super_url
elif "thumb_url" in dom.image.__dict__ and is_string(dom.image.thumb_url):
imgurl_s = dom.image.thumb_url
return imgurl_s