如何使用python更新AWS S3中的现有xml文件,

时间:2017-08-17 21:50:14

标签: python xml amazon-web-services amazon-s3 lambda

我写了一个非常简单的python代码来更新现有的xml文件。现在我必须在AWS S3中做同样的事情。下面是我的代码,尝试了一下,没有运气。首先在xml_tree = ET.parse(xml_file)中找到该错误。任何有经验的想法..?

import os
import xml.etree.ElementTree as ET
import boto3


s3_resource = boto3.resource('s3')    
bucket = s3.Bucket('3d-app')  


def lambda_handler(event, context):
    #xml_file = 's3://3d-app/updator/project_detail.xml/'  
    xml_file = os.path.realpath("project_detail.xml")

    xmltree = ET.parse(xml_file)

       #print(xmltree) 
    root = xmltree.getroot()

       #print(root)
       #print(root.tag)

    #root_tag = root.find('root')

    project = ET.SubElement(root, "project")
    indexpage_path = ET.SubElement(project, "indexpage_path")
    description = ET.SubElement(project, "description")
    thumbnail_path = ET.SubElement(project, "thumbnail_path")

    indexpage_path.text ="$(new to be added) "
    description.text = "$(new to be added) "
    thumbnail_path.text = "$(new to be added) "

      #print ((indexpage_path), (indexpage_path.text))
      #print((description), (description.text))

    tree = ET.ElementTree(root)
    tree.write(xml_file)
    return 

1 个答案:

答案 0 :(得分:0)

请将XML的生成与AWS S3中的存储分开。

如果XML本地存储在文件中,请使用 set_contents_from_filename()
如果XML存储在字符串中,请使用 set_contents_from_string()

AWS_Region = 'eu-west-1'    # use connect_to_region to avoid 301 error
target_bucket = 'your.bucket.com'
conn = boto.s3.connect_to_region(
        AWS_REGION,
        aws_access_key_id=AWS_ACCESS_KEY_ID,
        aws_secret_access_key=AWS_ACCESS_KEY_SECRET,
        is_secure=True,               # uncomment if you are not using ssl
        calling_format = boto.s3.connection.OrdinaryCallingFormat(),
        )
bucket = conn_s3_r.get_bucket(target_bucket)
k = Key(bucket)
k.key = target_key
#if k.exists(): print "File existing, overwriting anyway: ", target_key
k.set_contents_from_filename(src_file)
k.make_public()   #I use this for static website hosted on AWS S3