Forums

Error when creating tables from Python code (SQLAlchemy)

Good morning everyone. I would be very grateful to anyone who could help me with this error that has been giving me problems. You see I have installed the newest versions of Python and MySQL, in Python I have a script that is responsible for creating tables in the database, the script is called "modellogs.py" is as follows:

from app import db

class carlogs(db.Model):
    __tablename__ = 'carlogs'
    __table_args__ = {'extend_existing': True}
    id = db.Column('ID', db.Integer, primary_key=True)
    make = db.Column('MAKE', db.String(80), nullable=False)
    model = db.Column('MODEL', db.String(80), nullable=False)
    year = db.Column('YEAR', db.SmallInteger, nullable=False)
    lkpyear = db.Column('LKPYEAR',db.SmallInteger, nullable=False)
    lkpmonth = db.Column('LKPMONTH',db.SmallInteger, nullable=False)
    lkpday = db.Column('LKPDAY',db.SmallInteger, nullable=False)
    lkphour = db.Column('LKPHOUR',db.SmallInteger, nullable=False)
    lkpminute = db.Column('LKPMINUTE',db.SmallInteger, nullable=False)
    lkpsecond = db.Column('LKPSECOND',db.SmallInteger, nullable=False)

    def __init__(self, make, model, year, lkpyear, lkpmonth, lkpday, lkphour, lkpminute, lkpsecond):
        self.make = make
        self.model = model
        self.year = year
        self.lkpyear = lkpyear
        self.lkpmonth = lkpmonth
        self.lkpday = lkpday
        self.lkphour = lkphour
        self.lkpminute = lkpminute
        self.lkpsecond = lkpsecond

class codelogs(db.Model):
    __tablename__ = 'codelogs'
    __table_args__ = {'extend_existing': True}
    id = db.Column('ID', db.Integer, primary_key=True)
    proveedor = db.Column('PROVEEDOR', db.String(80), nullable=False)
    parte = db.Column('PARTE', db.String(100), nullable=False)
    codigo = db.Column('CODIGO', db.String(80), nullable=False)
    lkpyear = db.Column('LKPYEAR',db.SmallInteger, nullable=False)
    lkpmonth = db.Column('LKPMONTH',db.SmallInteger, nullable=False)
    lkpday = db.Column('LKPDAY',db.SmallInteger, nullable=False)
    lkphour = db.Column('LKPHOUR',db.SmallInteger, nullable=False)
    lkpminute = db.Column('LKPMINUTE',db.SmallInteger, nullable=False)
    lkpsecond = db.Column('LKPSECOND',db.SmallInteger, nullable=False)

    def __init__(self, proveedor, parte, codigo, lkpyear, lkpmonth, lkpday, lkphour, lkpminute, lkpsecond):
        self.proveedor = proveedor
        self.parte = parte
        self.codigo = codigo
        self.lkpyear = lkpyear
        self.lkpmonth = lkpmonth
        self.lkpday = lkpday
        self.lkphour = lkphour
        self.lkpminute = lkpminute
        self.lkpsecond = lkpsecond

if __name__ == "__main__":
    # Run this file directly to create the database tables.
    print("Creating database tables...")
    db.create_all()
    print("Done!")

When I run it in my virtual environment in the CMD I get the following error:

(psavenv) C:\Users\conta\psadbs>python modellogs.py
Traceback (most recent call last):
  File "C:\Users\conta\psadbs\psavenv\Lib\site-packages\sqlalchemy\util\_collections.py", line 214, in __getattr__
    return self._data[key]
        ~~~~~~~~~~^^^^^
KeyError: 'lprecios'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\conta\eapsadbs\modellogs.py", line 1, in <module>
    from app import db
  File "C:\Users\conta\eapsadbs\app.py", line 40, in <module>
    from sigaweb import updtPrices, backup_db_os, gen_lprecios, stats_charts
  File "C:\Users\conta\eapsadbs\sigaweb.py", line 15, in <module>
    import preciolista
  File "C:\Users\conta\eapsadbs\preciolista.py", line 16, in <module>
    lprecios = Base.classes.lprecios
                    ^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\conta\psadbs\psavenv\Lib\site-packages\sqlalchemy\util\_collections.py", line 216, in __getattr__
    raise AttributeError(key)
AttributeError: lprecios

Which I don't quite understand why it happens, if by checking the code the definition of lprecios is correct, as well as its import, here is the part of the code where "preciolista.py" says the problem is:

from openpyxl import load_workbook, Workbook
from openpyxl.styles import Alignment, Border, Side, Font, Fill, Color, PatternFill
from sqlalchemy.orm import Session
from sqlalchemy.ext.automap import automap_base
from sqlalchemy import create_engine, MetaData
from dicts import todict
from operator import itemgetter
import datetime
import os
import sys

# MYSQL ORM
Base = automap_base()
enginedev = create_engine('mysql://root:psa@localhost/psa')
Base.prepare(enginedev, reflect=True)
lprecios = Base.classes.lprecios
sessiondev = Session(enginedev)

# FILEPATH TO SAVE FILES
FILEPATHFOLDER = 'lprecios/'

And in case you tell me that if you already create that table in the database, "lprecios" is also supposed to be created from the code, especially in this script called "modelserv.py"

from app import db
from flask_login import UserMixin
from werkzeug.security import generate_password_hash, check_password_hash
class lprecios(db.Model):
    __tablename__ = 'lprecios'
    id = db.Column('ID', db.Integer, primary_key=True)
    tabla = db.Column('TABLA', db.String(30), nullable=False)
    parte = db.Column('PARTE', db.String(120), nullable=False)
    codigo = db.Column('CODIGO', db.String(25), nullable=False)
    codigosiga = db.Column('CODIGOSIGA', db.String(25), nullable=False)
    precio = db.Column('PRECIO', db.Float, nullable=False)
    cantidad = db.Column('CANTIDAD', db.Integer, nullable=False)
    __table_args__ = (db.Index('UI', codigo, codigosiga, unique=True), {
                      'extend_existing': True})

    def __init__(self, tabla, parte, codigo, codesiga, precio, cantidad):
        self.tabla = tabla
        self.parte = parte
        self.codigo = codigo
        self.codigosiga = codesiga
        self.precio = precio
        self.cantidad = cantidad

    def __str__(self):
        return 'Lista de Precios'

I also already made sure that the url of the database was the same in each script in which it was referenced ('mysql://root:psa@localhost/psa') I also made sure that the PIP extensions that I use were compatible with each other (in fact most of them are the latest versions) I leave you the list of extensions that I use:

Package            Version
------------------ -----------
APScheduler        3.10.3
beautifulsoup4     4.12.2
blinker            1.6.2
certifi            2023.7.22
charset-normalizer 3.2.0
click              8.1.6
colorama           0.4.6
dnspython          2.4.2
email-validator    2.0.0.post2
et-xmlfile         1.1.0
Flask              2.3.2
Flask-APScheduler  1.12.4
Flask-Login        0.6.2
Flask-Mail         0.9.1
Flask-SQLAlchemy   3.0.5
Flask-WTF          1.1.1
greenlet           2.0.2
idna               3.4
itsdangerous       2.1.2
Jinja2             3.1.2
MarkupSafe         2.1.3
mysqlclient        2.1.1
numpy              1.25.2
openpyxl           3.1.2
packaging          23.1
pandas             2.0.3
pip                23.1.2
plotly             5.16.0
python-dateutil    2.8.2
pytz               2023.3
requests           2.31.0
setuptools         65.5.0
six                1.16.0
soupsieve          2.4.1
SQLAlchemy         2.0.20
tenacity           8.2.3
typing_extensions  4.7.1
tzdata             2023.3
tzlocal            5.0.1
urllib3            2.0.4
Werkzeug           2.3.7
wheel              0.41.1
WTForms            3.0.1

So at the moment I am without ideas of what could be causing this error, if someone could help me find the possible error I would be very grateful. In advance thank you very much for your attention.

These are the forums for PythonAnywhere, an online development environment, so we (the staff here) can only answer questions about that -- not about programming on your own machine. It's possible that other people here might be able to help out, but you'll probably have better luck posting on a general programming help site like Stack Overflow.