How to solve Django app name conflict with external library
Question:
I made a big mistake by creating an app inside my Django
project called requests
that happened a long time ago and the system has already been running for years. now I need to use the requests library and it is being imported like import requests
as mentioned in the documentation … and of course whenever I do this import it imports my app instead of the library .. so how to solve this?
Answers:
You can try importing the requests/__init__.py
file directly as shown in docs: https://docs.python.org/3/library/importlib.html#importing-a-source-file-directly.
Example:
import sys
import importlib.util
module_name = 'requests'
# declare the full path to requests/__init__.py file below
module_path = '/path/to/virtualenv/site-packages/requests/__init__.py'
spec = importlib.util.spec_from_file_location(module_name, module_path)
requests = importlib.util.module_from_spec(spec)
sys.modules[module_name] = requests
spec.loader.exec_module(requests)
print(requests.post) # should not raise error
I made a big mistake by creating an app inside my Django
project called requests
that happened a long time ago and the system has already been running for years. now I need to use the requests library and it is being imported like import requests
as mentioned in the documentation … and of course whenever I do this import it imports my app instead of the library .. so how to solve this?
You can try importing the requests/__init__.py
file directly as shown in docs: https://docs.python.org/3/library/importlib.html#importing-a-source-file-directly.
Example:
import sys
import importlib.util
module_name = 'requests'
# declare the full path to requests/__init__.py file below
module_path = '/path/to/virtualenv/site-packages/requests/__init__.py'
spec = importlib.util.spec_from_file_location(module_name, module_path)
requests = importlib.util.module_from_spec(spec)
sys.modules[module_name] = requests
spec.loader.exec_module(requests)
print(requests.post) # should not raise error