Crontab python django issue - python

The following works as expected:
python /usr/share/str8RED/manage.py getLiveResults
However, nothing happens when I use the following cronjob:
*/1 * * * * python /usr/share/str8RED/manage.py getLiveResults
Using the link below I have managed to create a error log:
http://matthewwittering.com/blog/django-tips/running-a-django-management-commands-with-crontab.html
This informs me that:
Traceback (most recent call last):
File "/usr/share/str8RED/manage.py", line 8, in <module>
from django.core.management import execute_from_command_line
ImportError: No module named django.core.management
I can get cronjab working and running every minute with echo "Hello World". Any help would be appreciated, many thanks, Alan.
Contents of getLiveResults.py:
from django.core.management import BaseCommand
from straightred.models import StraightredTeam
from straightred.xmlsoccer import XmlSoccer
#The class must be named Command, and subclass BaseCommand
class Command(BaseCommand):
# Show this when the user types help
help = "My test command"
# A command must define handle()
def handle(self, *args, **options):
xmlsoccer = XmlSoccer(api_key='XYZ', use_demo=False)
teams = xmlsoccer.call_api(method='GetAllTeamsByLeagueAndSeason',
seasonDateString='1617',
league='English League Championship')
numberOfTeamsUpdated = 0
for team in teams:
if '{http://xmlsoccer.com/Team}Team_Id' in team.keys():
teamUpdate = StraightredTeam(teamid=team['{http://xmlsoccer.com/Team}Team_Id'],
teamname=team['{http://xmlsoccer.com/Team}Name'],
country=team['{http://xmlsoccer.com/Team}Country'],
stadium=team['{http://xmlsoccer.com/Team}Stadium'],
homepageurl=team['{http://xmlsoccer.com/Team}HomePageURL'],
wikilink=team['{http://xmlsoccer.com/Team}WIKILink'],
currentteam=1)
teamUpdate.save()
numberOfTeamsUpdated = numberOfTeamsUpdated + 1
self.stdout.write("Hello world!")

If you are using virtual env, then you need to activate the environment,
maybe something like:
*/1 * * * * /usr/share/str8RED/.env/bin/python /usr/share/str8RED/manage.py getLiveResults

Related

ModuleNotFoundError : No Module named 'tests'

I have a test automation project where so far everything was working great.
I was able to run all the test by setting the Python path by typing the below command:
set PYTHONPATH="projectpath"
then
python .\"testscriptpath"
Now this week I started seeing this error:
ModuleNotFoundError : No Module named 'tests'
I tried the solution of adding a blank __init__.py file, but it didn't help.
I am looking for a solution to generate XML report files.
Below is the code:
import unittest
import allure
import xmlrunner
from selenium.webdriver.common.by import By
from tests.common import WICSUtils
from tests.common.GenericUtils import wics_select_by_visible_text, wics_utils_click, wics_select_by_index, \
wics_utils_get_text
from tests.icc.ICC_Common_Methods import search_by_offender_id_icc, make_initial_decision, \
go_to_inmate_classification_report, go_to_job_submitter_screen_and_submit_report, \
refresh_job_queue_until_job_finished
class ICCInmateInitialClassification(unittest.TestCase):
#classmethod
def setUpClass(cls):
# Get new driver instance
global myDriver
global emailAddress
global userFolder
myDriver = GenericUtils.get_new_driver_instance()
#allure.step("Logging into WICS")
def test_01_logging_into_WICS(self):
global emailfolderforreports
emailfolderforreports = "Reports"
WICSUtils.loginToWICS(myDriver, WICSUtils.Environment.UAT1, test)
expectedTitle = "ODSP590 - My Landing Page"
actualTitle = WICSUtils.get_page_main_title(myDriver)
GenericUtils.wics_assertion_is_substring(expectedTitle, actualTitle, myDriver)
#classmethod
def tearDownClass(cls):
WICSUtils.logOutWICS(myDriver)
myDriver.quit()
if __name__ == '__main__':
# main method to run xmlrunner to produce xml report in test-reports folder
with open('../../../test-results/ICC_R001_Inmate_Initial_Classification.xml', 'wb') as output:
unittest.main(
testRunner=xmlrunner.XMLTestRunner(output=output),
failfast=False, buffer=False, catchbreak=False)
Below is the error stack trace:
PS C:\Users\VellaSR\PycharmProjects\wics-selenium-scripts> python .\tests\icc\High\ICC_R001_Inmate_Initial_Classification.py
Traceback (most recent call last):
File ".\tests\icc\High\ICC_R001_Inmate_Initial_Classification.py", line 8, in <module>
from tests.common import WICSUtils
ModuleNotFoundError: No module named 'tests'
In order to make Python resolves all your relative imports, you must execute your script from the root working directory.
In your case, for example, the root is wics-selenium-scripts. You need to go there with your terminal, and then execute python path/to/your/script.py, e.g. python tests\icc\High\scriptName.py

How to run a python script in Django?

I am new to Django, and I'm trying to import one of my models in a script as we do it in views.py. I'm getting an error:
Traceback (most recent call last):
File "CallCenter\make_call.py", line 3, in <module>
from .models import Campaign
ModuleNotFoundError: No module named '__main__.models'; '__main__' is not a package
My file structure is like:
MyApp\CallCenter\
CallCenter contains __init__.py, make_call.py, models.py, views.py and MyApp has manage.py
from twilio.rest import Client
from twilio.twiml.voice_response import VoiceResponse, Say, Dial, Number, VoiceResponse
from .models import Campaign
def create_xml():
# Creates XML
response = VoiceResponse()
campaign = Campaign.objects.get(pk=1)
response.say(campaign.campaign_text)
return response
xml = create_xml()
print(xml)
In general, it's better to refactor "ad-hoc" scripts – anything you might run manually from a command line, say – into management commands.
That way the Django runtime is set up correctly once things get to your code, and you get command-line parsing for free too.
Your make_call.py might become something like this:
CallCenter/management/commands/make_call.py
from twilio.rest import Client
from twilio.twiml.voice_response import VoiceResponse, Say, Dial, Number, VoiceResponse
from CallCenter.models import Campaign
from django.core.management import BaseCommand
def create_xml(campaign):
# Creates XML
response = VoiceResponse()
response.say(campaign.campaign_text)
return response
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument("--campaign-id", required=True, type=int)
def handle(self, campaign_id, **options):
campaign = Campaign.objects.get(pk=campaign_id)
xml = create_xml(campaign)
print(xml)
and it would be invoked with
$ python manage.py make_call --campaign-id=1
from wherever your manage.py is.
(Remember to have an __init__.py file in both the management/ and the management/commands/ folders.)

Python import from script outside package

Python unable to import package, but works correctly from within the package. A fully functional example below. In the virtual env I am using 3.6 All responses greatly appreciated!
parsers/
__init__.py
element.py
parser1.py
parser2.py
parserresolver.py
outsidepkg.py
init.py is empty
element.py:
def router():
pass
parser1.py:
from element import *
def parse(data):
return data
parser2.py:
from element import *
def parse(data):
return data
parserresolver.py:
import sys
from parser1 import *
from parser2 import *
def resolve(data):
parseddata = None
parsers = ['parser1', 'parser2']
funcname = 'parse'
for parser in parsers:
module = sys.modules[parser]
if hasattr(module, funcname):
func = getattr(module, funcname)
parseddata = func(data)
print(parseddata)
return parseddata
if __name__ == "__main__":
resolve('something')
outsidepkg.py:
import parsers.parserresolver
def getapi(data):
parsers.parserresolver.resolve(data)
if __name__ == "__main__":
print(getapi('in parse api main'))
So when I call parserresolver.py directly it works great, no import errors and prints out "something" as expected.
But when I call outsidepkg.py I am getting this error:
Traceback (most recent call last):
File "C:\code\TestImport\TestImport\outsidepkg.py", line 1, in <module>
import parsers.parserresolver
File "C:\code\TestImport\TestImport\parsers\parserresolver.py", line 2, in <module>
from parser1 import *
ModuleNotFoundError: No module named 'parser1'
Press any key to continue . . .
You need to change the imports of:
from file import whatever
To:
from .file import whatever
Since your code to run it is outside the folder, use a . to get the directory, since the file isn't outside the package.

Writing and importing custom modules/classes

I've got a class that I'm trying to write called dbObject and I'm trying to import it from a script in a different folder. My structure is as follows:
/var/www/html/py/testobj.py
/var/www/html/py/obj/dbObject.py
/var/www/html/py/obj/__init__.py
Now, __init__.py is an empty file. Here are the contents of dbObject.py:
class dbObject:
def __init__():
print "Constructor?"
def test():
print "Testing"
And here's the contents of testobj.py:
#!/usr/bin/python
import sys
sys.path.append("/var/www/html/py")
import obj.dbObject
db = dbObject()
When I run this, I get:
Traceback (most recent call last):
File "testobj.py", line 7, in <module>
db = dbObject()
NameError: name 'dbObject' is not defined
I'm new to Python, so I'm very confused as to what I'm doing wrong. Could someone please point me in the right direction?
EDIT: Thanks to Martijn Pieters' answer I modified my testobj.py as follows:
#!/usr/bin/python
import sys
sys.path.append("/var/www/html/py")
sys.path.append("/var/www/html/py/dev")
from obj.dbObject import dbObject
db = dbObject()
However, now when I run it I get this error:
Traceback (most recent call last):
File "testobj.py", line 7, in <module>
db = dbObject()
TypeError: __init__() takes no arguments (1 given)
Is this referring to my init.py or the constructor within dbObject?
EDIT(2): Solved that one myself, the constructor must be able to take at least one parameter - a reference to itself. Simple fix. Looks like this problem is solved!
EDIT (Final): This is nice - I can cut out the import sys and sys.path.append lines and it still works in this instance. Lovely.
You need to import the class from the module:
from obj.dbObject import dbObject
This adds the class dbObject directly to your local namespace.
Your statement import obj.dbObject adds the name obj to the local namespace, so you could also do this instead:
db = obj.dbObject.dbObject()
because obj.dbObject is the dbObject.py module in your obj package directory.

ContentHandler is undefined

I'm trying to learn Python's SAX module from O'Reilly's Python and XML. I'm trying to run the following sample code, but I keep getting an error and I can't figure out why.
The first file is handlers.py:
class ArticleHandler(ContentHandler):
"""
A handler to deal with articles in XML
"""
def startElement(self, name, attrs):
print "Start element:", name
The second file is art.py, which imports the first file:
#!/usr/bin/env python
# art.py
import sys
from xml.sax import make_parser
from handlers import ArticleHandler
ch = ArticleHandler( )
saxparser = make_parser( )
saxparser.setContentHandler(ch)
saxparser.parse(sys.stdin)
When I try to run art.py, I get the following:
% python art.py < article.xml
Traceback (most recent call last):
File "art.py", line 7, in <module>
from handlers import ArticleHandler
File "~/handlers.py", line 1, in <module>
class ArticleHandler(ContentHandler):
NameError: name 'ContentHandler' is not defined
I'm probably missing something obvious. Can anybody help?
Thanks!
You have to import ContentHandler in handlers.py as follows:
from xml.sax.handler import ContentHandler
This should do it.

Categories

Resources