在 Python 中根据用户输入创建保存文件名

发布于 2024-10-19 19:54:07 字数 1010 浏览 7 评论 0原文

我正在编写 IRCXMPP 机器人需要将用户提供的输入转换为文件名。我已经编写了一个函数来执行此操作。够理智吗?

这是代码:

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

那么你觉得怎么样?

I'm programming an IRC and XMPP bot that needs to convert user provided input to a filename. I have already written a function to do this. Is it sane enough?

Here is the code:

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

It's a whitelist with extra code to remove control characters and replace os.sep, as well as some repaces to make the filename Google App Engine compatible.

The bot in question is at http://jsonbot.googlecode.com.

So what do you think of it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

夏九 2024-10-26 19:54:07

urllib.quote(name.encode("utf8")) 将产生人类可读的内容,这也应该是安全的。例子:

In [1]: urllib.quote(u"foo bar$=+:;../..(boo)\u00c5".encode('utf8'))
Out[1]: 'foo%20bar%24%3D%2B%3A%3B../..%28boo%29%C3%85'

urllib.quote(name.encode("utf8")) will produce something human-readable, which should also be safe. Example:

In [1]: urllib.quote(u"foo bar$=+:;../..(boo)\u00c5".encode('utf8'))
Out[1]: 'foo%20bar%24%3D%2B%3A%3B../..%28boo%29%C3%85'
够运 2024-10-26 19:54:07

您可能会考虑只执行base64.urlsafe_b64encode(name),这将始终生成一个安全的名称,除非您确实想要一个人类可读的文件名。否则,边缘情况的数量会相当长,如果你忘记了其中之一,就会遇到安全问题。

You might consider just doing base64.urlsafe_b64encode(name), which will always produce a safe name, unless you really want a human-readable file name. Otherwise, the number of edge cases is pretty long, and if you forget one of them, you've got a security problem.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文