1
votes

I'm new in Flask. I'm trying to write a very simple app. Since I come from the MVC world I'm trying to organice my code following a minimalistic MVC structure. So I've got the following:

priceChecker/
    core/
        controllers/
            __init__.py
            ItemController.py
        models/
            model.py
            item.py
            __init__.py
        services
            __init__.py
     static/
     templates/
     __init__.py
     priceChecker.py

priceChecker.py:

import os
from flask import Flask, request, session, g, redirect, url_for, abort, render_template, flash
from cassandra.cluster import Cluster

app = Flask(__name__)

# load config from this file, app.py
app.config.from_object(__name__)

#app.run(debug=True, use_debugger=False, use_reloader=False)

cluster = Cluster()

keyspace = 'testdb'
db = cluster.connect(keyspace)

from priceChecker.core.controllers.ItemController import ItemController

app.debug = True
@app.route('/search', methods=['GET', 'POST'])
def show_search_form():
    item = ItemController()
    if request.method == 'POST':
        return 'post'
    else:
        a='get'

    first_order = item.retrieveItems
    for order in first_order:
         print(order.shipname)

    return render_template('search.html')

model.py

from priceChecker.priceChecker import db


class Model(db):

    def __init__(self, tableName):
        self.__tablename__ = tableName

    def getAll(self, conditions=[]):
        try:
            result = db.execute("SELECT * FROM " + self.__tablename__)
            return result
        except ValueError:
            print("Oops, something went wrong!...")

item.py

from priceChecker.core.models.model import Model as db

class Item(db):

    def __init__(self):
        super().__init__('orders')

    def getAllItems(self):
        return db.getAllItems()

ItemController.py

from priceChecker.core.models.item import Item

class ItemController:

    def __init__(self):
        self.item = Item()

    def retrieveItems(self):
        allItms = self.item.getAllItems()
        return allItms

When running the app I'm getting some errors:

AttributeError: 'str' object has no attribute 'profile_manager'

and if I move the following line to the top

from priceChecker.core.controllers.ItemController import ItemController

I'm getting

ImportError: cannot import name 'db'

Suggestions?

Edit:

Error printed on screen:

    builtins.ImportError
ImportError: cannot import name 'db'

Traceback (most recent call last)

File "/Users/bigweld/Desktop/priceChecker/priceChecker/priceChecker.py", line 5, in <module>
from priceChecker.core.controllers.ItemController import ItemController
File "/Users/bigweld/Desktop/priceChecker/priceChecker/core/controllers/ItemController.py", line 1, in <module>
from priceChecker.core.models.item import Item
File "/Users/bigweld/Desktop/priceChecker/priceChecker/core/models/item.py", line 1, in <module>
Open an interactive python shell in this framefrom priceChecker.core.models.model import Model as db
File "/Users/bigweld/Desktop/priceChecker/priceChecker/core/models/model.py", line 2, in <module>
from priceChecker.priceChecker import db
ImportError: cannot import name 'db'
The debugger caught an exception in your WSGI application. You can now look at the traceback which led to the error.
To switch between the interactive traceback and the plaintext one, you can click on the "Traceback" headline. From the text traceback you can also create a paste of it. For code execution mouse-over the frame you want to debug and click on the console icon on the right side.

You can execute arbitrary Python code in the stack frames and there are some extra helpers available for introspection:

dump() shows all variables in the frame
dump(obj) dumps all that's known about the object
1
When you get the AttributeError, what file is raising this error? If you go to the debug screen can you try and see what value the str is?Kerry Gougeon
@KerryGougeon I just modified the questions and added the error given on screen, thanksMrCujo
can you also show priceChecker.py? @MrCujoKerry Gougeon
@KerryGougeon is there, I used the wrong name, is priceChecker.py not app.py, I corrected it already, sorry about thatMrCujo
db is a Cluster connection in priceChecker, then you import Model as db in items.py, not sure about that but there could be some naming conflicts ?euri10

1 Answers

1
votes

Figured it out! The issue was related to the way I was extending classes.

priceChecker.py and ItemController.py were fine.

Now, let's start with model.py, I had:

from priceChecker.priceChecker import db

class Model(db):

    def __init__(self, tableName):
        self.__tablename__ = tableName

    def getAll(self, conditions=[]):
        try:
            result = db.execute("SELECT * FROM " + self.__tablename__)
            return result
        except ValueError:
            print("Oops, something went wrong!...")

when it should have been:

from priceChecker.priceChecker import db

class Model():

    def __init__(self, tableName):
        self.__tablename__ = tableName

    def getAll(self, conditions=[]): 
        try:
            result = db.execute("SELECT * FROM " + self.__tablename__)
            return result
        except ValueError:
            print("Oops, something went wrong!...")

I guess that it was failing here because I was trying to extend Model() from db which is a property and not a class.

And now, item.py should have been:

from priceChecker.core.models.model import Model

class Item(Model):

    def __init__(self):
        print('\n\nInitializing Item model...')
        super().__init__('orders')

    def getAllItems(self):
       return Model.getAll(self)

at this point everything is working fine, which was initially the issue, but as you can see I'm using the word Model because I couldn't import as 'db' as my initial statement.