TAGS :Viewed: 9 - Published at: a few seconds ago

[ Importing Model / Lib Class and calling from controller ]

I'm new to python and pylons although experienced in PHP.

I'm trying to write a model class which will act as a my data access to my database (couchdb). My problem is simple

My model looks like this and is called models/BlogModel.py

from couchdb import *

class BlogModel:

    def getTitles(self):
        # code to get titles here

    def saveTitle(self):
       # code to save title here

My controller is called controllers/main.py

import logging

from pylons import request, response, session, tmpl_context as c
from pylons.controllers.util import abort, redirect_to

from billion.lib.base import BaseController, render

log = logging.getLogger(__name__)

from billion.model import BlogModel

class MainController(BaseController):

    def index(self):
        return render('/main.mako')

In my index action, how do I access the method getTitles() in BlogModel?

I've tried

x = BlogModel()

But i get TypeError: 'module' object is not callable

Also BlogModel.getTitles() results in AttributeError: 'module' object has no attribute 'getTitles'

Is this down to the way I'm including the class ? Can someone tell me the best way to do this ?


Answer 1

x = BlogModel.BlogModel()

Or, more verbosely:

After you did the import, you have an object in your namespace called 'BlogModel'. That object is the BlogModel module. (The module name comes from the filename.) Inside that module, there is a class object called 'BlogModel', which is what you were after. (The class name comes from the source code you wrote.)

Instead of:

from billion.model import BlogModel

You could use:

from billion.model.BlogModel import BlogModel

then your

x = BlogModel()

would work.