Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to give structure to python flask application

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

like image 845
dhana lakshmi Avatar asked Aug 31 '26 14:08

dhana lakshmi


1 Answers

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.

like image 53
Stijn Diependaele Avatar answered Sep 03 '26 03:09

Stijn Diependaele



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!