https://pantsbuild.org/ logo
#general
Title
# general
h

handsome-sunset-98068

09/27/2022, 8:15 AM
How to correctly include a non-py (.png) file into the binary, though it correctly works running locally? I am getting this error after deploying on lambda
Copy code
Response
{
  "errorMessage": "[Errno 2] No such file or directory: 'newcamera.png'",
  "errorType": "FileNotFoundError",
  "requestId": "2276ab1d-46e1-4c5f-ad34-18a5f75e3968",
  "stackTrace": [
    "  File \"/var/task/lambdex_handler.py\", line 58, in handler\n    return __RUNNER(*args, **kwargs)\n",
    "  File \"/var/task/test.py\", line 9, in lambda_handler\n    file_length()\n",
    "  File \"/var/task/test.py\", line 2, in file_length\n    with open('newcamera.png', 'rb') as f:\n"
  ]
}
repo link for reference.
1
f

fast-nail-55400

09/27/2022, 8:41 AM
You would use a
resource
target to include the
.png
file.
h

handsome-sunset-98068

09/27/2022, 9:42 AM
Thanks @fast-nail-55400, this worked, but now I am stuck at the original problem. My monorepo has a structure like this.
projects/<proj1>/apps/<app1>/assets/<file.png>
Copy code
$ ./pant roots
.
projects
so while opening the image in
projects/<proj1>/apps/<app1>/helper.py
Copy code
with open("projects/proj1/apps/app1/assets/file.png") as f:
  f.read()
this works fine locally, but breaks on lambda (file not found) - possibly cuz the projects is the root of the repo which not the related to the lambda package. I tried changing in
projects/<proj1>/apps/<app1>/helper.py
to:
Copy code
with open("proj1/apps/app1/assets/file.png") as f:
  f.read()
this works in lambda, but won't work locally. How to set this up so that it works both ways without changing code?
h

happy-kitchen-89482

09/27/2022, 1:52 PM
You probably need to load the file as a resource using pkgutil or similar, rather than using "open".
There are newer apis for this in importlib.resources, assuming you're using Python 3.7 or later
Right now you're assuming that the file has been extracted from the zip, and at a specific location relative to the cwd, and that assumption may not be true in the lambda environment
Resource loading abstracts that away
h

handsome-sunset-98068

09/27/2022, 3:18 PM
This worked. Thanks @happy-kitchen-89482.
h

happy-kitchen-89482

09/27/2022, 5:39 PM
Great!
7 Views