L44TXF
L44TXF

Reputation: 95

Zipfile's issue when uploading to AWS Lambda

I am trying to zip my code but specifically two folders, main and pymysql. I am using the below code which creates a folder which seems to be in the correct structure.

import os
import zipfile

def zipit(folders, zip_filename):
    zip_file = zipfile.ZipFile(zip_filename, 'w', zipfile.ZIP_DEFLATED)

    for folder in folders:
        for dirpath, dirnames, filenames in os.walk(folder):
            for filename in filenames:
                zip_file.write(
                    os.path.join(dirpath, filename),
                    os.path.relpath(os.path.join(dirpath, filename), os.path.join(folders[0], '../..')))

    zip_file.close()


folders = [
    "main",
    "pymysql"]

if __name__ == "__main__":
    zipit(folders, "project-lambda-preSignUpTrigger.zip")

When I extract the above file I get something that looks like this (directory 1)

project-lambda-preSignUpTrigger
- main
- pymysql

Which looks correct. However when I upload the zip file to AWS lambda it ends up like this. (directory 2)

project-lambda-preSignUpTrigger
- project-lambda-preSignUpTrigger
-- main
-- pymysql

Now I thought it may be a aws lambda issue, but I corrected the file structure there and exported it as a zip which presented me with a file that was identical to directory 1. I uploaded this zip and it uploaded as I wanted like directory 1. Thus, I believe this is due to how I used zipfiles. Does any one know why?

Upvotes: 0

Views: 463

Answers (1)

hc_dev
hc_dev

Reputation: 9418

What does your resulting zip-file look like, especially the directory structure inside. From your extracted output it seems:

project-lambda-preSignUpTrigger
- main
- pymysql

From AWS lambda I assume it should list the folders "main", etc. (without nesting):

main
pymysql

So you could fix the third argument and go not that far back:

os.path.relpath(os.path.join(dirpath, filename), os.path.join(folders[0], '..')))

Note: I removed the /..

Upvotes: 1

Related Questions