Flask is a Python web framework (full disclosure - currently Flask is my go-to framework), this snippet provides a template for creating a Flask application that uses MongoFrames.
There are various ways of creating a Flask application, we're going to be using an application factory:
# app.py
import argparse
from flask import Flask
from mongoframes import *
from pymongo import MongoClient
def create_app(env):
"""
We use an application factory to allow the app to be configured from the
command line at start up.
"""
# Create the app
app = Flask(__name__)
# Configure the application to the specified config
app.config['ENV'] = env
app.config.from_object('settings.{0}.Config'.format(env))
# Set up MongoFrames
app.mongo = MongoClient(app.config['MONGO_URI'])
Frame._client = app.mongo
if app.config.get('MONGO_PASSWORD'):
Frame.get_db().authenticate(
app.config.get('MONGO_USERNAME'),
app.config.get('MONGO_PASSWORD')
)
# ...other application set up tasks...
return app
if __name__ == "__main__":
# Parse the command-line arguments
parser = argparse.ArgumentParser(description='Application server')
parser.add_argument(
'-e',
'--env',
choices=['dev', 'local', 'prod'],
default='local',
dest='env',
required=False
)
args = parser.parse_args()
# Create and run the application
app = create_app(args.env)
app.run(port=app.config.get('PORT'))
The application code here can be configured to different environments (in this case local, development or production), to start the application in the production environment we'd enter the following at the command line:
$ python app.py --prod
Each environment requires its own settings file which is used to configure the application (including potentially different database credentials), at the same level as the app.py file we create a settings folder and add Python files for each environment (e.g local.py, dev.py, prod.py). Each settings file must define a Config class the attributes of which are used as settings:
# settings/prod.py
class Config:
# Database
MONGO_URI = 'mongodb://localhost:27017/mydb'
MONGO_USERNAME = 'mydb'
MONGO_PASSWORD = 'password'
# Debugging
DEBUG = False
# Networking
PORT = 5000
PREFERRED_URL_SCHEME = 'https'
SERVER_NAME = 'mywebsite.com'
In my own set up I also create a DefaultConfig class which the other environment Config classes inherit from.
And that's it, you can now use MongoFrames with your Flask application :)