I am needing to defer the import of some libraries unless they are needed so I have created have an object to defer the import.
class Importer(object):
def __init__(self, name):
self.name = name
def __bool__(self):
try:
mod = importlib.import_module(self.name)
return True
except ImportError:
return False
def __getattr__(self, name):
try:
mod = importlib.import_module(self.name)
attr = getattr(mod, name)
setattr(self, name, attr)
return attr
except ImportError as e:
msg = self.name + " must be installed"
raise ImportError(msg)
I have run nose with my tests and everything passes. However, when I run --with-doctest it runs an extra test (that I have not defined) that generates an error in any environment where a given library isn't installed.
Testing the code below recreates the issue I am experiencing. In an environment without numpy, nosetests --with-doctest is running a second test which I have not defined.
numpy = Importer('numpy')
def mean(array):
"""
Mean of an array.
Examples
--------
>>> mean([1, 2, 3])
2.0
>>> mean([1, -1])
0.0
"""
if numpy:
return numpy.mean(array)
return float(sum(array) / len(array))
Clearly, there is only one doctest available to test. Also if numpy is installed only 1 test is run. So why then when numpy is not installed am I getting a second test? Here is the output.
.E
======================================================================
ERROR: Failure: ImportError (numpy must be installed)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/devin/Dropbox/Devin_S_+_Spark_Wave/nimble/zissue/issue.py", line 16, in __getattr__
mod = importlib.import_module(self.name)
File "/Users/devin/anaconda3/envs/issueEnv/lib/python3.6/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'numpy'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/devin/anaconda3/envs/issueEnv/lib/python3.6/site-packages/nose/failure.py", line 39, in runTest
raise self.exc_val.with_traceback(self.tb)
File "/Users/devin/anaconda3/envs/issueEnv/lib/python3.6/site-packages/nose/plugins/manager.py", line 154, in generate
for r in result:
File "/Users/devin/anaconda3/envs/issueEnv/lib/python3.6/site-packages/nose/plugins/doctests.py", line 228, in loadTestsFromModule
tests = self.finder.find(module)
File "/Users/devin/anaconda3/envs/issueEnv/lib/python3.6/doctest.py", line 933, in find
self._find(tests, obj, name, module, source_lines, globs, {})
File "/Users/devin/anaconda3/envs/issueEnv/lib/python3.6/doctest.py", line 992, in _find
if ((inspect.isroutine(inspect.unwrap(val))
File "/Users/devin/anaconda3/envs/issueEnv/lib/python3.6/inspect.py", line 512, in unwrap
while _is_wrapper(func):
File "/Users/devin/anaconda3/envs/issueEnv/lib/python3.6/inspect.py", line 503, in _is_wrapper
return hasattr(f, '__wrapped__')
File "/Users/devin/Dropbox/testing/issue/issue.py", line 22, in __getattr__
raise ImportError(msg)
ImportError: numpy must be installed
----------------------------------------------------------------------
Ran 2 tests in 0.003s
Well, this is fun!
The core difficulty is that the doctest module "tricked" you into attempting a numpy import.
That is, it probed for numpy.__wrapped__, and you took the bait.
You need to distinguish between a probe call,
for which returning a dummy value is acceptable,
and a real call, for which you must import or raise.
Perhaps a heuristic of testing for __wrapped__ suffices.
But you may find it necessary to inspect the call stack to find the caller,
notice it is e.g. autodoc,
and change behavior based on that.
Related
I am a noob in Python multiprocessing and trying to learn it.
While trying to run a class method on a separate Multiprocessing-Process. The Python class is initialized in the main process and I am trying to start a class method in a separate process.
def __initialise_strat_class_obj(self, *, strat_name: str, strat_config: StratInput):
try:
strat_instance = strat_class_dict[strat_name](strat_args=self.strat_args, strat_input=strat_config) # dynamically fetching & calling the class
strat_instance.init()
except Exception as e:
self._logger.error(f"unable to init strategy `{strat_config.id}`: {e}")
return False
strat_process = Process(target=strat_instance.run)
strat_process.start()# starting the class method in a separate process
def start(self):
self.init()
if self.is_active():
self.run()
else:
self._logger.warning(f"{self.id} -> strat is inactive, returning from thread")
return
However, I encountered the cannot pickle '_io.TextIOWrapper' object error. Below is the stack trace of the error.
Traceback (most recent call last):
File "D:\repo\StockTradeBotV2\src\strategy\__init__.py", line 237, in __init__
self.__initialise_strat_class_obj(strat_name=strat_name, strat_config=strat_inp)
File "D:\repo\StockTradeBotV2\src\strategy\__init__.py", line 263, in __initialise_strat_class_obj
strat_process.start()
File "C:\Program Files\Python311\Lib\multiprocessing\process.py", line 121, in start
self._popen = self._Popen(self)
^^^^^^^^^^^^^^^^^
File "C:\Program Files\Python311\Lib\multiprocessing\context.py", line 224, in _Popen
return _default_context.get_context().Process._Popen(process_obj)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Program Files\Python311\Lib\multiprocessing\context.py", line 336, in _Popen
return Popen(process_obj)
^^^^^^^^^^^^^^^^^^
File "C:\Program Files\Python311\Lib\multiprocessing\popen_spawn_win32.py", line 94, in __init__
reduction.dump(process_obj, to_child)
File "C:\Program Files\Python311\Lib\multiprocessing\reduction.py", line 60, in dump
ForkingPickler(file, protocol).dump(obj)
TypeError: cannot pickle '_io.TextIOWrapper' object
To overcome the serialization issue, I made use of the multiprocess package which utilizes dill for serializing objects. This time I got a completely different error:
Traceback (most recent call last):
File "D:\repo\StockTradeBotV2\src\strategy\__init__.py", line 237, in __init__
self.__initialise_strat_class_obj(strat_name=strat_name, strat_config=strat_inp)
File "D:\repo\StockTradeBotV2\src\strategy\__init__.py", line 263, in __initialise_strat_class_obj
strat_process.start()
File "C:\PythonEnvironments\StockTradeBotV2\Lib\site-packages\multiprocess\process.py", line 121, in start
self._popen = self._Popen(self)
^^^^^^^^^^^^^^^^^
TypeError: BaseProcess._Popen() takes 1 positional argument but 2 were given
I have tried calling the raw class without initializing and passing the self-argument which didn’t help. On changing the Process to Thread, the code works as intended without any errors, but I want this to run on its own process instead of parallelism so that the additional cores on my PC are used.
I am doing all this on Python-3.11.1 with multiprocess-0.70.14 package.
Edit: I have to use multiprocess.Process rather than from multiprocess.process import BaseProcess as Process which solved the issue
from PyARMViz import PyARMViz
Traceback (most recent call last):
File "", line 1, in
from PyARMViz import PyARMViz
File "C:\Users\naveen-raj-b\Anaconda3\lib\site-packages\PyARMViz_init_.py", line 14, in
from PyARMViz.PyARMViz import adjacency_parallel_category_plot
File "C:\Users\naveen-raj-b\Anaconda3\lib\site-packages\PyARMViz\PyARMViz.py", line 371, in
def adjacency_graph_gephi(rules:List[Rule], output_path:str=None):
File "C:\Users\naveen-raj-b\Anaconda3\lib\typing.py", line 261, in inner
return func(*args, **kwds)
File "C:\Users\naveen-raj-b\Anaconda3\lib\typing.py", line 685, in getitem
params = tuple(_type_check(p, msg) for p in params)
File "C:\Users\naveen-raj-b\Anaconda3\lib\typing.py", line 685, in
params = tuple(_type_check(p, msg) for p in params)
File "C:\Users\naveen-raj-b\Anaconda3\lib\typing.py", line 149, in _type_check
raise TypeError(f"{msg} Got {arg!r:.100}.")
TypeError: Parameters to generic types must be types. Got <module 'PyARMViz.Rule' from 'C:\Users\naveen-raj-b\Anaconda3\lib\site-packages\PyARMViz\Rule.
assuming you've downloaded the source code to your local machine
in the PyARMViz.py file,
change this (line 5):
from PyARMViz import Rule
to this:
from PyARMViz.Rule import Rule
then rebuild using "pip install ."
I have been trying to run a python script, but I keep on getting the following error.
Error:
Traceback (most recent call last):
File "cloud_copasi/background_daemon/cloud_copasi_daemon.py", line 18, in <module>
django.setup()
File "/Users/cloudcopasi/cloud-copasi/venv/lib/python3.8/site-packages/django/__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "/Users/cloudcopasi/cloud-copasi/venv/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate
app_config = AppConfig.create(entry)
File "/Users/cloudcopasi/cloud-copasi/venv/lib/python3.8/site-packages/django/apps/config.py", line 90, in create
module = import_module(entry)
File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'web_interface'
The script file which I am trying to run (cloud_copasi_daemon) is:
import sys, time
import django
django.setup()
from tools.daemon import Daemon
import tools.background_script
from tools.response import RemoteLoggingResponse
from cloud_copasi import settings
import logging
log=logging.getLogger(__name__)
class MyDaemon(Daemon):
#Set the level we wish to log at. Logs are sent back to the central server
#Choices are all, debug, info, error, none
def __init__(self, *args, **kwargs):
return super(MyDaemon, self).__init__(*args, **kwargs)
def stop(self, *args, **kwargs):
return super(MyDaemon, self).stop(*args, **kwargs)
def run(self):
log.debug('Daemon running')
while True:
min_repeat_time = settings.DAEMON_POLL_TYME #Seconds
start_time = time.time()
try:
tools.background_script.run()
log.debug('Background script finished')
except Exception as e:
log.exception(e)
finish_time = time.time()
difference = finish_time - start_time
if difference < min_repeat_time:
time.sleep(min_repeat_time - difference)
if __name__ == "__main__":
daemon = MyDaemon('/tmp/Cloud-COPASI.pid')
if len(sys.argv) == 2:
if 'start' == sys.argv[1]:
daemon.start()
elif 'stop' == sys.argv[1]:
daemon.stop()
elif 'restart' == sys.argv[1]:
daemon.restart()
else:
print ("Unknown command")
sys.exit(2)
sys.exit(0)
else:
print("usage: %s start|stop|restart" % sys.argv[0])
sys.exit(2)
"web_interface" is the Django App and I have verified that the path referring to it is correct. I don't know where else do I need to fix the file path to get this python script to work.
I am having the same problem on Mac OS Big Sur (running Python 3.8) as well as on Linux CentOS (running Python 3.6).
Any help is much appreciated.
When you are trying to bootstrap django like this you need to make sure to set the environment variable PYTHONPATH to include the folder where web_interface lives. I'm guessing that your cloud_copasi_daemon.py is in a different folder than web_interface so when you run python cloud_copasi_daemon.py it looks in the immediate folder in which you invoked the script and can't find it.
I am new to pysnmp and nameko. I have been assignment a work to create a service in nameko framework to perform snmp get_request using pysnmp library.
Below is the code i have tried
from pysnmp.hlapi import *
from nameko.rpc import rpc
class GreetingService(object):
name = "greeting_service"
#rpc
def getFunc(oid):
errorIndication, errorStatus, errorIndex, varBinds = next(
getCmd(SnmpEngine(),
CommunityData('public', mpModel=0),
UdpTransportTarget(('snmp.live.gambitcommunications.com', 161)),
ContextData(),
ObjectType(ObjectIdentity('SNMPv2-MIB', oid, 0)))
)
if errorIndication:
print(errorIndication)
elif errorStatus:
print('%s at %s' % (errorStatus.prettyPrint(),
errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))
else:
for varBind in varBinds:
print(' = '.join([x.prettyPrint() for x in varBind]))
if __name__ == "__main__":
getFunc('sysName')
when i try to start the service using terminal with the following command
$ nameko run helloworld
I get the following error message.
syed#syed-ThinkPad-E480:~/Pysnmp$ nameko run helloworld
Traceback (most recent call last):
File "/home/syed/.local/bin/nameko", line 11, in <module>
sys.exit(main())
File "/home/syed/.local/lib/python3.7/site-packages/nameko/cli/main.py", line 112, in main
args.main(args)
File "/home/syed/.local/lib/python3.7/site-packages/nameko/cli/commands.py", line 110, in main
main(args)
File "/home/syed/.local/lib/python3.7/site-packages/nameko/cli/run.py", line 181, in main
import_service(path)
File "/home/syed/.local/lib/python3.7/site-packages/nameko/cli/run.py", line 71, in import_service
if inspect.getmembers(potential_service, is_entrypoint):
File "/usr/lib/python3.7/inspect.py", line 354, in getmembers
if not predicate or predicate(value):
File "/home/syed/.local/lib/python3.7/site-packages/nameko/cli/run.py", line 35, in is_entrypoint
return hasattr(method, ENTRYPOINT_EXTENSIONS_ATTR)
File "/home/syed/.local/lib/python3.7/site-packages/pyasn1/type/base.py", line 221, in __getattr__
raise error.PyAsn1Error('Attempted "%s" operation on ASN.1 schema object' % attr)
pyasn1.error.PyAsn1Error: Attempted "nameko_entrypoints" operation on ASN.1 schema object
Error in sys.excepthook:
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/apport_python_hook.py", line 63, in apport_excepthook
from apport.fileutils import likely_packaged, get_recent_crashes
File "/usr/lib/python3/dist-packages/apport/__init__.py", line 5, in <module>
from apport.report import Report
File "/usr/lib/python3/dist-packages/apport/report.py", line 30, in <module>
import apport.fileutils
File "/usr/lib/python3/dist-packages/apport/fileutils.py", line 23, in <module>
from apport.packaging_impl import impl as packaging
File "/usr/lib/python3/dist-packages/apport/packaging_impl.py", line 24, in <module>
import apt
File "/usr/lib/python3/dist-packages/apt/__init__.py", line 23, in <module>
import apt_pkg
ModuleNotFoundError: No module named 'apt_pkg'
Original exception was:
Traceback (most recent call last):
File "/home/syed/.local/bin/nameko", line 11, in <module>
sys.exit(main())
File "/home/syed/.local/lib/python3.7/site-packages/nameko/cli/main.py", line 112, in main
args.main(args)
File "/home/syed/.local/lib/python3.7/site-packages/nameko/cli/commands.py", line 110, in main
main(args)
File "/home/syed/.local/lib/python3.7/site-packages/nameko/cli/run.py", line 181, in main
import_service(path)
File "/home/syed/.local/lib/python3.7/site-packages/nameko/cli/run.py", line 71, in import_service
if inspect.getmembers(potential_service, is_entrypoint):
File "/usr/lib/python3.7/inspect.py", line 354, in getmembers
if not predicate or predicate(value):
File "/home/syed/.local/lib/python3.7/site-packages/nameko/cli/run.py", line 35, in is_entrypoint
return hasattr(method, ENTRYPOINT_EXTENSIONS_ATTR)
File "/home/syed/.local/lib/python3.7/site-packages/pyasn1/type/base.py", line 221, in __getattr__
raise error.PyAsn1Error('Attempted "%s" operation on ASN.1 schema object' % attr)
pyasn1.error.PyAsn1Error: Attempted "nameko_entrypoints" operation on ASN.1 schema object
Please help me out to understand weather what i have tried is correct way or else it is wrong.. If so how to rectify the mistake.
Any help will be appreciable.
Thanks in advance
It has something to do with the way how nameko hooks up your code...
It seems to try looking up nameko_entrypoints attribute at all objects it can find in your module eventually running into ASN.1 schema objects (which are sacred and should not be used for anything other than blueprinting purposes).
My suggestion would be to replace from pysnmp.hlapi import * with specific imports of pysnmp classes/functions you are using in your code. That should hopefully hide fragile pieces out of nameko's sight.
I've recently configured celery to run some dummy tasks, and ran the workers through Terminal on my Mac. It all seems to run accordingly, took a while, since some of the literature out there seems to advise different configuration scenarios, but I got there anyway. Now the next step is to trigger the tasks via my view in Django. I'm using celery 1.2.26.post2
My project structure:
/MyApp
celery_tasks.py
celeryconfig.py
__init__.py
I've been following several tutorials and found this video and this video and this video very helpful to obtain an overall view of celery.
My scripts are:
celery_tasks.py
from celery import Celery
from celery.task import task
app = Celery() # Initialise the app
app.config_from_object('celeryconfig') # Tell Celery instance to use celeryconfig module
suf = lambda n: "%d%s" % (n, {1: "st", 2: "nd", 3: "rd"}.get(n if n < 20 else n % 10, "th"))
#task
def fav_doctor():
"""Reads doctor.txt file and prints out fav doctor, then adds a new
number to the file"""
with open('doctor.txt', 'r+') as f:
for line in f:
nums = line.rstrip().split()
print ('The {} doctor is my favorite'.format(suf(int(nums[0]))))
for num in nums[1:]:
print ('Wait! The {} doctor is my favorite'.format(suf(int(num))))
last_num = int(nums[-1])
new_last_num = last_num + 1
f.write(str(new_last_num) + ' ')
#task
def reverse(string):
return string[::-1]
#task
def add(x, y):
return x+y
celeryconfig.py
from datetime import timedelta
## List of modules to import when celery starts.
CELERY_IMPORTS = ('celery_tasks',)
## Message Broker (RabbitMQ) settings.
BROKER_URL = 'amqp://'
BROKER_PORT = 5672
#BROKER_TRANSPORT = 'sqlalchemy'
#BROKER_HOST = 'sqlite:///tasks.db'
#BROKER_VHOST = '/'
#BROKER_USER = 'guest'
#BROKER_PASSWORD = 'guest'
## Result store settings.
CELERY_RESULT_BACKEND = 'rpc://'
#CELERY_RESULT_DBURI = 'sqlite:///mydatabase.db'
## Worker settings
#CELERYD_CONCURRENCY = 1
#CELERYD_TASK_TIME_LIMIT = 20
#CELERYD_LOG_FILE = 'celeryd.log'
#CELERYD_LOG_LEVEL = 'INFO'
## Misc
CELERY_IGNORE_RESULT = False
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_ACCEPT_CONTENT=['json']
CELERY_TIMEZONE = 'Europe/Berlin'
CELERY_ENABLE_UTC = True
CELERYBEAT_SCHEDULE = {
'doctor-every-10-seconds': {
'task': 'celery_tasks.fav_doctor',
'schedule': timedelta(seconds=3),
},
}
__init__.py
from .celery_tasks import app as celery_app # Ensures app is always imported when Django starts so that shared_task will use this app.
__all__ = ['celery_app']
In settings.py
INSTALLED_APPS = [
...
'djcelery',
]
In my views folder, I have a specific view module, admin_scripts.py
from MyApp.celery_tasks import fav_doctor, reverse, send_email, add
#login_required
def admin_script_dashboard(request):
if request.method == 'POST':
form = Admin_Script(request.POST)
if form.is_valid():
backup_script_select = form.cleaned_data['backup_script_select']
dummy_script_select = form.cleaned_data['dummy_script_select']
print ("backup_script_select: {0}".format(backup_script_select))
print ("dummy_script_select: {0}".format(dummy_script_select))
if backup_script_select:
print ("Backup script exectuting. Please wait...")
dbackup_script_dir = str(Path.home()) + '/Software/MyOtherApp/cli-tools/dbbackup_DRAFT.py'
subprocess.call(" python {} ".format(dbackup_script_dir), shell=True)
async_result = reverse.delay('Using Celery')
print ("async_result: {0}".format(async_result))
result = reverse.AsyncResult(async_result.id)
print ("result: {0}".format(result))
print ("Something occured...")
if dummy_script_select:
print ("Dummy script exectuting. Please wait...")
dummy_script_dir = str(Path.home()) + '/Software/MyOtherApp/cli-tools/dummy.py'
subprocess.call(" python {} ".format(dummy_script_dir), shell=True)
async_result = add.delay(2, 5)
print ("async_result: {0}".format(async_result))
result = add.AsyncResult(async_result.id)
print ("result: {0}".format(result))
print ("Something occured...")
return render(request, 'MyApp/admin_scripts_db.html')
The problem occurs at the line in my admin_scripts.py file, where async_result = add.delay(2, 5) is called. Below the traceback:
[12/Jul/2018 09:23:19] ERROR [django.request:135] Internal Server Error: /MyProject/adminscripts/
Traceback (most recent call last):
File "/Users/MyMBP/anaconda3/lib/python3.6/site-packages/celery/local.py", line 309, in _get_current_object
return object.__getattribute__(self, '__thing')
AttributeError: 'PromiseProxy' object has no attribute '__thing'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/MyMBP/anaconda3/lib/python3.6/site-packages/kombu/utils/__init__.py", line 323, in __get__
return obj.__dict__[self.__name__]
KeyError: 'conf'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/MyMBP/anaconda3/lib/python3.6/site-packages/celery/loaders/base.py", line 158, in _smart_import
return imp(path)
File "/Users/MyMBP/anaconda3/lib/python3.6/site-packages/celery/loaders/base.py", line 112, in import_from_cwd
package=package,
File "/Users/MyMBP/anaconda3/lib/python3.6/site-packages/celery/utils/imports.py", line 101, in import_from_cwd
return imp(module, package=package)
File "/Users/MyMBP/anaconda3/lib/python3.6/site-packages/celery/loaders/base.py", line 106, in import_module
return importlib.import_module(module, package=package)
File "/Users/MyMBP/anaconda3/lib/python3.6/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 978, in _gcd_import
File "<frozen importlib._bootstrap>", line 961, in _find_and_load
File "<frozen importlib._bootstrap>", line 948, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'celeryconfig'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/MyMBP/anaconda3/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/Users/MyMBP/anaconda3/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/Users/MyMBP/anaconda3/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/MyMBP/anaconda3/lib/python3.6/site-packages/django/contrib/auth/decorators.py", line 23, in _wrapped_view
return view_func(request, *args, **kwargs)
File "/Users/MyMBP/Software/MyProject/MyProjectsite/MyProject/views/admin_scripts.py", line 44, in admin_script_dashboard
async_result = add.delay(2, 5)
File "/Users/MyMBP/anaconda3/lib/python3.6/site-packages/celery/local.py", line 143, in __getattr__
return getattr(self._get_current_object(), name)
File "/Users/MyMBP/anaconda3/lib/python3.6/site-packages/celery/local.py", line 311, in _get_current_object
return self.__evaluate__()
File "/Users/MyMBP/anaconda3/lib/python3.6/site-packages/celery/local.py", line 341, in __evaluate__
thing = Proxy._get_current_object(self)
File "/Users/MyMBP/anaconda3/lib/python3.6/site-packages/celery/local.py", line 101, in _get_current_object
return loc(*self.__args, **self.__kwargs)
File "/Users/MyMBP/anaconda3/lib/python3.6/site-packages/celery/app/base.py", line 270, in _task_from_fun
'__wrapped__': fun}, **options))()
File "/Users/MyMBP/anaconda3/lib/python3.6/site-packages/celery/app/task.py", line 201, in __new__
instance.bind(app)
File "/Users/MyMBP/anaconda3/lib/python3.6/site-packages/celery/app/task.py", line 365, in bind
conf = app.conf
File "/Users/MyMBP/anaconda3/lib/python3.6/site-packages/kombu/utils/__init__.py", line 325, in __get__
value = obj.__dict__[self.__name__] = self.__get(obj)
File "/Users/MyMBP/anaconda3/lib/python3.6/site-packages/celery/app/base.py", line 638, in conf
return self._get_config()
File "/Users/MyMBP/anaconda3/lib/python3.6/site-packages/celery/app/base.py", line 454, in _get_config
self.loader.config_from_object(self._config_source)
File "/Users/MyMBP/anaconda3/lib/python3.6/site-packages/celery/loaders/base.py", line 140, in config_from_object
obj = self._smart_import(obj, imp=self.import_from_cwd)
File "/Users/MyMBP/anaconda3/lib/python3.6/site-packages/celery/loaders/base.py", line 161, in _smart_import
return symbol_by_name(path, imp=imp)
File "/Users/MyMBP/anaconda3/lib/python3.6/site-packages/kombu/utils/__init__.py", line 96, in symbol_by_name
module = imp(module_name, package=package, **kwargs)
File "/Users/MyMBP/anaconda3/lib/python3.6/site-packages/celery/loaders/base.py", line 112, in import_from_cwd
package=package,
File "/Users/MyMBP/anaconda3/lib/python3.6/site-packages/celery/utils/imports.py", line 101, in import_from_cwd
return imp(module, package=package)
File "/Users/MyMBP/anaconda3/lib/python3.6/site-packages/celery/loaders/base.py", line 106, in import_module
return importlib.import_module(module, package=package)
File "/Users/MyMBP/anaconda3/lib/python3.6/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 978, in _gcd_import
File "<frozen importlib._bootstrap>", line 961, in _find_and_load
File "<frozen importlib._bootstrap>", line 948, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'celeryconfig'
Numerous errors get thrown, and the traceback is very large, about 9000 lines long in total. This is just a snippet. I'm new to celery and task queueing in general, so perhaps for some of the experts out there you can pick out some very obvious mistakes from my code.
As I said, the configuration of celery is successful, and when triggering the tasks in Terminal, the tasks do what they are supposed to do. I'm building this up piece by piece, so this next step is to trigger the tasks using my view in Django (instead of being called using Terminal). Once I have figured that out, then the ultimate aim is to track the progress of a task, and report the output to the user in a separate window (.js, AJAX etc.) that shows for example the line output that you see in Console.
I read that the tasks.py (in my case celery_tasks.py) file needs to be in a django app that's registered in settings.py. Is this true?
This is not a full answer, but may help partly others who encounter a similar issue:
Basically in the celery_tasks.py there is the following:
app.config_from_object('celeryconfig')
When I trigger the workers through Terminal, this works. When I do it via my view, then the error message above can be seen. Changing this line works via the view:
app.config_from_object('MyApp.celeryconfig')
I still need to figure out why there is this discrepancy and how to resolve this so that it is indifferent whether the Tasks are called via my view or Terminal.