Skip to content

Instantly share code, notes, and snippets.

@evernotegists
Created April 4, 2013 20:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save evernotegists/5313823 to your computer and use it in GitHub Desktop.
Save evernotegists/5313823 to your computer and use it in GitHub Desktop.
def makeResourceFromFiles(fpaths):
"""
Create a Resource object from the passed file(s) and return it
"""
for fpath in fpaths:
if not os.path.exists(fpath):
print "Path doesn't exist: %s" % fpath
continue
# try to determine the MIME type of the file
mt = mimetypes.guess_type(fpath)
typestr = mt[0]
if typestr.split('/')[0] == "text":
rmode = 'r'
else:
rmode = 'rb'
fdata = open(fpath, rmode).read()
md5 = hashlib.md5()
md5.update(fdata)
hashs = md5.digest()
data = Types.Data()
data.size = len(fdata)
data.bodyHash = hashs
data.body = fdata
resource = Types.Resource()
resource.mime = typestr
resource.data = data
attrs = Types.ResourceAttributes()
attrs.fileName = os.path.basename(fpath)
resource.attributes = attrs
yield resource
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment