【发布时间】:2011-02-27 12:27:01
【问题描述】:
我正在编写一个需要将用户提供的输入转换为文件名的 IRC 和 XMPP 机器人。我已经写了一个函数来做到这一点。够理智吗?
代码如下:
allowednamechars = string.ascii_letters + string.digits + '_+/$.-'
def stripname(name, allowed=""):
""" strip all not allowed chars from name. """
n = name.replace(os.sep, '+')
n = n.replace("@", '+')
n = n.replace("#", '-')
n = n.replace("!", '.')
res = u""
for c in n:
if ord(c) < 31: continue
elif c in allowednamechars + allowed: res += c
else: res += "-" + str(ord(c))
return res
这是一个白名单,带有额外的代码来删除控制字符并替换 os.sep,以及一些替换以使文件名 Google App Engine 兼容。
有问题的机器人位于http://jsonbot.googlecode.com。
那你怎么看?
【问题讨论】:
-
如果用户将
../../../../fubar作为文件名会发生什么?确保始终保存到正确的目录。另外,如果文件已经存在怎么办? -
特别是在 Windows 上,
os.sep是 \,但 / 也可以用作分隔符。 -
您能解释一下转换的意义何在吗?你需要独特性吗?可回收性?在您的代码中可能存在冲突,您是否要避免它们尚不清楚。
-
我知道这个字符串 concat 的比较,我会用它来让机器人使用更少的内存,因为它使用了很多字符串;] 现在我专注于让它保存..
-
我不知道/也曾在 Windows 上用作分隔符,我会考虑到这一点;]
标签: python xmpp user-input filenames irc