Question

Problems with Python imports in functions

Hi, I’m working with serverless functions and being new to Python having some issues with making my own class imports that work locally also work when deployed to DO.

It could be the way that I am invoking my

packages/joke/joke/___main___.py

file to test it locally.

My file structure matches this example project https://github.com/digitalocean/sample-functions-python-jokes and all my custom classes are in packages/joke/joke alongside the __main__.py file.

I’ve tried both

from packages.joke.joke.persist_email_to_storage import PersistEmailToStorage
from packages.joke.joke.s3_client_exception import S3ClientException

or

from .persist_email_to_storage import PersistEmailToStorage
from .s3_client_exception import S3ClientException

in __main__.py and while either of those works “locally” it does not when deployed.

When I say locally, I’ve created a runlocal.py file in the root directory in attempt to invoke the

__main__.py

file and it does run the code.

import packages.joke.joke.__main__ as fetch_emails

output = fetch_emails.main(args={})
print(output)
print('run local.py complete.')

Is there a better way to emulate how DO would invoke it, where the imports would work in the same way? What would I need to do differently? Thanks


Submit an answer

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Sign In or Sign Up to Answer

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in Q&A, subscribe to topics of interest, and get courses and tools that will help you grow as a developer and scale your project or business.

I created this sample repo https://github.com/rabbah/functions/tree/master/pymod if it’s helpful. Are you relying on any pip installed packages that may be globally installed on your dev environment? Can you share the error you’re encountering?

If there is a third party library (S3 related perhaps?) then you will need a build file to create a Python virtual environment that captures the dependencies similar to what’s done for the jokes sample project.