5

I am new to python flask

Experimenting some end points with MongoDB as shown below in a single file

from flask import Flask, request
from flask.ext.mongoalchemy import MongoAlchemy
app = Flask(__name__)
app.config['DEBUG'] = True
app.config['MONGOALCHEMY_DATABASE'] = 'library'
db = MongoAlchemy(app)


class Author(db.Document):
    name = db.StringField()


class Book(db.Document):
    title = db.StringField()
    author = db.DocumentField(Author)
    year = db.IntField();


@app.route('/author/new')
def new_author():
    """Creates a new author by a giving name (via GET parameter)
    e.g.: GET /author/new?name=Francisco creates a author named Francisco
    """
    author = Author(name=request.args.get('name', ''))
    author.save()
    return 'Saved :)'






@app.route('/authors/')
def list_authors():
    """List all authors.

    e.g.: GET /authors"""
    authors = Author.query.all()
    content = '<p>Authors:</p>'
    for author in authors:
        content += '<p>%s</p>' % author.name
    return content

if __name__ == '__main__':
    app.run()

Above code which contains two end points to post and get the data which is working fine

Know looking for a way to separate the code into different file like

the database connection related code should be in different file

from flask import Flask, request
from flask.ext.mongoalchemy import MongoAlchemy
app = Flask(__name__)
app.config['DEBUG'] = True
app.config['MONGOALCHEMY_DATABASE'] = 'library'
db = MongoAlchemy(app)

I should be able to get the DB reference in different files where the schema is define and use it

class Author(db.Document):
    name = db.StringField()


class Book(db.Document):
    title = db.StringField()
    author = db.DocumentField(Author)
    year = db.IntField();

and routes will be different file

@app.route('/author/new')
def new_author():
    """Creates a new author by a giving name (via GET parameter)
    e.g.: GET /author/new?name=Francisco creates a author named Francisco
    """
    author = Author(name=request.args.get('name', ''))
    author.save()
    return 'Saved :)'






@app.route('/authors/')
def list_authors():
    """List all authors.

    e.g.: GET /authors"""
    authors = Author.query.all()
    content = '<p>Authors:</p>'
    for author in authors:
        content += '<p>%s</p>' % author.name
    return content

Here in the endpoints file i should get the reference of database schema please help me in getting this structure

Point me to some understandable sample or video which can help me to do,I am new to python as well as flask please point some sample and help to learn more thanks

dhana lakshmi
  • 847
  • 1
  • 12
  • 29

1 Answers1

13

A basic structure could look like this:

/yourapp  
    /run.py  
    /config.py  
    /yourapp  
        /__init__.py
        /views.py  
        /models.py  
        /static/  
            /main.css
        /templates/  
            /base.html  
    /requirements.txt  
    /venv

Applied to your example it would look like this.

run.py: Start your application.

from yourapp import create_app

app = create_app()
if __name__ == '__main__':
    app.run()

config.py: Contains configuration, you could add subclasses to differentiate between Development config, Test config and Production config

class Config:
    DEBUG = True
    MONGOALCHEMY_DATABASE = 'library'

yourapp/_init_.py: Initialization of your application creating a Flask instance. (Also makes your app a package).

from flask import Flask
from flask.ext.mongoalchemy import MongoAlchemy
from config import Config

db = MongoAlchemy()

def create_app():
    app = Flask(__name__)
    app.config.from_object(Config)

    db.init_app(app)
    
    from views import author_bp
    app.register_blueprint(author_bp)

    return app
    

yourapp/models.py: Contains your different models.

from . import db

class Author(db.Document):
    name = db.StringField()


class Book(db.Document):
    title = db.StringField()
    author = db.DocumentField(Author)
    year = db.IntField();

yourapp/views.py: Also called the routes.py sometimes. contains your url endpoints and the associated behavior.

from flask import Blueprint
from .models import Author

author_bp = Blueprint('author', __name__)

@author_bp.route('/author/new')
def new_author():
    """Creates a new author by a giving name (via GET parameter)
    e.g.: GET /author/new?name=Francisco creates a author named Francisco
    """
    author = Author(name=request.args.get('name', ''))
    author.save()
    return 'Saved :)'

@author_bp.route('/authors/')
def list_authors():
   """List all authors.     
   e.g.: GET /authors"""
   authors = Author.query.all()
   content = '<p>Authors:</p>'
   for author in authors:
       content += '<p>%s</p>' % author.name
   return content

yourapp/static/... Contains your static files.

yourapp/templates/.. Contains your templates.

requirements.txt has a snapshot of your package dependencies.

venv (Virtualenv) folder where your python libs are to be able to work in a contained environment.

References:

Have a look at this related question.

Good example of a widely used project structure.

Guy Shefer
  • 88
  • 1
  • 2
  • 6
  • @Beat I have updated my answer to include a more extensive overview of what the structure could look like. Please review again. – Stijn Diependaele Dec 19 '16 at 16:06
  • i am following the same directory as above but when i run the run.py i am getting the error has Traceback (most recent call last): File "run.py", line 1, in from flaskApp import create_app File "D:\angular-python\pythonAppStructure\flaskApp\__init__.py", line 3, in from config import config ImportError: cannot import name config please what i ma doing wrong – dhana lakshmi Dec 21 '16 at 09:01
  • @dhana lakshmi Try changing it too "from config import Config" (second config with capital letter) – Stijn Diependaele Dec 21 '16 at 09:22
  • Thanks, yes i tried it i understood that it from filename import class name but still i am getting the same error can u please create a git repo for above directory structure that would help me a lot please – dhana lakshmi Dec 21 '16 at 09:37
  • I am getting the error has Traceback (most recent call last): File "run.py", line 3, in app = create_app() File "D:\angular-python\pythonAppStructure\flaskApp\__init__.py", line 8, in create_app app.config.from_object(config) NameError: global name 'config' is not defined – dhana lakshmi Dec 21 '16 at 09:45
  • Also change the c to capital C => create_app app.config.from_object(**C**onfig) – Stijn Diependaele Dec 21 '16 at 10:11
  • where is this order_bp of app.register_blueprint means by any chance it must be author_bp as defined in views.py because i am getting the below error Traceback (most recent call last): File "run.py", line 3, in app = create_app() File "D:\angular-python\pythonAppStructure\flaskApp\__init__.py", line 12, in create_app app.register_blueprint(author_bp) NameError: global name 'author_bp' is not defined – dhana lakshmi Dec 21 '16 at 10:37
  • @dhana-lakshmi You're correct this should be as follows: (I have corrected the response too) from views import author_bp app.register_blueprint(author_bp) – Stijn Diependaele Dec 21 '16 at 10:47
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/131148/discussion-between-dhana-lakshmi-and-stijn-diependaele). – dhana lakshmi Dec 21 '16 at 10:56
  • Please take a look at this question http://stackoverflow.com/questions/41280074/acessing-sub-package-inside-a-package-in-python-flask-is-not-working – dhana lakshmi Dec 22 '16 at 09:45