I come from the background of spaghetti PHP code. I am trying to learn MVC by cutting my teeth in Python using Flask and MongoDB. I think this question may apply to other situations. This is more a question for Python newbies. But this is where I first come across this setting.
I am using Flask with Blueprints to build my application. I break each main site function into a subdirectory myapp (module / project). Here is my directory structure
Dir structure
/proj/config.py /proj/runserver.py /proj/myapp/ /proj/myapp/__init__.py /proj/myapp/static/ /proj/myapp/templates/ /proj/myapp/templates/users/ /proj/myapp/templates/forums/ /proj/myapp/templates/frontend/ /proj/myapp/users/ /proj/myapp/users/__init__.py /proj/myapp/users/models.py /proj/myapp/users/views.py /proj/myapp/forums/ .. /proj/myapp/frontend/ ..
So, I'm trying to implement this simple MongoKit example. But instead of having it in one file. I need to decompose it according to the MVC pattern.
MongoKit example
from flask import Flask, request, render_template, redirect, url_for from flask.ext.mongokit import MongoKit, Document app = Flask(__name__) class User(Document): __collection__ = 'user' structure = { 'name': unicode, 'email': unicode, } required_fields = ['name', 'email'] use_dot_notation = True db = MongoKit(app) db.register([User])
The main part of my application is in init .py and looks like this:
/myapp/_init_.py
from flask import Flask, render_template, abort from flask.ext.mongokit import MongoKit, Document from .home.views import mod as home_blueprint from .users.views import mod as user_blueprint from .forums.views import mod as forum_blueprint def create_app(): app = Flask(__name__) app.config.from_object('config')
And then I'm not quite sure what to do with the rest. I am setting up the class in /myapp/users/models.py as shown below. I know that the last statement is undefined. I'm not sure if he will go there, or I need to put him somewhere else. Or, if it goes there, how can I get "db" from create_app () in init .py. I believe this has less to do with MongoKit and the Python base materials.
/myapp/users/models.py
from flask.ext.mongokit import MongoKit, Document class User(Document): structure = { 'name': unicode, 'email': unicode, } use_dot_notation = True db.register([User])