What I’m trying to do:
I am trying to structure my imports so that code can run in the Anvil designer AND also via uplink without needing to make any changes to the code.
I have code in “Server Code” that import a couple modules and packages which also live in “Server Code”. Works fine when I run from the Anvil designer but I get import errors when running via uplink.
What I’ve tried and what’s not working:
As an example, I have server code structured like this:
Server Code
runner.py
mymod.py (contains minimal "calc1()" function)
mypkg\
mymod2.py (contains minimal "calc2()" function)
The runner.py file basically contains:
from . import mymod
from .mypkg import mymod2
@anvil.server.callable
def runtest(x):
a = mymod.calc1(x)
b = mymod2.calc2(x)
This works from the Anvil designer. But when I clone this repo (funcsharing) locally and run via uplink (v 0.6.0 of anvil-uplink), I get the import errors below. I’m running uplink on Windows 10 in a GitBash terminal, which has worked great with other apps.
$ python -m anvil.run_app_via_uplink funcsharing
Importing funcsharing
Importing funcsharing.mymod
Importing funcsharing.mypkg
Importing funcsharing.mymod2
Traceback (most recent call last):
File "<frozen runpy>", line 198, in _run_module_as_main
File "<frozen runpy>", line 88, in _run_code
File "C:\cache\repo\funcsharing\venv\Lib\site-packages\anvil\run_app_via_uplink.py", line 45, in <module>
import_all(server_path, mod.__name__)
File "C:\cache\repo\funcsharing\venv\Lib\site-packages\anvil\run_app_via_uplink.py", line 33, in import_all
import_all(subpkg.__path__, mod.__package__ or mod.__name__)
File "C:\cache\repo\funcsharing\venv\Lib\site-packages\anvil\run_app_via_uplink.py", line 29, in import_all
submod = importlib.import_module(package_name+"."+f[:-3])
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Program Files\Python311\Lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "<frozen importlib._bootstrap>", line 1206, in _gcd_import
File "<frozen importlib._bootstrap>", line 1178, in _find_and_load
File "<frozen importlib._bootstrap>", line 1142, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'funcsharing.mymod2'
I’ve read:
- Doc “How to import things”
- Forum post on “Inconsistency in import”
- Forum post on “documentation on anvil-run-app-via-uplink”
- Forum post on “import difference between server vs uplink”
What is the best practice to follow to get import statements that work in the designer and with uplink?