lundi 27 juin 2016

MVC the simplest example, python

I'm struggling to understand MVC pattern. I've been working with MVC frameworks like ASP.NET MVC and Django, but project structure there is pretty much forced, so it really didn't help to understand how to build my own apps based on this pattern. To clear things up i decided to write the simplest example of my understanding of MVC(console program in Python) and figure out if there is anything wrong.

|- program:
|—— controller.py
|—— model.py
|—— view.py
|—— db.txt #simulates database

So this is my basic structure. What this program will do is display all people that are inside db.txt. I use db.txt(json) to simulate actual database.

controller.py

from model import Person
import view

def showAll():
    #gets list of all Person objects
    people_in_db = Person.getAll()
    #calls view
    return view.showAllView(people_in_db)

def start():
    view.startView()
    input = raw_input()
    if input == 'y':
        return showAll()
    else:
        return view.endView()

if __name__ == "__main__":
    #running controller function
    start()

view.py

from model import Person


def showAllView(list):
    print 'In our db we have %i users. Here they are:' % len(list)
    for item in list:
        print item.name()
def startView():
    print 'MVC - the simplest example'
    print 'Do you want to see everyone in my db?[y/n]'

def endView():
    print 'Goodbye!'    

model.py

import json

class Person(object):

    def __init__(self, first_name = None, last_name = None):
        self.first_name = first_name
        self.last_name = last_name
    #returns Person name, ex: John Doe
    def name(self):
        return ("%s %s" % (self.first_name,self.last_name))

    @classmethod
    #returns all people inside db.txt as list of Person objects
    def getAll(self):
        database = open('db.txt', 'r')
        result = []
        json_list = json.loads(database.read())
        for item in json_list:
            item = json.loads(item)
            person = Person(item['first_name'], item['last_name'])
            result.append(person)
        return result

So this is scenario when user wants to see all people in db: enter image description here

Is this approach correct?

Aucun commentaire:

Enregistrer un commentaire