def create_app(config_name): app = Flask(__name__, static_url_path='/static') app.config.from_object(DevelopmentConfig) DevelopmentConfig.init_app(app) bootstrap.init_app(app) mail.init_app(app) moment.init_app(app) from main import main as main_blueprint app.register_blueprint(main_blueprint) return app
def create_app(config_name): app = Flask(__name__) app.config.from_object(config) config.init_app(app) mail.init_app(app) bootstrap.init_app(app) moment.init_app(app) db.init_app(app) login_manager.init_app(app) from .main import main as main_blueprint app.register_blueprint(main_blueprint) from .auth import auth as auth_blueprint app.register_blueprint(auth_blueprint, url_prefix = '/auth') from .post import post as post_blueprint app.register_blueprint(post_blueprint, url_prefix = '/post') return app
else: raise def init_logger(cfg): mkdir_p(cfg.LOG_DIR) mkdir_p(cfg.LOG_DIR_TASK) logger = logging.getLogger("dls") formatter = logging.Formatter( '%(asctime)s %(name)-12s %(levelname)-8s %(message)s') handler = logging.handlers.RotatingFileHandler(cfg.LOG_DIR + "/dls.log", maxBytes=1000000, backupCount=5) handler.setFormatter(formatter) logger.addHandler(handler) logger.setLevel(logging.DEBUG) config = DevelopmentConfig() init_logger(config) app_flask = Flask(__name__, static_folder='../frontend', template_folder='../frontend') app_flask.config.from_object('config.DevelopmentConfig') if app_flask.config['DEBUG']: print ('Flask application config:') for ii,pp in enumerate(app_flask.config): print ('\t%d : %s -> [%s]' % (ii, pp, app_flask.config[pp])) async_mode = None socketio = SocketIO(app_flask, async_mode=async_mode) from app.backend import api from app.backend.core import datasets from app.backend.dataset import api from app.backend.core import models from app.backend.model import api
from flask import Flask from flask_sqlalchemy import SQLAlchemy from config import ProductionConfig, TestingConfig, DevelopmentConfig from .middleware import MiddleWare # Instance of flask app app = Flask(__name__) # load Environment configurations if app.config["ENV"] == "production": app.config.from_object(ProductionConfig()) elif app.config["ENV"] == "testing": app.config.from_object(TestingConfig()) else: app.config.from_object(DevelopmentConfig()) from .utils.constants import LOGS_FILE # Error Handle file_handler = FileHandler(app.config[LOGS_FILE]) file_handler.setLevel(WARNING) # Add Error Handler to App app.logger.addHandler(file_handler) # Middle Ware app.wsgi_app = MiddleWare(app.wsgi_app) db = SQLAlchemy(app) from rq import Queue
from scrapy import Request from scrapy.spiders import CrawlSpider from scrapy.crawler import CrawlerProcess from scrapy.utils.project import get_project_settings import uuid import logging from config import DevelopmentConfig from modules.common.db.database import DBHelper, VNCSpecies, VNCSpeciesDetails, VNCSpeciesImage, DetailStatusEnum logger = logging.getLogger(__name__) DBHelper.connect_database(DevelopmentConfig()) def download_and_put_image_into_host(url): return None def update_status(obj, status, session): try: obj.detail_status = status session.commit() logger.info('Updated status of object id={}, from to {}'.format( obj.id, status)) except (Exception, ) as ex: logger.error('Update detail_status failed on id={}. Error: {}'.format( obj.id, ex)) session.rollback()
# -*- coding: utf-8 -*- """ bb8 Client API init ~~~~~~~~~~~~~~~~~~~ Copyright 2016 bb8 Authors """ import os from config import DevelopmentConfig, DeployConfig, TestingConfig config = None if os.getenv('BB8_TEST', '') == 'true': config = TestingConfig() # pylint: disable=R0204 elif os.getenv('BB8_DEPLOY', '') == 'true': config = DeployConfig() # pylint: disable=R0204 else: config = DevelopmentConfig() # pylint: disable=R0204
def create_app(test_config=None): # create and configure the app app = Flask(__name__) if test_config: app.config.from_object(TestingConfig()) else: app.config.from_object(DevelopmentConfig()) db = setup_db(app) migrate.init_app(app, db) CORS(app) @app.route('/') def index(): return "Course Management APP" #---------------------------------------------------------# # Students #---------------------------------------------------------# @app.route('/students') @authorize_user('get:data') def get_students(): items_limit = request.args.get('limit', 3, type=int) page_num = request.args.get('page', 1, type=int) current_index = page_num - 1 error = False try: students = db.session.query(Student).order_by( Student.std_id).limit(items_limit).offset(items_limit * current_index).all() formatted_std = [student.format for student in students] except Exception: error = True print(sys.exc_info()) if error: abort(404) else: return jsonify({ "success": True, "students": formatted_std, "total": len(formatted_std) }) @app.route('/students/<int:student_id>') @authorize_user('get:data') def get_student_by_id(student_id): error = False try: student = db.session.query(Student).filter( Student.std_id == student_id).one_or_none() format_student = student.format except Exception: error = True print(sys.exc_info()) if error: abort(404) else: return jsonify({ "success": True, "student": format_student, }) @app.route('/students/create', methods=['POST']) @authorize_user('post:data') def create_student(): body = request.get_json() std_fname = body.get('fname') std_lname = body.get('lname') std_email = body.get('email') std_dob = body.get('dob') std_gender = body.get('sex') std_regno = int(body.get('regno')) error = False try: # instantiate student object std = Student(std_regno, std_fname, std_lname, std_email, std_dob, std_gender) std.insert() students = Student.query.order_by(Student.std_id).all() students_list = [student.format for student in students] except Exception as e: db.session.rollback() error = True print(sys.exc_info()) finally: db.session.close() if error: abort(422) else: return redirect('/students') @app.route('/students/<int:student_id>', methods=['PATCH']) @authorize_user('patch:data') def update_students(student_id): body = request.get_json() if body: email = body.get('email') else: abort(400) error = False try: std = db.session.get(Student, student_id) std.std_email = email std.update() except Exception as e: db.session.rollback() error = True print(sys.exc_info()) if error: abort(422) else: return redirect(f'/students/{student_id}') @app.route('/students/<int:student_id>', methods=['DELETE']) @authorize_user('delete:data') def delete_students(student_id): error = False try: std = db.session.get(Student, student_id) std.delete() updated_students = Student.query.order_by(Student.std_id).all() formatted_students = [ student.format for student in updated_students ] except Exception as e: db.session.rollback() print(e) finally: db.session.close() if error: abort(404) else: return redirect('/students') #---------------------------------------------------------# # Courses #---------------------------------------------------------# @app.route('/courses') @authorize_user('get:data') def getCourses(): error = False try: courses = db.session.query(Course).order_by(Course.crs_id).all() format_courses = [course.format for course in courses] except Exception: error = True print(sys.exc_info()) finally: db.session.close() if error: abort(404) else: return jsonify({ "success": True, "courses": format_courses, "total": len(courses) }) @app.route('/courses/create', methods=['POST']) @authorize_user('post:data') def create_courses(): body = request.get_json() crs_title = body.get('title') crs_code = body.get('code') crs_desc = body.get('desc') crs_book = body.get('book') crs_lec = int(body.get('lec')) crs_room = int(body.get('room')) error = False try: # instantiate course object crs = Course(crs_code, crs_title, crs_desc, crs_book, crs_lec, crs_room) crs.insert() courses = Course.query.order_by(Course.crs_id).all() courses_list = [course.format for course in courses] except Exception as e: db.session.rollback() error = True print(sys.exc_info()) finally: db.session.close() if error: abort(422) else: return redirect('/courses') @app.route('/courses/<int:course_id>', methods=['PATCH']) @authorize_user('patch:data') def update_courses(course_id): body = request.get_json() if body: title = body.get('title') book = body.get('book') else: abort(400) error = False try: crs = db.session.get(Course, course_id) crs.crs_title = title crs.crs_book = book crs.update() except Exception as e: db.session.rollback() error = True print(sys.exc_info()) if error: abort(422) else: return jsonify({'success': True, 'course_id': crs.crs_id}) @app.route('/courses/<int:course_id>', methods=['DELETE']) @authorize_user('delete:data') def delete_courses(course_id): error = False try: crs = db.session.get(Course, course_id) crs.delete() updated_courses = Course.query.order_by(Course.crs_id).all() formatted_courses = [course.format for course in updated_courses] except Exception as e: db.session.rollback() print(e) finally: db.session.close() if error: abort(422) else: return jsonify({ 'success': True, 'deleted_id': crs.crs_id, 'courses': formatted_courses, 'total_courses': len(updated_courses) }) @app.errorhandler(AuthError) def authError(error): return jsonify({ 'success': False, 'error': error.status_code, 'message': error.error['description'] }), error.status_code @app.errorhandler(400) def bad_request(error): return jsonify({ "success": False, "error": 400, "message": "Bad Request" }), 400 @app.errorhandler(404) def not_found(error): return jsonify({ "success": False, "error": 404, "message": "Resource Not Found" }), 404 @app.errorhandler(500) def server_error(error): return jsonify({ "success": False, "error": 500, "message": "Internal Server error" }), 500 @app.errorhandler(422) def unprocessable(error): return jsonify({ "success": False, "error": 422, "message": "unprocessable" }), 422 return app