MongoEngine/mongoengine

how to access app object in other files of flask app

prafullan82 opened this issue · 2 comments

run.py file

# flask packages
import jwt
from flask import Flask
from flask_restful import Api
from flask_mongoengine import MongoEngine
from flask_jwt_extended import JWTManager
import logging
# local packages
import models
from api.routes import create_routes

# external packages
import os

# default mongodb configuration
default_config = {'MONGODB_SETTINGS': {
    'db': 'blog_db',
    'host': 'localhost',
    'port': 27017}
}


def get_flask_app(config: dict = None):
    """
    Initializes Flask app with given configuration.
    Main entry point for wsgi (gunicorn) server.
    :param config: Configuration dictionary
    :return: app
    """
    # init flask
    app = Flask(__name__)

    # # configure app
    # config = default_config if config is None else config
    # app.config.update(config)

    # load config variables
    if 'MONGODB_URI' in os.environ:
        app.config['MONGODB_SETTINGS'] = {'host': os.environ['MONGODB_URI'], 'retryWrites': False}
    if 'JWT_SECRET_KEY' in os.environ:
        app.config['JWT_SECRET_KEY'] = os.environ['JWT_SECRET_KEY']

    app.config['JWT_BLACKLIST_ENABLED'] = True
    app.config['JWT_BLACKLIST_TOKEN_CHECKS'] = ['access', 'refresh']

    # File upload configs
    app.config['PROFILE_FOLDER'] = '/images/profiles'
    app.config['PROFILE_FOLDER'] = '/images/posts'
    app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
    app.config['ALLOWED_EXTENSIONS'] = set(['png', 'jpg', 'jpeg', 'gif'])

    # init api and routes
    api = Api(app=app)
    create_routes(api=api)

    # init mongoengine
    db = MongoEngine(app=app)

    # init jwt manager
    jwt = JWTManager(app=app)

    # @jwt.token_in_blocklist_loader
    # def check_if_token_in_blacklist(decrypted_token):
    #     jti = decrypted_token['jti']
    #     return models.RevokedTokens.is_jti_blacklisted(jti)

    return app


if __name__ == '__main__':
    # Main entry point when run in stand-alone mode.
    app = get_flask_app()
    app.run(debug=True)

I am trying to use app object in the file in different folder utilities.py

import os
import sys

from werkzeug.utils import secure_filename
from flask import jsonify
from run import app


class Utilities:
    FILE_ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])

    @staticmethod
    def allowed_file(filename):
        return '.' in filename and filename.rsplit('.', 1)[1].lower() in Utilities.FILE_ALLOWED_EXTENSIONS

    @staticmethod
    def upload_files(file, filename, foldername):
        try:
            print(">>>>>>>>>" + foldername + filename, file=sys.stdout)
            filename = secure_filename(filename)
            file.save(os.path.join(app.root_path, foldername, filename))
            resp = jsonify({'message': 'File successfully uploaded'})
            resp.status_code = 201
            return resp
        except Exception as e:
            print(">>>>>>>>>" + str(e), file=sys.stdout)
            resp = jsonify({'message': 'File upload failed'})
            resp.status_code = 400
            return resp

but getting below error :

ImportError: cannot import name 'create_routes' from partially initialized module 'api.routes' (most likely due to a circular import) (D:\Python\Projects\XXXX\api\routes.py)
Capture

This is a flask/mongoengine question, please ask it in https://github.com/MongoEngine/flask-mongoengine or on stackoverflow

This is a flask/mongoengine question, please ask it in https://github.com/MongoEngine/flask-mongoengine or on stackoverflow

sure Bastien..