def create_app(): app = Flask(__name__) app.config.from_object('config') mongodb_database = MongoDBConn(host=app.config.get("MONGODB_HOST"), port=app.config.get("MONGODB_PORT")) mongodb_conn = mongodb_database[app.config.get("MONGODB_DATABASE")] from .models import User, Task, Project mongodb_database.register([User, Task, Project]) app.mongodb_database = mongodb_database app.mongodb_conn = mongodb_conn from .api_v1 import api as api_blueprint from .open_api import open_api as open_api_blueprint app.register_blueprint(api_blueprint, url_prefix="/api/v1") app.register_blueprint(open_api_blueprint, url_prefix="/open_api") @app.before_request def app_before_request(): if request.method == "OPTIONS": resp = current_app.make_default_options_response() cors_headers = { "Access-Control-Allow-Headers": "Origin, Accept, Content-Type, Authorization", "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS, HEAD", "Access-Control-Allow-Origin": "*" } resp.headers.extend(cors_headers) return resp return @app.after_request def after_request(rv): headers = getattr(g, "headers", {}) rv.headers.extend(headers) return rv return app
def create_app(config_name='development'): config_name = CONFIG_NAME or config_name app = Flask(__name__) app.version = __version__ app.artisan = __artisan__ # config app.config.from_object(config[config_name]) app.json_encoder = Encoder app.debug = app.config.get("DEBUG") # logging if app.config.get("TESTING") is True: app.logger.setLevel(logging.FATAL) else: error_file_handler = RotatingFileHandler( app.config.get("LOGGING")["error"]["file"], maxBytes=app.config.get("LOGGING_ROTATING_MAX_BYTES"), backupCount=app.config.get("LOGGING_ROTATING_BACKUP_COUNT") ) error_file_handler.setLevel(logging.WARNING) error_file_handler.setFormatter( logging.Formatter(app.config.get('LOGGING')['error']['format']) ) app.logger.addHandler(error_file_handler) # database connections app.mongodb_database = MongodbConn( host=app.config.get("DB_HOST"), port=app.config.get("DB_PORT")) app.mongodb_conn = app.mongodb_database[ app.config.get("DB_DBNAME")] app.sup_oauth = SupOAuth( ext_key=app.config.get("EXT_KEY"), ext_secret=app.config.get("EXT_SECRET"), secret_key=app.config.get("SECRET_KEY"), expires_in=app.config.get("EXPIRES_IN"), api_uri=app.config.get("OAUTH_API_URI"), token_uri=app.config.get("OAUTH_TOKEN_API_URI"), redirect_uri=app.config.get("OAUTH_REDIRECT_URI") ) from blueprints.user.models import ExtUser app.mongodb_database.register([ExtUser]) # register blueprints from blueprints.user import blueprint as user_module app.register_blueprint(user_module, url_prefix="/user") from blueprints.comment import blueprint as comment_module app.register_blueprint(comment_module, url_prefix="/comment") # register error handlers @app.errorhandler(404) def app_error_404(error): current_app.logger.warn( "Error: 404\n{}".format(traceback.format_exc())) return make_json_response(NotFound()) @app.errorhandler(405) def app_error_405(error): current_app.logger.warn( "Error: 405\n{}".format(traceback.format_exc())) return make_json_response(MethodNotAllowed()) @app.errorhandler(Exception) def app_error_uncaught(error): current_app.logger.warn( "Error: Uncaught\n{}".format(traceback.format_exc())) return make_json_response(UncaughtException(repr(error))) @app.before_request def app_before_request(): # cors response if request.method == "OPTIONS": resp = current_app.make_default_options_response() cors_headers = make_cors_headers() resp.headers.extend(cors_headers) return resp print "-------------------------------------------------------" print "Comment Extension: {}".format(app.version) print "Developers: {}".format(', '.join(app.artisan)) print "-------------------------------------------------------" return app
def create_app(config_name='default'): config_name = CONFIG_NAME or config_name app = Flask(__name__, static_folder='static', static_url_path='/static', template_folder='templates') # config app.config.from_object(config[config_name]) app.debug = app.config.get('DEBUG') app.json_encoder = Encoder app.jinja_env.cache = None ensure_dirs( app.config.get('LOG_FOLDER'), app.config.get('TEMPORARY_FOLDER') ) # cdn app.cdn = Qiniu( access_key=app.config.get('CDN_ACCESS_KEY'), secret_key=app.config.get('CDN_SECRET_KEY'), ssl=app.config.get('CDN_USE_SSL'), ) @app.template_filter() def dateformat(t, to_format='%Y-%m-%d'): try: _date = datetime.fromtimestamp(t) except Exception: return u'' return _date.strftime(to_format) @app.template_filter() def safe_src(url, timestamp=None): return media_safe_src(url, timestamp) # logging if app.config.get('UNITTEST') is True: app.logger.setLevel(logging.FATAL) # database connections rds_pool = ConnectionPool(host=app.config.get('REDIS_HOST'), port=app.config.get('REDIS_PORT'), db=app.config.get('REDIS_DB'), password=app.config.get('REDIS_PASSWORD')) rds_conn = Redis(connection_pool=rds_pool) mongodb_conn = MongodbConn( host=app.config.get('MONGODB_HOST'), port=app.config.get('MONGODB_PORT'), max_pool_size=app.config.get('MONGODB_MAX_POOL_SIZE') ) mongodb = mongodb_conn[app.config.get('MONGODB_DATABASE')] mongodb_user = app.config.get('MONGODB_USER') mongodb_pwd = app.config.get('MONGODB_PASSWORD') if mongodb_user and mongodb_pwd: mongodb.authenticate(mongodb_user, mongodb_pwd) # register mongokit models mongodb_conn.register([Commodity, Promotion, Activity, Category, Tip, Store, Media, Shortcut]) # register new mimetype mimetypes.init() mimetypes.add_type('image/svg+xml', '.svg') # inject database connections to app object app.redis = rds_conn app.mongodb_conn = mongodb_conn app.mongodb = mongodb # inject analytics app.sa_mod = Analyzer(rds_conn, rds_conn) # register blueprints register_blueprints(app) # errors @app.errorhandler(Exception) def errorhandler(err): err_detail = traceback.format_exc() err_detail = '<br />'.join(err_detail.split('\n')) err_msg = '<h1>{}</h1><br/>{}'.format(repr(err), err_detail) return make_response(err_msg, 579) return app
def create_app(config_name='development'): app = Flask(__name__) # config app.config.from_object(config[config_name]) app.debug = app.config.get('DEBUG') app.json_encoder = Encoder # bson.ObjectId, encode as string repr # database connections mongodb_database = Connection(host=app.config.get("MONGODB_HOST"), port=app.config.get("MONGODB_PORT")) mongodb_conn = mongodb_database[app.config.get("MONGODB_DATABASE")] # inject database connections to app object app.mongodb_database = mongodb_database app.mongodb_conn = mongodb_conn # register error handlers @app.errorhandler(404) def app_error_404(error): current_app.logger.warn("Error: 404\n{}".format( traceback.format_exc())) return make_json_response(NotFound()) @app.errorhandler(405) def app_error_405(error): current_app.logger.warn("Error: 405\n{}".format( traceback.format_exc())) return make_json_response(MethodNotAllowed()) @app.errorhandler(400) def app_error_400(error): current_app.logger.warn("Error: 400\n{}".format( traceback.format_exc())) return make_json_response(ErrUncaughtException(repr(error))) # register before request handlers @app.before_request def app_before_request(): # cors response if request.method == "OPTIONS": resp = current_app.make_default_options_response() cors_headers = make_cors_headers() resp.headers.extend(cors_headers) return resp return # register blueprints from blueprints.user import blueprint as user_module app.register_blueprint(user_module, url_prefix="/user") from blueprints.group import blueprint as group_module app.register_blueprint(group_module, url_prefix="/group") from blueprints.order import blueprint as order_module app.register_blueprint(order_module, url_prefix="/order") from blueprints.menu import blueprint as menu_module app.register_blueprint(menu_module, url_prefix="/menu") return app
def create_app(config_name='development'): config_name = CONFIG_NAME or config_name app = Flask(__name__) app.version = __version__ app.artisan = __artisan__ # config app.config.from_object(config[config_name]) app.json_encoder = Encoder # logging if app.config.get("TESTING") is True: app.logger.setLevel(logging.FATAL) else: error_file_handler = RotatingFileHandler( app.config.get("LOGGING")["error"]["file"], maxBytes=app.config.get("LOGGING_ROTATING_MAX_BYTES"), backupCount=app.config.get("LOGGING_ROTATING_BACKUP_COUNT") ) error_file_handler.setLevel(logging.WARNING) error_file_handler.setFormatter( logging.Formatter(app.config.get('LOGGING')['error']['format']) ) app.logger.addHandler(error_file_handler) # database connections app.mongodb_database = MongodbConn( host=app.config.get("DB_HOST"), port=app.config.get("DB_PORT")) app.mongodb_conn = app.mongodb_database[ app.config.get("DB_DBNAME")] app.sup_oauth = SupOAuth( ext_key=app.config.get("EXT_KEY"), ext_secret=app.config.get("EXT_SECRET"), secret_key=app.config.get("SECRET_KEY"), expires_in=app.config.get("EXPIRES_IN"), api_uri=app.config.get("OAUTH_API_URI"), token_uri=app.config.get("OAUTH_TOKEN_API_URI"), redirect_uri=app.config.get("OAUTH_REDIRECT_URI") ) from blueprints.user.models import ExtUser app.mongodb_database.register([ExtUser]) # register blueprints from blueprints.user import blueprint as user_module app.register_blueprint(user_module, url_prefix="/user") from blueprints.newsletter import blueprint as newsletter_module app.register_blueprint(newsletter_module, url_prefix="/newsletter") # register error handlers @app.errorhandler(404) def app_error_404(error): current_app.logger.warn( "Error: 404\n{}".format(traceback.format_exc())) return make_json_response(NotFound()) @app.errorhandler(405) def app_error_405(error): current_app.logger.warn( "Error: 405\n{}".format(traceback.format_exc())) return make_json_response(MethodNotAllowed()) @app.errorhandler(Exception) def app_error_uncaught(error): current_app.logger.warn( "Error: Uncaught\n{}".format(traceback.format_exc())) return make_json_response(UncaughtException(repr(error))) @app.before_request def app_before_request(): # cors response if request.method == "OPTIONS": resp = current_app.make_default_options_response() cors_headers = make_cors_headers() resp.headers.extend(cors_headers) return resp print "-------------------------------------------------------" print "Newsletter Extension: {}".format(app.version) print "Developers: {}".format(', '.join(app.artisan)) print "-------------------------------------------------------" return app