2017-08-17 58 views
1

我編寫了一個非常簡單的python代碼來更新現有的xml文件。現在我必須做同樣的事情,但在AWS S3中。下面是我的代碼,嘗試了一下,沒有運氣。該錯誤首先在xml_tree = ET.parse(xml_file)中找到。任何有經驗的想法..?如何使用python更新AWS S3中的現有xml文件,

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 
+0

這很可能是XML文件不存在。你遇到了什麼錯誤?從S3讀取直接看看[Boto3 S3文檔](http://boto3.readthedocs.io/en/latest/reference/services/s3.html#object) – stdunbar

+0

當我添加打印(xml_file)它打印/var/task/project_detail.xml – David

+0

但是,錯誤消息如下所示; [Errno 2]沒有這樣的文件或目錄:'/var/task/project_detail.xml':IOError Traceback(最近一次調用最後一次): lambda_handler中的第14行文件「/var/task/myFunction.py」 xmltree = ET.parse(xml_file) 文件「/usr/lib64/python2.7/xml/etree/ElementTree.py」,行1182,解析 tree.parse(源文件,解析器) 文件「/ usr/lib64 /python2.7/xml/etree/ElementTree.py「,第647行,解析爲 source = open(source,」rb「) IOError:[Errno 2]沒有這樣的文件或目錄:'/ var/task/project_detail .xml' – David

回答

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 
相關問題