Openpyxl AttributeError - python-2.7

I was running this file fine yesterday and now I'm getting an AttributeError when I tried running it today. Here is the code I'm trying to run:
from openpyxl import load_workbook
def read_in():
wb = load_workbook('GenerateModel.xlsx')
ws = wb.get_sheet_by_name('Sheet1')
da_name = []
for i in range(1, ws.max_row+1):
if ws.cell(row=i,column=3).value != None and (
ws.cell(row=i,column=3).value != u'DA Name'):
da_name.append(ws.cell(row=i,column=3).value.encode('ascii'))
start_date = ws.cell(row=4, column=4).value
end_date = ws.cell(row=4, column=5).value
if start_date == None or end_date == None:
raise ValueError('Date cannot be left blank')
if start_date > end_date:
raise ValueError('Start Date must be less than End Date')
And here is the error that I get:
line 28, in read_in
for i in range(1, ws.max_row+1):
AttributeError: 'Worksheet' object has no attribute 'max_row'
I tried running another python script and I'm getting an ImportError that says
from openpyxl.styles import PatternFill
ImportError: cannot import name PatternFill
This makes me think that there is something wrong with the openpyxl module. I installed it using pip and I'm using the Spyder IDE. Thanks for the help.

It says '1.8.5'
Your openpyxl version is seriously outdated - hence the absence of max_row attribute on a WorkSheet class.
You need to figure out what Python executable is used when you run your script from the Spyder IDE and then update openpyxl in that environment:
pip install --upgrade openpyxl
(currently latest openpyxl is 2.4.8)

Related

Scheduled Tasks - Runs without Error but does not produce any output - Django PythonAnywhere

I have setup a scheduled task to run daily on PythonAnywhere.
The task uses the Django Commands as I found this was the preferred method to use with PythonAnywhere.
The tasks produces no errors but I don't get any output. 2022-06-16 22:56:13 -- Completed task, took 9.13 seconds, return code was 0.
I have tried uses Print() to debug areas of the code but I cannot produce any output in either the error or server logs. Even after trying print(date_today, file=sys.stderr).
I have set the path on the Scheduled Task as: (Not sure if this is correct but seems to be the only way I can get it to run without errors.)
workon advancementvenv && python3.8 /home/vicinstofsport/advancement_series/manage.py shell < /home/vicinstofsport/advancement_series/advancement/management/commands/schedule_task.py
I have tried setting the path as below but then it gets an error when I try to import from the models.py file (I know this is related to a relative import but cannot management to resolve it). Traceback (most recent call last): File "/home/vicinstofsport/advancement_series/advancement/management/commands/schedule_task.py", line 3, in <module> from advancement.models import Bookings ModuleNotFoundError: No module named 'advancement'
2022-06-17 03:41:22 -- Completed task, took 14.76 seconds, return code was 1.
Any ideas on how I can get this working? It all works fine locally if I use the command py manage.py scheduled_task just fails on PythonAnywhere.
Below is the task code and structure of the app.
from django.core.management.base import BaseCommand
import requests
from advancement.models import Bookings
from datetime import datetime, timedelta, date
import datetime
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail
from django.core.mail import send_mail
import os
from decouple import config
class Command(BaseCommand):
help = 'Sends Program Survey'
def handle(self, *args, **kwargs):
# Get today's date
date_today = datetime.datetime.now().date()
# Get booking data
bookings = Bookings.objects.all()
# For each booking today, send survey email
for booking in bookings:
if booking.booking_date == date_today:
if booking.program_type == "Sport Science":
booking_template_id = 'd-bbc79704a31a4a62a5bfea90f6342b7a'
email = booking.email
booking_message = Mail(from_email=config('FROM_EMAIL'),
to_emails=[email],
)
booking_message.template_id = booking_template_id
try:
sg = SendGridAPIClient(config('SG_API'))
response = sg.send(booking_message)
except Exception as e:
print(e)
else:
booking_template_id = 'd-3167927b3e2146519ff6d9035ab59256'
email = booking.email
booking_message = Mail(from_email=config('FROM_EMAIL'),
to_emails=[email],
)
booking_message.template_id = booking_template_id
try:
sg = SendGridAPIClient(config('SG_API'))
response = sg.send(booking_message)
except Exception as e:
print(e)
else:
print('No')
Thanks in advance for any help.
Thanks Filip and Glenn, testing within the bash console and changing the directory in the task helped to fix the issue. Adding 'cd /home/vicinstofsport/advancement_series && to my task allowed the function to run.'

exe with pytz-2018.3.dist not working. raises UnknownTimeZoneError

I'm having a problem when building an exe from my scripts that use the pytz lib. I'm constantly getting the error:
File "pytz\__init__.pyc", line 180, in timezone UnknownTimeZoneError: 'Europe\Ljubljana'
No matter how I build the exe I get this error. Running the script works. I tried all suggestions that were posted here and on other sites.
My setup.py file:
from distutils.core import setup
import os.path
try:
import py2exe
has_py2exe = True
except ImportError, e:
has_py2exe = False
myScript=__import__("myScript")
options = {'py2exe': {'packages': ['pytz']}}
options['py2exe'] = {'dist_dir': 'dist'}
setup(
name="myScript",
version=myScript.CONST_VERSION,
console=[{
'script': 'myScript.py',
'copyright': 'None',
'company_name': 'None'
}],
options=options,
)
if has_py2exe:
import zipfile
zipfile_path = os.path.join(options['py2exe']['dist_dir'], 'library.zip')
z = zipfile.ZipFile(zipfile_path, 'a')
import pytz
assert (pytz.__file__.endswith('__init__.pyc') or pytz.__file__.endswith('__init__.py')), pytz.__file__
zoneinfo_dir = os.path.join(os.path.dirname(pytz.__file__), 'zoneinfo')
disk_basedir = os.path.dirname(os.path.dirname(pytz.__file__))
for absdir, directories, filenames in os.walk(zoneinfo_dir):
assert absdir.startswith(disk_basedir), (absdir, disk_basedir)
zip_dir = absdir[len(disk_basedir):]
for f in filenames:
z.write(os.path.join(absdir, f), os.path.join(zip_dir, f))
z.close()
This builds the exe and includes the zoneinfo dir and all timezone files to library.zip.
I only use the pytz in one function where I convert the CEST timestamp to UTC timestamp to store on the server.
The function:
from datetime import datetime
import pytz
def date_time_utc(date_str):
date_tz = pytz.timezone("Europe/Ljubljana")
fmt = '%Y-%m-%d %H:%M:%S'
date_str_dt_object = datetime.strptime(date_str, fmt)
date_str_dt_object = date_tz.localize(date_str_dt_object)
date_utc = date_str_dt_object.astimezone(pytz.timezone('UTC'))
return date_utc.strftime(fmt)
The setup script for the pytz is from here. All other things like this script and any other suggested fixes raised the exactly same error.
Has any one figured out how to get this working?

Import error:No module named app1.models

In django, I am trying to populate my database from a csv file. with the help of this tutorial I wrote this code:
load_data.py:
# Full path and name to your csv file
csv_filepathname="Home/Desktop/MyProject/practice/app1/data/link1.csv"
# Full path to your django project directory
your_djangoproject_home="Home/Desktop/MyProject/practice/"
import sys,os
sys.path.append('Home/Desktop/MyProject/practice/')
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
from app1.models import Link
import csv
dataReader = csv.reader(open(csv_filepathname), delimiter=',', quotechar='"')
for row in dataReader:
abc = Link()
abc.name = row[0]
abc.roll = row[1]
abc.save()
Now, when I run this, I get import error saying no module named app1.models. I can't figure it out. Can someone please highlight the mistakes?
my directory structure
I'm working on python 2.7 and django 1.6.
All package directories in Python need an __init__.py file, which can be empty.
You shouldn't really create app directories yourself anyway; you should have run manage.py startapp app1 which would have done it for you.
(Also, note you should absolutely not be using Django 1.6, which is several years old, unsupported, and almost definitely insecure. Upgrade to a more recent, supported, version.)

Integrate SASS/SCSS with Django

I want to use SASS/SCSS with Django application.
I followed the link https://bitbucket.org/synic/django-sass.
I installed SASS using sudo pip install sass.
When i run Python manage.py runserver,iam getting error as
'sass' is not a valid tag library: Template library sass not found, tried django.templatetags.sass
Can Anyone help me?!
python sass (pip install sass) https://pypi.python.org/pypi/sass is different
from django-sass (https://bitbucket.org/synic/django-sass)
Download django sass from https://bitbucket.org/synic/django-sass after that install and setup as documented .
Have you first installed sass, the ruby app?
$ apt-get install ruby-sass
You'll know if it's done properlly; as type sass on the command line, does sassy things.
Next, I cloned django-sass (from the other answer):
git clone git#bitbucket.org:synic/django-sass.git
Then navigated to the puled folder and installed it.
$ python setup.py install
Initially the installation crashed out:
IOError: [Errno 2] No such file or directory: 'CHANGES.rst'
So I quickly created the file:
touch CHANGES.rst
and ran the install command again.
no problems.
The django-sass-processor package is a great package that lets you easily integrate SASS/SCSS with Django.
Here's a tutorial on how to set up SASS/SCSS with Django.
I've used the package a few times and have been happy with it.
Here is my DIY out of the box solution
Install Libsass and Watchdog
pip install libsass watchdog
Create an app named core
python manage.py startapp core
core/sass.py
import os
import time
import site
import sass
import threading
from pathlib import Path
from django.apps import apps
from django.conf import settings
from watchdog.observers import Observer
from watchdog.events import FileClosedEvent
def compiler():
packageFolders = [
site.getusersitepackages(),
*[path for path in site.getsitepackages()],
]
staticFolders = settings.STATICFILES_DIRS.copy()
staticFolders += [
os.path.join(app.path, "static") for app in apps.get_app_configs()
]
compileFolders = staticFolders.copy()
for staticFolder in staticFolders:
for packageFolder in packageFolders:
if Path(staticFolder).is_relative_to(packageFolder):
if staticFolder in compileFolders:
compileFolders.remove(staticFolder)
if settings.DEBUG:
def watcher(path):
class Event(FileClosedEvent):
def dispatch(self, event):
filename, extension = os.path.splitext(event.src_path)
if extension == ".scss":
time.sleep(0.5)
for d in compileFolders:
if os.path.isdir(d):
try:
sass.compile(
dirname=(d, d),
output_style="expanded",
include_paths=staticFolders,
)
except sass.CompileError as error:
print(error)
event_handler = Event(path)
observer = Observer()
observer.schedule(event_handler, path, recursive=True)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
for d in compileFolders:
if os.path.isdir(d):
try:
sass.compile(
dirname=(d, d),
output_style="expanded",
include_paths=staticFolders,
)
except sass.CompileError as error:
print(error)
thread = threading.Thread(target=watcher, args=(d,), daemon=True)
thread.start()
else:
d = settings.STATIC_ROOT
if os.path.exists(d):
try:
sass.compile(
dirname=(d, d),
output_style="expanded",
include_paths=staticFolders,
)
except sass.CompileError as error:
print(error)
core/apps.py
from django.apps import AppConfig
from core.sass import compiler
class CoreConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'core'
def ready(self):
compiler()
For more info, djboilerplate is a boilerplate project where I have added this out of the sass feature

AttributeError: 'module' object has no attribute 'ElasticSearchError' : Using Haystack Elasticsearch

Using Django & Haystack with ElasticSearch.
After installing haystack and ES, and Rebuilding Index
./manage.py rebuild_index
WARNING: This will irreparably remove EVERYTHING from your search index in connection 'default'.
Your choices after this are to restore from backups or rebuild via the rebuild_index command.
Are you sure you wish to continue? [y/N] y
Removing all documents from your index because you said so.
All documents removed.
Indexing 1039 <django.utils.functional.__proxy__ object at 0x10ca3ded0>.
AttributeError: 'module' object has no attribute 'ElasticSearchError'
Updating index has the same problem
/manage.py update_index
Indexing 1039 <django.utils.functional.__proxy__ object at 0x10ea49d90>.
AttributeError: 'module' object has no attribute 'ElasticSearchError'
Clear index works fine though ( probably because there is no index )
./manage.py clear_index
WARNING: This will irreparably remove EVERYTHING from your search index in connection 'default'.
Your choices after this are to restore from backups or rebuild via the `rebuild_index` command.
Are you sure you wish to continue? [y/N] y
Removing all documents from your index because you said so.
All documents removed.
Versions
django-haystack==2.0.0-beta
pyelasticsearch==0.5
elasticsearch==0.20.6
localhost:9200 says :
{
"ok" : true,
"status" : 200,
"name" : "Jigsaw",
"version" : {
"number" : "0.20.6",
"snapshot_build" : false
},
"tagline" : "You Know, for Search"
}
Haystack settings :
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine',
'URL': 'http://127.0.0.1:9200/',
'INDEX_NAME': 'haystack',
},
}
search_indexes.py :
import datetime
import haystack
from haystack import indexes
from app.models import City
class CityIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
name = indexes.CharField(model_attr='name')
state = indexes.CharField(model_attr='state')
country = indexes.CharField(model_attr='country')
lat = indexes.FloatField(model_attr='latitude')
lon = indexes.FloatField(model_attr='longitude')
alt = indexes.FloatField(model_attr='altitude')
pop = indexes.IntegerField(model_attr='population')
def get_model(self):
return City
Any help - why I am getting error ?
Solved it !
After debugging the process using pdb
./manage.py rebuild_index
At line 222 - in /haystack/backend/elasticsearch_backend.py
Changed
except (requests.RequestException, pyelasticsearch.ElasticSearchError), e:
To
# except (requests.RequestException, pyelasticsearch.ElasticSearchError), e:
except Exception as inst:
import pdb; pdb.set_trace()
I found out the core error was this
'ElasticSearch' object has no attribute 'from_python'.
To which I found solution here - https://github.com/toastdriven/django-haystack/issues/514#issuecomment-4058230
The version of pyelasticsearch I was using was from http://github.com/rhec/pyelasticsearch,
So I installed pyelasticsearch from a fork - http://github.com/toastdriven/pyelasticsearch using :
pip install --upgrade git+https://github.com/toastdriven/pyelasticsearch.git#3bfe1a90eab6c2dfb0989047212f4bc9fb814803#egg=pyelasticsearch
and That fixed it & Index was build !