【问题标题】:open('file_path').read() - save contents back to fileopen('file_path').read() - 将内容保存回文件
【发布时间】:2013-09-07 23:01:04
【问题描述】:

我需要使用 urllib2 将文件上传到服务器。由于我使用的是 OpenOffice python,因此我无法使用任何外部库(如 requests 和其他库),因此我需要一种简单的方法来发布文件数据。

所以我来了:

post_url = "http://localhost:8000/admin/oo_file_uploader?user_id=%s&file_id=%s" % (user_id, file_id)
file_path = doc.Location.replace('file://', '')
data = urllib.urlencode({"file": open(file_path).read()})
urllib2.urlopen(post_url, data)

将某些内容发布到服务器。

我想知道是否可以使用 python/django 将发布的内容保存回文件?

【问题讨论】:

    标签: python django file


    【解决方案1】:

    这在@zero323 的回答上有所扩展。您需要确保实施某种安全措施,以防止未经授权的用户上传随机文件,这是 @file_upload_security 装饰器隐含的处理方式。

    @file_upload_security
    def oo_file_uploader(user_id=None, file_id=None):
        if request.method == 'POST':
            # Exception handling skipped if get() fails.
            user = User.objects.get(id=user_id)
            save_to_file = MyFiles.objects.get(id=file_id)
    
            # You will probably want to ensure 'file' is in post data.
            file_contents = save_to_file.parse_post_to_content(request.POST['file'])
    
            with open(save_to_file.path_to_file, 'w') as fw:
                fw.write(file_contents)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-30
      • 1970-01-01
      • 2013-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-10
      • 2012-01-18
      相关资源
      最近更新 更多