How to use multiprocess in django command? - django

I'm tring to use ProcessPoolExecutor in django command to get some results at same time. And I tried with below codes to get it
# main codes
import json
import time
import datetime
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
from redis import Redis
from django.conf import settings
from django.core.management.base import BaseCommand
from thrift.transport import TSocket, TTransport
from thrift.protocol import TBinaryProtocol
from utils.cache import pool
from services.analysis.thrift.Analysis import Client, Dashparam
from api.analysis.models import MDashBoard
redis_con = Redis(connection_pool=pool)
class AnalysisThriftService(object):
def __init__(self):
...
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.transport.close()
class Command(BaseCommand):
help = 'python manage.py --settings "xxx"'
def add_arguments(self, parser):
parser.add_argument('--dashboard_id', type=int, help="ID")
#staticmethod
def _handle_with_thrift(dashboard_id):
try:
print(dashboard_id)
with AnalysisThriftService() as thrift_server:
dashboard_result = ...
except:
import traceback
traceback.print_exc()
def handle(self, *args, **options):
dashboard_id = options["dashboard_id"]
if dashboard_id is None:
dashboard_tables = [dashboard.id for dashboard in MDashBoard.objects.all()]
with ProcessPoolExecutor(max_workers=5) as executor:
executor.map(Command._handle_with_thrift, dashboard_tables)
else:
...
But I always get error like
Process Process-5:
Process Process-2:
Traceback (most recent call last):
File "D:\python3\lib\multiprocessing\process.py", line 258, in _bootstrap
self.run()
File "D:\python3\lib\multiprocessing\process.py", line 93, in run
self._target(*self._args, **self._kwargs)
File "D:\python3\lib\concurrent\futures\process.py", line 169, in _process_worker
call_item = call_queue.get(block=True)
File "D:\python3\lib\multiprocessing\queues.py", line 113, in get
return _ForkingPickler.loads(res)
File "C:\Users\Domob\Desktop\dev\myapi\analysis\management\commands\dashboard_schedule_task.py", line 15, in <modu
le>
from api.analysis.models import MDashBoard
File "C:\Users\Domob\Desktop\dev\myapi\analysis\models.py", line 4, in <module>
from utils.models import BasicModel, StaticCharField
File "C:\Users\Domob\Desktop\dev\myapi\utils\models.py", line 9, in <module>
class BasicModel(models.Model):
File "C:\Users\Domob\Desktop\dev\venv_myapi\lib\site-packages\django\db\models\base.py", line 103, in __new__
app_config = apps.get_containing_app_config(module)
File "C:\Users\Domob\Desktop\dev\venv_myapi\lib\site-packages\django\apps\registry.py", line 252, in get_containing_ap
p_config
self.check_apps_ready()
File "C:\Users\Domob\Desktop\dev\venv_myapi\lib\site-packages\django\apps\registry.py", line 135, in check_apps_ready
raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
How can I get the expected results.
Great thanks.

You'll need to set up Django for the subprocesses in the subprocess initializer function.
def subprocess_setup():
django.setup()
# Could do other things here
# ...
with ProcessPoolExecutor(max_workers=5, initializer=subprocess_setup) as executor:

Got the same issue but solved it differently as suggested by this thread.
I had to explicitly pass the context to the ProcessPoolExecutor in order to get things right.
The code would look something like this
import multiprocessing
fork_context = multiprocessing.get_context('fork')
with ProcessPoolExecutor(max_workers=5, mp_context=fork_context) as executor:
...

Related

Django ElasticSearch Celery Task Model call returns 'str' object is not callable

Running into an odd issue that hasn't occurred in other projects with celery and django.
I'm taking a JSON obj, iterating through it, and putting it into a django model, but can't create the model.
tasks.py
from __future__ import absolute_import, unicode_literals
from myapp.celery import app
from django.apps import apps
from datetime import datetime
from zeep import Client, Settings, helpers
from zeep.wsse.username import UsernameToken
from .models import *
import pickle, json, copy
class DateTimeEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, datetime):
return o.isoformat()
return json.JSONEncoder.default(self, o)
#app.task()
def getProjects():
#dumpfile is a pickled zeep obj
dumpfile = open('dump.txt','rb')
getDataObjs = pickle.load(dumpfile)
getDataObjsAsOrderedDict = helpers.serialize_object(getDataObjs)
getDataObjsAsJson = json.loads(json.dumps(getDataObjsAsOrderedDict, cls=DateTimeEncoder))
for project in getDataObjsAsJson:
try:
new_project_project_key = int(copy.deepcopy(project['projectKey']))
print(new_project_project_key)
print(type(new_project_project_key))
print(type(MyDjangoDBModel))
new_project_db_obj,created = MyDjangoDBModel.objects.get_or_create(project_key=new_project_project_key)
print("HIT")
This is what the logs return
[2019-06-12 15:08:03,319: WARNING/ForkPoolWorker-4] 10836
[2019-06-12 15:08:03,319: WARNING/ForkPoolWorker-4] <class 'int'>
[2019-06-12 15:08:03,319: WARNING/ForkPoolWorker-4] <class 'django.db.models.base.ModelBase'>
[2019-06-12 15:08:03,321: WARNING/ForkPoolWorker-4] 'str' object is not callable
I've also gotten the same error with MyDjangoModel = app.get_model('app name', 'model name'), the above is with direct import with from .models import *. The copy is more than likely unnecessary, though it was an attempt to work around the issue.
UPDATE
documents.py
from elasticsearch_dsl.connections import connections
from django_elasticsearch_dsl import DocType, Index
from elasticsearch import Elasticsearch, RequestsHttpConnection
from elasticsearch_dsl import Search
client = Elasticsearch(
['https://user:pass#elasticsearch:9200'],
# turn on SSL
use_ssl=True,
# make sure we verify SSL certificates
verify_certs=True,
# provide a path to CA certs on disk
ca_certs='/usr/src/app/ca.crt',
connection_class=RequestsHttpConnection
)
my_search = Search(using=client)
from .models import MyDjangoModel
# Create a connection to ElasticSearch
connections.create_connection()
myDjangoModel = Index('myDjangoModel')
myDjangoModel.settings(
number_of_shards=1,
number_of_replicas=0
)
#myDjangoModel.doc_type
class siteMyDjangoModelDocument(DocType):
class Meta:
model = MyDjangoModel
fields = ['project_key', 'name', 'description', 'userCreated', 'userModified']
# define simple search here
# Simple search function
def search(title):
query = my_search.query("match", name=title)
response = query.execute()
return response
models.py
from django.db import models
# Create your models here.
class MyDjangoModel(models.Model):
"""Handles x"""
project_key = models.IntegerField(db_index=True)
name = models.TextField(blank=True)
description = models.TextField(blank=True)
userCreated = models.TextField(blank=True)
userModified = models.TextField(blank=True)
as requested, I've run this outside of celery, this is what the traceback looks like, the root cause looks to be django_elasticsearch_dsl library,
I've added both models.py and documents.py above.
'str' object is not callable
Traceback (most recent call last):
File "tests.py", line 59, in <module>
new_project_db_obj = GetProjects.objects.create(project_key=new_project_project_key)
File "/usr/local/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/django/db/models/query.py", line 422, in create
obj.save(force_insert=True, using=self.db)
File "/usr/local/lib/python3.7/site-packages/django/db/models/base.py", line 741, in save
force_update=force_update, update_fields=update_fields)
File "/usr/local/lib/python3.7/site-packages/django/db/models/base.py", line 790, in save_base
update_fields=update_fields, raw=raw, using=using,
File "/usr/local/lib/python3.7/site-packages/django/dispatch/dispatcher.py", line 175, in send
for receiver in self._live_receivers(sender)
File "/usr/local/lib/python3.7/site-packages/django/dispatch/dispatcher.py", line 175, in <listcomp>
for receiver in self._live_receivers(sender)
File "/usr/local/lib/python3.7/site-packages/django_elasticsearch_dsl/signals.py", line 57, in handle_save
registry.update(instance)
File "/usr/local/lib/python3.7/site-packages/django_elasticsearch_dsl/registries.py", line 75, in update
doc().update(instance, **kwargs)
File "/usr/local/lib/python3.7/site-packages/django_elasticsearch_dsl/documents.py", line 231, in update
self._get_actions(object_list, action), **kwargs
File "/usr/local/lib/python3.7/site-packages/django_elasticsearch_dsl/documents.py", line 191, in bulk
return bulk(client=self.connection, actions=actions, **kwargs)
File "/usr/local/lib/python3.7/site-packages/elasticsearch_dsl/document.py", line 269, in _get_connection
return connections.get_connection(using or self._doc_type.using)
File "/usr/local/lib/python3.7/site-packages/elasticsearch_dsl/connections.py", line 91, in get_connection
return self.create_connection(alias, **self._kwargs[alias])
File "/usr/local/lib/python3.7/site-packages/elasticsearch_dsl/connections.py", line 66, in create_connection
conn = self._conns[alias] = Elasticsearch(**kwargs)
File "/usr/local/lib/python3.7/site-packages/elasticsearch/client/__init__.py", line 192, in __init__
self.transport = transport_class(_normalize_hosts(hosts), **kwargs)
File "/usr/local/lib/python3.7/site-packages/elasticsearch/transport.py", line 127, in __init__
self.set_connections(hosts)
File "/usr/local/lib/python3.7/site-packages/elasticsearch/transport.py", line 177, in set_connections
connections = list(zip(connections, hosts))
File "/usr/local/lib/python3.7/site-packages/elasticsearch/transport.py", line 173, in _create_connection
return self.connection_class(**kwargs)
TypeError: 'str' object is not callable
Please, make sure the version of each packages is the right one, specially:
Django
elasticsearch,
elasticsearch-dsl,
django-elasticsearch-dsl
Make sure they are compatible between them and supported, also take in mind you are running everything over Python 3.7
Is your field project_key on MyDjangoDBModel CharField?
If project['projectKey'] is string as well, try putting directly.
MyDjangoDBModel.objects.get_or_create(project_key=project['projectKey'])
Let's see if there will be any difference.

errors while running python scripts triggered by django app

I am building a fully open source testrunner for my needs but I am running into some problems. the test runner parses a yaml file for a set of scripts in various paths and executed the scripts and uses a lib that i will be creating to return the outcome. right now i have a simple ping script that im working to get running and testing as i progress but i am getting a lot of errors. the errors are below and all the source code is also shown below the errors.
The github repo for this is here. feel free to pull it in and test the issues i am seeing.
https://github.com/castaway2000/testrunner
The issue:
I am trying to use the testrunner i built to parse a yaml file for paths to scripts i am writing for projects im using.
For example if want to use a group of certain tests on a target, i can make a yaml file for each set of the types of tests.
There is a certain problem I am seeing with this however, the relative path and exact path of the files are not able to use the django libraries, cause its unable to find the path of the libraries unless its running from the top level of the django app (ie. ./ping_google.py vs ./testcases/ping_google.py)
but on top of that, the django app says is not running when the independent libraries are referencing models.py and admin.py cant import models from the same directory. I need help fixing and understanding this issue.
Here is the rundown(stacktrace):
Enterprize:testrunner xwing$ python3 ping_google.py
Traceback (most recent call last):
File "ping_google.py", line 1, in <module>
from testrunnerlib.test import HostInterface
File "/Users/xwing/PycharmProjects/testrunner/testrunnerlib/test.py", line 11, in <module>
from testrunner.models import Host, TestSuite
File "/Users/xwing/PycharmProjects/testrunner/testrunner/models.py", line 5, in <module>
class Host(models.Model):
File "/usr/local/lib/python3.6/site-packages/django/db/models/base.py", line 105, in __new__
app_config = apps.get_containing_app_config(module)
File "/usr/local/lib/python3.6/site-packages/django/apps/registry.py", line 237, in get_containing_app_config
self.check_apps_ready()
File "/usr/local/lib/python3.6/site-packages/django/apps/registry.py", line 124, in check_apps_ready
raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
after i put import django and django.setup() in the django settings file the above error goes away but i get the following error:
Enterprize:testrunner xwing$ python3 ping_google.py
Traceback (most recent call last):
File "ping_google.py", line 1, in <module>
from testrunnerlib.test import HostInterface
File "/Users/xwing/PycharmProjects/testrunner/testrunnerlib/test.py", line 11, in <module>
from testrunner.models import Host, TestSuite
File "/Users/xwing/PycharmProjects/testrunner/testrunner/models.py", line 5, in <module>
class Host(models.Model):
File "/Users/xwing/PycharmProjects/testrunner/testrunner/models.py", line 6, in Host
ip_address = models.CharField(max_length=16)
File "/usr/local/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 1043, in __init__
super(CharField, self).__init__(*args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 166, in __init__
self.db_tablespace = db_tablespace or settings.DEFAULT_INDEX_TABLESPACE
File "/usr/local/lib/python3.6/site-packages/django/conf/__init__.py", line 53, in __getattr__
self._setup(name)
File "/usr/local/lib/python3.6/site-packages/django/conf/__init__.py", line 41, in _setup
self._wrapped = Settings(settings_module)
File "/usr/local/lib/python3.6/site-packages/django/conf/__init__.py", line 97, in __init__
mod = importlib.import_module(self.SETTINGS_MODULE)
File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "/Users/xwing/PycharmProjects/testrunner/testrunner/settings.py", line 133, in <module>
django.setup()
File "/usr/local/lib/python3.6/site-packages/django/__init__.py", line 27, in setup
apps.populate(settings.INSTALLED_APPS)
File "/usr/local/lib/python3.6/site-packages/django/apps/registry.py", line 115, in populate
app_config.ready()
File "/usr/local/lib/python3.6/site-packages/django/contrib/admin/apps.py", line 23, in ready
self.module.autodiscover()
File "/usr/local/lib/python3.6/site-packages/django/contrib/admin/__init__.py", line 26, in autodiscover
autodiscover_modules('admin', register_to=site)
File "/usr/local/lib/python3.6/site-packages/django/utils/module_loading.py", line 50, in autodiscover_modules
import_module('%s.%s' % (app_config.name, module_to_search))
File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "/Users/xwing/PycharmProjects/testrunner/testrunner/admin.py", line 3, in <module>
from testrunner.models import Host, TestSuite
ImportError: cannot import name 'Host'
Fixing this will help with testing the rest of the build out scenarios for the testrunner but i will still need advice on the relative path and environment python needs to use to know where to look for these libraries. if possible i can put the libs in the root python directory so the libs are irrelevant to the problem.
problem file:
from testrunnerlib.test import HostInterface
from testrunnerlib.outcomes import Outcomes
from ping3 import ping
def pinger(host):
result = Outcomes()
try:
ping_google = ping(host)
print(ping_google)
if ping_google:
return result.passed()
msg = 'ping had an issue, the following is all we know %s' % ping_google
return result.failed(msg)
except Exception as e:
return result.aborted(exception=e)
if __name__ == '__main__':
pinger(HostInterface().target)
only lib with django imports:
import yaml
import subprocess
from testrunner.models import Host, TestSuite
class HostInterface(object):
def __init__(self):
self._target = 'not set'
#property
def target(self):
return self._target
#target.setter
def target(self, value):
print("setter of target called", value)
self._target = value
#target.deleter
def target(self):
print("deleter of target called")
del self._target
def host(self):
out = Host.objects.get(id=self.target).name
return out
class YamlInterface:
def __init__(self, yamlfile):
self.file = yamlfile
def handle_yaml(self):
data = TestSuite.objects.get(id=self.file)
yamldata = yaml.safe_load(data.text)
for i in yamldata['testsuite']:
status = subprocess.call('python3 %s' % i, shell=True)
print(status)
def run_tests(host, yaml):
h_interface = HostInterface()
h_interface.target = host
h_interface.host()
yaml = YamlInterface(yaml)
yaml.handle_yaml()
the models:
from __future__ import unicode_literals
from django.db import models
class Host(models.Model):
ip_address = models.CharField(max_length=16)
port = models.IntegerField()
name = models.CharField(max_length=256)
class TestSuite(models.Model):
name = models.CharField(max_length=256)
text = models.TextField()
is_active = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True, auto_now=False)
updated = models.DateTimeField(auto_now_add=False, auto_now=True)
def __str__(self):
return "%s" % self.name
admin.py
from django.contrib import admin
from django import forms
from testrunner.models import Host, TestSuite
class HostAdmin(admin.ModelAdmin):
list_display = ['name']
fields = ('name', 'ip_address', 'port')
def __str__(self):
return '%s' % self.name
pass
admin.site.register(Host, HostAdmin)
class TestSuiteAdmin(admin.ModelAdmin):
def formfield_for_dbfield(self, db_field, **kwargs):
formfield = super(TestSuiteAdmin, self).formfield_for_dbfield(db_field, **kwargs)
if db_field.name == 'text':
formfield.widget = forms.Textarea(attrs=formfield.widget.attrs)
return formfield
admin.site.register(TestSuite, TestSuiteAdmin)
You need to make a Django Management Command. This will let you create scripts that will allow you to use all of Django's features.
And you would run this command as python3 manage.py ping_google
To create a management command,
In your apps folder, create a module called management (make a folder called management and place init.py file in it)
Inside the management folder, create a commands module (folder and init.py file)
Inside the commands folder create your ping_google.py file.
Commands are written like this,
from django.core.management.base import BaseCommand, CommandError
class Command(BaseCommand):
help = 'Desc of your command'
def handle(self, *args, **options):
# Your logic goes here
You can read more on custom django commands here

celery error :'module' object has no attribute 'celery'

I try to start celery using command below:
celery -A converter worker --loglevel=info
but it doesn't work.
my converter.py is:
from __future__ import absolute_import, unicode_literals
from celery.task import task
#task
def ffmpeg_convert(input_file, bitrate):
#do something
and my celery.py:
from __future__ import absolute_import, unicode_literals
import os
from celery import Celery
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings.base')
app = Celery('converter')
app.config_from_object('django.conf:settings', namespace='CELERY')
app.conf.broker_url = 'redis://localhost:6379/0'
app.autodiscover_tasks()
#app.task(bind=True)
def debug_task(self):
print('Request: {0!r}'.format(self.request))
but I get following error:
Traceback (most recent call last):
File "/usr/local/bin/celery", line 11, in <module>
sys.exit(main())
File "/usr/local/lib/python2.7/dist-packages/celery/__main__.py", line 14, in main
_main()
File "/usr/local/lib/python2.7/dist-packages/celery/bin/celery.py", line 326, in main
cmd.execute_from_commandline(argv)
File "/usr/local/lib/python2.7/dist-packages/celery/bin/celery.py", line 488, in execute_from_commandline
super(CeleryCommand, self).execute_from_commandline(argv)))
File "/usr/local/lib/python2.7/dist-packages/celery/bin/base.py", line 279, in execute_from_commandline
argv = self.setup_app_from_commandline(argv)
File "/usr/local/lib/python2.7/dist-packages/celery/bin/base.py", line 481, in setup_app_from_commandline
self.app = self.find_app(app)
File "/usr/local/lib/python2.7/dist-packages/celery/bin/base.py", line 503, in find_app
return find_app(app, symbol_by_name=self.symbol_by_name)
File "/usr/local/lib/python2.7/dist-packages/celery/app/utils.py", line 366, in find_app
found = sym.celery
AttributeError: 'module' object has no attribute 'celery'
Do anyone has any idea?Thank for help
I've been experiencing a similar problem and I think the issue might be from where you're running celery -A proj worker --loglevel=info.
If you have a project structure like
directory
--virtualenv/
--proj/
----manage.py
----requirements.txt
----proj/
------settings.py
------celery.py
You need to run the command from --proj/
Looks like your celery.py file shadows the celery package.

django celery Getting TypeError: 'tuple' object is not callable

I've just installed celery on my local machine (win10) with RabbitMQ and followed their beginners tutorial . But I get the error message TypeError: 'tuple' object is not callable
src>workon clicknstrip
(clicknstrip) src>python manage.py celery beat
celery beat v3.1.18 (Cipater) is starting.
__ - ... __ - _
Configuration ->
. broker -> amqp://guest:**#localhost:5672//
. loader -> celery.loaders.app.AppLoader
. scheduler -> celery.beat.PersistentScheduler
. db -> celerybeat-schedule
. logfile -> [stderr]#%INFO
. maxinterval -> now (0s)
[2015-08-13 10:01:13,441: INFO/MainProcess] beat: Starting...
[2015-08-13 10:01:13,466: WARNING/MainProcess] DB Reset: Account for new __version__ field
[2015-08-13 10:01:13,470: CRITICAL/MainProcess] beat raised exception <type 'exceptions.TypeError'>: TypeError("'tuple' object is not callable",)
Traceback (most recent call last):
File "clicknstrip\lib\site-packages\celery\apps\beat.py", line 112, in start_scheduler
beat.start()
File "clicknstrip\lib\site-packages\celery\beat.py", line 454, in start
humanize_seconds(self.scheduler.max_interval))
File "clicknstrip\lib\site-packages\kombu\utils\__init__.py", line 322, in __get__
value = obj.__dict__[self.__name__] = self.__get(obj)
File "clicknstrip\lib\site-packages\celery\beat.py", line 494, in scheduler
return self.get_scheduler()
File "clicknstrip\lib\site-packages\celery\beat.py", line 489, in get_scheduler
lazy=lazy)
File "clicknstrip\lib\site-packages\celery\utils\imports.py", line 53, in instantiate
return symbol_by_name(name)(*args, **kwargs)
File "clicknstrip\lib\site-packages\celery\beat.py", line 358, in __init__
Scheduler.__init__(self, *args, **kwargs)
File "clicknstrip\lib\site-packages\celery\beat.py", line 185, in __init__
self.setup_schedule()
File "clicknstrip\lib\site-packages\celery\beat.py", line 406, in setup_schedule
self.install_default_entries(self.schedule)
File "clicknstrip\lib\site-packages\celery\beat.py", line 190, in install_default_entries
not self.app.backend.supports_autoexpire:
File "clicknstrip\lib\site-packages\kombu\utils\__init__.py", line 322, in __get__
value = obj.__dict__[self.__name__] = self.__get(obj)
File "clicknstrip\lib\site-packages\celery\app\base.py", line 625, in backend
return self._get_backend()
File "clicknstrip\lib\site-packages\celery\app\base.py", line 444, in _get_backend
return backend(app=self, url=url)
TypeError: 'tuple' object is not callable
This is my celery.py
from __future__ import absolute_import
import os
from celery import Celery
# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'clicknstrip.settings.local')
from django.conf import settings
app = Celery('clicknstrip')
# Using a string here means the worker will not have to
# pickle the object when using Windows.
app.config_from_object('django.conf:settings')
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)
#app.task(bind=True)
def debug_task(self):
print('Request: {0!r}'.format(self.request))
This is my task.py
from __future__ import absolute_import
from celery import shared_task
#shared_task
def add(x, y):
return x + y
#shared_task
def mul(x, y):
return x * y
#shared_task
def xsum(numbers):
return sum(numbers)
Found my issue because I added an extra comma at the end of
CELERY_RESULT_BACKEND='djcelery.backends.database:DatabaseBackend',

Correctly import in Django management command

Custom management command, oauth.py, needs a model from another module. When I include "from appname.authentication.models import Contact" I get "AttributeError: 'module' object has no attribute 'models'." - Im stuck on django 1.6 until I able to build an test suite to help with the upgrade.
How do I correctly import Contact?
Other notable SO answers:
Circular Import
Import Settings
Each directory other than /app has an __init__.py . /app is in sys.path/ django directory, /app:
util
-management
--commands
---oauth.py
appname
-authentication
--models.py
extouth.py
extoauth.py is standalone script with the same import and works, but only in manage.py shell. The custom management command will be better.
oauth.py:
import sys
from optparse import make_option
from provider.oauth2.models import Client
from appname.authentication.models import Contact
from django.core.management.base import BaseCommand
class Command(BaseCommand):
help = 'Creates OAUTH user and gets access token.'
option_list = BaseCommand.option_list + (
make_option('--create-client',
dest='create_client',
help='''Returns tuple of <id,secret>...'''),
make_option('--get-access-token',
dest='get_access_token',
help='''Returns time limited access token...'''),
)
def handle(self, *args, **options):
if options['create_client']:
return self.create_client(options['create_client'])
elif options['get_access_token']:
self.get_access_token()
def create_client(self, user):
return user
def get_access_token(self):
pass
Console out:
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 399, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 392, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 272, in fetch_command
klass = load_command_class(app_name, subcommand)
File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 75, in load_command_class
module = import_module('%s.management.commands.%s' % (app_name, name))
File "/usr/local/lib/python2.7/site-packages/django/utils/importlib.py", line 40, in import_module
__import__(name)
File "/app/waapiutil/management/commands/oauth.py", line 4, in <module>
from wowza.authentication.models import Contact
File "/app/wowza/authentication/models.py", line 80, in <module>
class
SalesforceModel(with_metaclass(salesforce.models.SalesforceModelBase, models.Model)):
AttributeError: 'module' object has no attribute 'models'
hypo - settings is not getting imported
So my settings must be getting set just as they do with the manage.py shell usage because if I include at the top of my file:
from django.conf import settings
settings.configure()
I get:
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 399, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 392, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 272, in fetch_command
klass = load_command_class(app_name, subcommand)
File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 75, in load_command_class
module = import_module('%s.management.commands.%s' % (app_name, name))
File "/usr/local/lib/python2.7/site-packages/django/utils/importlib.py", line 40, in import_module
__import__(name)
File "/app/waapiutil/management/commands/oauth.py", line 2, in <module>
settings.configure()
File "/usr/local/lib/python2.7/site-packages/django/conf/__init__.py", line 89, in configure
raise RuntimeError('Settings already configured.')
RuntimeError: Settings already configured.
hypo - deeper syntax error (that should have broken production anyway)
searching for occurrences of models.model in my app files yields four results, each has the correct capitalization of models.Model.
hypo - Contact is already imported
When I comment out the import and run the command i get:
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 399, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 392, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python2.7/site-packages/django/core/management/base.py", line 242, in run_from_argv
self.execute(*args, **options.__dict__)
File "/usr/local/lib/python2.7/site-packages/django/core/management/base.py", line 285, in execute
output = self.handle(*args, **options)
File "/app/waapiutil/management/commands/oauth.py", line 23, in handle
return self.create_client(options['create_client'])
File "/app/waapiutil/management/commands/oauth.py", line 32, in create_client
c = Client(user=Contact.objects.get_by_email(e), name=n,
NameError: global name 'Contact' is not defined
Snippets from authentication/models.py for hynekcer's comment
# Core Django imports
from django.db import models
from django.core.validators import MinLengthValidator
from django.utils.six import with_metaclass
# Third-party imports
import pycountry
from rest_framework.compat import oauth2_provider
import salesforce
from salesforce import fields
from salesforce.backend import manager
...
class SalesforceManager(manager.SalesforceManager):
"""
Override the default Salesforce manager so we can get some proper REST framework exceptions
"""
def get(self, *args, **kwargs):
try:
result = self.get_queryset().get(*args, **kwargs)
except self.model.MultipleObjectsReturned:
raise MultipleUniqueRecords()
except Exception as e:
logger.warning("SalesForce exception %s", str(e))
raise NoRecord()
return result
class SalesforceModel(with_metaclass(salesforce.models.SalesforceModelBase, models.Model)):
"""
Abstract model class for Salesforce objects.
"""
_base_manager = objects = SalesforceManager()
_salesforce_object = True
class Meta:
managed = False
abstract = True
Id = fields.SalesforceAutoField(primary_key=True)
def clean_fields(self, *args, **kwargs):
# Override the default clean_fields method so we can catch validation exceptions
try:
super(SalesforceModel, self).clean_fields(*args, **kwargs)
except Exception as validation_exception:
detail = ''
for field, message in validation_exception.error_dict.items():
detail += field + ': ' + message[0].messages[0]
raise ValidationError(detail)
def save(self, *args, **kwargs):
# Override the default save method so we can remove fields that Salesforce manages
if self._meta.model_name in ['contact', 'account', 'license', 'sslcertificate']:
if not self.Id:
for field in self._meta.fields:
if field.attname == 'created_date' or field.attname == 'certificate_id':
self._meta.fields.remove(field)
else:
update_fields = self._meta.get_all_field_names()
remove_list = []
if self._meta.model_name == 'contact':
remove_list = ['created_date', 'accesstoken', 'refreshtoken', 'oauth2_client', 'grant', 'Id', 'entitlement_plan']
elif self._meta.model_name == 'account':
remove_list = ['created_date', 'account', 'Id']
elif self._meta.model_name == 'license':
remove_list = ['created_date', 'Id']
elif self._meta.model_name == 'sslcertificate':
remove_list = ['certificate_id', 'created_date', 'Id']
for remove_field in remove_list:
if remove_field in update_fields:
update_fields.remove(remove_field)
kwargs['update_fields'] = update_fields
# Retry five times if there's a SalesforceError
delay = 1
for retry in range(5):
try:
super(SalesforceModel, self).save(*args, **kwargs)
break
except Exception as e:
logger.error("Saving {0} resulted in an error {1}, retry {2}".format(str(self),str(e),retry))
if retry < 4 and "SERVER_UNAVAILABLE" in str(e):
time.sleep(delay)
delay *= 2
else:
(This is a comment requiring much place, not the answer yet.)
I thought my eyes deceiving when I saw a line from my database backend in your application code, maybe also with a concrete model in the same module. I see that your pasted code is based on an older django-salesforce 0.5.x code. OK, hopefully you use also the package 0.5.x. It probably can not work with the current django-salesforce 0.6 or nobody should expect it
The most safe style is to use the public API. A more fragile style is to use also undocumented features. The most fragile is to copy-paste code from the core of other package and to forget that you started to use a new version. You must have a sufficiently serious reason and enough time if you do such things. (I did it six times for every Django version because the django-salesforce backend is interesting enough for me, but I don't reccomend it to you.)
You can write simply:
class MySalesforceModel(salesforce.models.SalesforceModel):
def ... # your custom method
class Meta:
managed = False
abstract = True
The advantage is that this will use the right current SalesforceModel even with the next version of Django and django-salesforce.
If you really need to customize a backend, please comply a sane separation of the backend and application code to different modules so that the backend can be imported without importing any concrete model. Otherwise you can easy get ugly dependencies. Also a nonempty 'init.py` can cause sily dependencies
You need no hypothesis ("hypo") for such simple things if you have the complete source code. You can simply log (print) that information e.g. put import sys; print("settings imported", "my_project.settings" in sys.modules) or verify that settins are correctly configured - put temporarily a line just before a problematic place: from django.conf import settings; print(settings.INSTALLED_APPS) # any valid name
You should check syntax errors before asking a help. It can be done easily for any specific Python version for a tree of subdirectories e.g. by python2.7 -m compileall $(pwd)
It is very insane to use a general handling except Exception: especially while you are debugging. Imagine that the code between try...except will raise an ImportError and you swallow it.
It can be easier to solve dependencies by refactoring the code than to maintain the fragile code later. Imagine that you import inside a function and you get a strange ImportError message from your friend only sometimes if the module is imported from a thread only in Apache, but it succeeds if you import it from the main thread. Explicit import is favoured.