代码之家  ›  专栏  ›  技术社区  ›  William Wino

如何在python中将base64编码的字符串转换为不带磁盘i/o的文件(用于http请求)

  •  0
  • William Wino  · 技术社区  · 8 年前

    我想通过python中的请求库发送一个文件,它接受 file 类型输入。这是我自己测试过的一段工作代码。

    FILES = []
    f = open('/home/dummy.txt', 'rb')
    # f : <type 'file'>
    FILES.append(('file', f))
    response = requests.post(url = 'https://dummy.com/dummy', headers = {'some_header':'content'}, data={'some_payload':'content'}, files=FILES)
    

    这很好,现在我有一个base64编码的字符串,我刚从数据库中得到

    base64_string = "Q3VyaW91cywgYXJlbid0IHlvdT8="
    FILES = []
    f = convert_base64_to_file(base64_string, "dummy.txt")
    # f : <type 'file'>
    FILES.append(('file', f))
    response = requests.post(url = 'https://dummy.com/dummy', headers = {'some_header':'content'}, data={'some_payload':'content'}, files=FILES)
    

    我需要 convert_base64_to_file (这是一种想象的方法)。如何在没有任何磁盘I/O的情况下实现这一点?

    我的 base64_string 没有文件名。如何模拟文件名,使其行为与从磁盘打开文件一样?

    我需要http请求来发布此消息:

    ------WebKitFormBoundary7MA4YWxkTrZu0gW
    Content-Disposition: form-data; name="file"; filename="dummy.txt"
    Content-Type: application/x-object
    
    ... contents of file goes here ...
    

    这就是为什么我需要指定文件名。

    2 回复  |  直到 8 年前
        1
  •  1
  •   MegaIng Mischa Lisovyi    8 年前

    你可以使用 io module :

    import io
    FILES = {}
    f = io.BytesIO()
    FILES{'file'] = ("dummy.txt", f)
    response = requests.post(url = 'https://dummy.com/dummy', headers = {'some_header':'content'}, data={'some_payload':'content'}, files=FILES)
    

    这里是 convert_base64_to_file 功能:

    import base64
    import io
    def convert_base64_to_file(data):
        return io.BytesIO(base64.b64decode(data))
    
        2
  •  0
  •   William Wino    8 年前

    要完成解决我一半问题的megalng答案,我们可以通过执行以下操作向构造的文件添加一个名称:

    import base64
    import io
    def convert_base64_to_file(base64_string,filename):
        f = io.BytesIO(base64.b64decode(base64_string))
        f.name = filename
        return f