Exemplo n.º 1
0
def create_app(*, config: BaseConfig) -> Flask:
    """Creates flask server from config file and register all associated
    blueprints.

    Args:
        config (BaseConfig): config object that specifies app config

    Returns:
        Flask: Flask app object
    """
    app = flask.Flask(
        __name__,
        static_folder="assets",
    )
    app.config.from_object(config())

    # Setting up SQLAlchemy dB
    app.logger.info(f'Initializing db...')
    db = SQLAlchemy(app)
    from app.model import db
    db.init_app(app)
    app.logger.info(f'Initializiing db complete!')

    app.logger.info(f'Initializing blueprints...')
    register_blueprints(app=app)
    app.logger.info(f'Initializing blueprints complete!')

    return app
Exemplo n.º 2
0
def create_app(config_object=None):
    app = Flask(__name__, instance_relative_config=True)

    # Load the default configuration
    app.config.from_object('config.default')

    # Load the configuration from the instance folder
    app.config.from_pyfile('config.py')

    if config_object:
        app.config.from_object(config_object)
    else:
        # Load the file specified by the APP_CONFIG_FILE environment variable
        # Variables defined here will override those in the default configuration
        app.config.from_envvar('APP_CONFIG_FILE')

    # Register Blueprints
    from app.views import user_blueprint
    app.register_blueprint(user_blueprint,
                           url_prefix=app.config['API_URL_PREFIX'])

    # Register SQLAclchemy DB
    from app.model import db
    db.init_app(app)

    # Register Bcrypt
    from app.provider import bcrypt
    bcrypt.init_app(app)

    return app
Exemplo n.º 3
0
def create_app(test_config=None):
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_mapping(
        SECRETE_KEY='dev',
        SQLALCHEMY_DATABASE_URI='sqlite:///' + os.path.join(app.instance_path, 'app.db'),
        SQLALCHEMY_TRACK_MODIFICATIONS=False
    )

    CORS(app)
    if test_config is None:
        app.config.from_pyfile('config.py', silent=True)
    else:
        app.config.from_mapping(test_config)

    try:
        os.makedirs(app.instance_path)
    except OSError:
        pass

    from app.model import db
    db.init_app(app)

    from flask_restful import Api
    api = Api(app)

    from app.model import migrate
    migrate.init_app(app=app, db=db)

    from app.resource import TicketListResource, TicketResource
    api.add_resource(TicketListResource, '/api/tickets')
    api.add_resource(TicketResource, '/api/tickets/<int:id>')

    return app
Exemplo n.º 4
0
def create_app(configPy):

	# init Flask
	from flask import Flask
	app = Flask(__name__)
	app.config.from_object(configPy)

	# init database
	from app.model import db
	db.app = app
	db.init_app(app)

	# register main blueprint
	from app.main.view import mainBlueprint
	app.register_blueprint(mainBlueprint)

	# register role blueprint
	from app.role.view import roleBlueprint
	app.register_blueprint(roleBlueprint)

	# register user blueprint
	from app.user.view import userBlueprint
	app.register_blueprint(userBlueprint)

	return app
Exemplo n.º 5
0
def create_app():
    app = Flask(__name__, instance_relative_config=True, static_url_path='')
    app.config.from_mapping(
        SECRET_KEY=os.environ.get('SECRET_KEY') or 'you-will-never-guess',
        SQLALCHEMY_DATABASE_URI=os.environ.get('DATABASE_URL')
        or 'sqlite:///' + os.path.join(app.instance_path, 'app.db'),
        SQLALCHEMY_TRACK_MODIFICATIONS=False,
        VCARD_FOLDER=os.path.join(app.instance_path, 'vcf'))

    try:
        os.makedirs(app.instance_path)
        os.makedirs(os.path.join(app.instance_path, 'vcf'))
    except OSError:
        pass

    from flask_sslify import SSLify
    if 'DYNO' in os.environ:
        sslify = SSLify(app)

    from app.model import db, migrate
    db.init_app(app)
    migrate.init_app(app, db)

    from app.controller import pwa, main, auth, user
    app.register_blueprint(pwa.bp)
    app.register_blueprint(auth.bp)
    app.register_blueprint(user.bp)
    app.register_blueprint(main.bp)

    return app
Exemplo n.º 6
0
def create_app():
    app = Flask(__name__, instance_relative_config=True, static_url_path='')
    app.config.from_mapping(
        SECRET_KEY=os.environ.get('SECRET_KEY') or 'you-will-never-guess',
        SQLALCHEMY_DATABASE_URI=os.environ.get('DATABASE_URL')
        or 'sqlite:///' + os.path.join(app.instance_path, 'app.db'),
        SQLALCHEMY_TRACK_MODIFICATIONS=False)

    try:
        os.makedirs(app.instance_path)
    except OSError:
        pass

    cors = CORS(app, resources={r"/list/*": {"origins": "*"}})

    from flask_sslify import SSLify
    if 'DYNO' in os.environ:
        sslify = SSLify(app)

    from app.model import db, ma, migrate
    db.init_app(app)
    ma.init_app(app)
    migrate.init_app(app, db)

    from app.controller import main, api
    app.register_blueprint(main.bp)
    app.register_blueprint(api.bp)

    return app
Exemplo n.º 7
0
def make_app():
    _app = Flask(__name__)
    _app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['DATABASE_URI']
    _app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    db.init_app(_app)
    api.init_app(_app)
    Migrate(app=_app, db=db)
    return _app
Exemplo n.º 8
0
    def init(u, p):
        # 初始化数据库
        db.init_app(app)
        db.create_all(app=app)
        # 新建用户
        new_user = UserModel(name=u, password_hash=UserModel.set_password(p))
        db.session.add(new_user)
        db.session.commit()

        click.echo('Success.')
Exemplo n.º 9
0
def create_app(config):
    app = Flask(__name__,
                static_folder='../static',
                template_folder='../templates')
    app.config.from_object(config)
    db.init_app(app)
    app.register_blueprint(stats, url_prefix='/stats')
    app.register_blueprint(theory, url_prefix='/theory')
    app.add_url_rule('/', 'home_page', home_page)

    return app
Exemplo n.º 10
0
    def setUp(self):

        app = create_app()
        self.app = app
        self.client = app.test_client()

        db.init_app(app)
        db.app = app
        with app.app_context():    
            db.drop_all()
            db.create_all()
Exemplo n.º 11
0
def app(pg_connection, postgres_dsn: str) -> Flask:
    app = Flask("app/main")
    app.register_blueprint(api)
    app.config["SQLALCHEMY_DATABASE_URI"] = postgres_dsn
    app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
    app.config["TESTING"] = True
    migrate = Migrate(app, db)
    db.init_app(app)
    ensure_schema(postgres_dsn)
    insert_data(postgres_dsn)
    yield app
    delete_data(postgres_dsn)
Exemplo n.º 12
0
def run():
    app.host = '0.0.0.0'
    app.port = PORT
    app.debug = True

    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////Users/Jackson/work/web/myblog/database/test.db'
    
    db.init_app(app)
    db.create_all()

    from livereload import Server
    server = Server(app)
    server.serve(port=PORT)
Exemplo n.º 13
0
def create_app():
    app = Flask(__name__)
    app.register_blueprint(route)
    app.register_blueprint(api)
    app.config['SECRET_KEY'] = SECRET_KEY

    app.config['SQLALCHEMY_DATABASE_URI'] = DB_URI
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    db.init_app(app)

    login_manager.init_app(app)

    return app
Exemplo n.º 14
0
def initialize_app(flask_app):
    setup_log()
    configure_app(flask_app)
    blueprint = Blueprint("api", __name__, url_prefix="/api")
    api.init_app(blueprint)
    api.namespaces = []
    api.add_namespace(nqueen)
    flask_app.register_blueprint(web)
    flask_app.register_blueprint(blueprint)
    db.init_app(flask_app)
    with flask_app.app_context():
        log.debug(f"Creating database: {settings.SQLALCHEMY_DATABASE_URI}")
        db.create_all(app=flask_app)
Exemplo n.º 15
0
def create_app(config_name):
    create_log(logging.INFO)
    logger = logging.getLogger(__name__)
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    db.init_app(app)
    # cache.init_app(app,{'CACHE_TYPE':'simple'})
    login_manager.init_app(app)

    from app.project import project_blueprint
    from app.api import api_blueprint
    from app.member import member_blueprint
    from app.case import case_blueprint
    from app.auth import auth

    app.register_blueprint(auth, url_prefix='/auth')
    app.register_blueprint(project_blueprint, url_prefix='/project')
    app.register_blueprint(api_blueprint, url_prefix='/api')
    app.register_blueprint(member_blueprint, url_prefix='/member')
    app.register_blueprint(case_blueprint, url_prefix='/case')

    @app.errorhandler(404)
    def not_found404(err):
        return jsonify({'code': 0, 'msg': 'data not found'})

    @app.before_request
    def before_request():
        g.startTime = time.time()

    @app.after_request
    def after_request(response):
        if current_user is None:
            userId = 'GUEST'
        else:
            # userId = current_user.id
            userId = 'GUEST'
        data = {
            'status_code': response.status_code,
            'method': request.method,
            'userId': userId,
            'ip': request.headers.get('X-Real-Ip', request.remote_addr),
            'url': request.url,
            'referer': request.headers.get('Referer'),
            'agent': request.headers.get('User-Agent'),
            'TimeInterval': '%0.2fs' % float(time.time() - g.startTime)
        }
        logger.info(data)
        return response

    return app
Exemplo n.º 16
0
def create_app():
    from flask import Flask
    app = Flask(__name__, instance_relative_config=True)

    from configuration.development import DevelopmentConfig
    app.config.from_object(DevelopmentConfig)
    app.config.from_pyfile("config.py", silent=True)

    from app.model import db
    db.init_app(app)

    from app.views.home import home
    app.register_blueprint(home, url_prefix='')

    return app
Exemplo n.º 17
0
def create_app(config_class=ProdConfig):
    app = Flask(__name__)
    app.config.from_object(config_class)
    db.init_app(app)
    jwt = JWTManager(app)

    @jwt.token_in_blacklist_loader
    def check_if_token_in_blacklist(decrypted_token):
        jti = decrypted_token['jti']

        return app.model.RevokedTokenModel.is_jti_blacklisted(jti)

    with app.app_context():
        init_db()

    from flask_restful import Api

    from app.api import bp as api_bp
    from app.api.stations import StationResource, StationsResource, StationTripResource
    from app.api.trips import TripResource, TripsResource
    from app.api.auth import UserLogin, UserLogoutAccess, UserLogoutRefresh, UserRegistration, AllUsers, TokenRefresh

    api = Api(api_bp)
    api.add_resource(StationsResource, '/stations')
    api.add_resource(StationResource, '/station/<int:station_id>')
    api.add_resource(StationTripResource, '/station/<int:station_id>/trips')
    api.add_resource(TripResource, '/trip/<int:trip_id>')
    api.add_resource(TripsResource, '/trips')
    api.add_resource(AllUsers, '/users')

    from flask import Blueprint

    auth_bp = Blueprint('auth', 'authentication')
    auth_api = Api(auth_bp)
    auth_api.add_resource(UserRegistration, '/signup')
    auth_api.add_resource(UserLogin, '/login')
    # only access tokens are allowed
    auth_api.add_resource(UserLogoutAccess, '/logout/access')
    # only refresh tokens are allowed
    auth_api.add_resource(UserLogoutRefresh, '/logout/refresh')
    # only refresh tokens are allowed
    auth_api.add_resource(TokenRefresh, '/refresh')

    app.register_blueprint(api_bp, url_prefix='/api')
    app.register_blueprint(auth_bp, url_prefix='/auth')

    return app
Exemplo n.º 18
0
def create_app(config_name):

    app = Flask(__name__)

    app.config.from_object(get_config_by_name(config_name))

    from app.model import db
    db.init_app(app)

    app.app_context().push()

    migrate.init_app(app, db)

    from app.service.api import blueprint
    app.register_blueprint(blueprint, url_prefix='/api')

    return app
Exemplo n.º 19
0
def create_app():
    app = Flask(__name__)
    app.config.from_object(config.DevelopmentConfig)

    from app.model import db
    db.init_app(app)

    from app.model import User, UserRoles, Author, Book, Role
    with app.app_context():
        db.create_all()

    CORS(app)
    api = Api(app)
    create_routes(api)

    # user_manager = UserManager(app, db, User.UserModel)

    return app
Exemplo n.º 20
0
Arquivo: run.py Projeto: andmatt/pongr
def create_app(cache):
    app = Flask(__name__, static_url_path='')
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///pong.db'
    cache.init_app(app)
    compress.init_app(app)
    Bootstrap(app)

    db.init_app(app)
    with app.app_context():
        db.create_all()

        admin = Admin(app, name='pongr', template_mode='bootstrap3')
        admin.add_view(GameView(Game, db.session))
        admin.add_view(DoublesView(DoublesGame, db.session))
        admin.add_view(PlayerView(Player, db.session))
        admin.add_view(RatingsView(Ratings, db.session))

    return app, cache
Exemplo n.º 21
0
def create_app():
    """
    :rtype: Flask
    """
    app = Flask(__name__)
    # 读取配置文件
    app.config.from_object('app.secure')
    # 注册蓝图
    register_blueprint(app)
    # 初始化dao
    db.init_app(app)
    db.create_all(app=app)
    # 初始化flask_login插件
    login.init_app(app)
    login.login_message = '请先注册或登录'
    login.login_view = 'web.login'
    # 初始化mail
    mail.init_app(app)
    return app
Exemplo n.º 22
0
def create_app() -> Flask:
    app = Flask(__name__)
    app.config["SQLALCHEMY_DATABASE_URI"] = os.environ["ARTICLES_DATABASE_URI"]

    from app.model import db, Article

    db.init_app(app)

    def serialize_article(article: Article) -> Dict[str, str]:
        return {"id": article.id, "url": article.url, "date_added": article.date_added}

    @app.route("/")
    def index() -> str:
        return "Articles API"

    @app.route("/articles", methods=["GET"])
    def get_articles() -> Dict[str, Dict[str, str]]:
        articles = Article.query.all()
        return {x.id: serialize_article(x) for x in articles}

    @app.route("/articles/<int:id>", methods=["GET"])
    def get_article(id: int) -> Union[Dict[str, str], Tuple[str, int]]:
        articles = Article.query.all()
        data = {x.id: serialize_article(x) for x in articles}
        try:
            return data[id]
        except KeyError:
            return f"Record not found for id {id}", 400

    @app.route("/articles", methods=["POST"])
    def post_article() -> Dict[str, str]:
        url = request.form.get("url")

        article = Article(url=url, date_added=int(today()))
        db.session.add(article)
        db.session.commit()
        id = article.id

        articles = Article.query.all()
        data = {x.id: serialize_article(x) for x in articles}
        return data[id]

    return app
Exemplo n.º 23
0
def create_app(config="app.config"):

    app = Flask(__name__)
    with app.app_context():
        app.config.from_object(config)

        from app.model import Beautys, db
        if not database_exists(
                app.config['SQLALCHEMY_DATABASE_URI']
        ) and not app.config['SQLALCHEMY_DATABASE_URI'].startswith('sqlite'):
            create_database(app.config['SQLALCHEMY_DATABASE_URI'])

        db.init_app(app)
        db.create_all()
        app.db = db

        from app.fanfan import fanfan
        app.register_blueprint(fanfan)

        return app
Exemplo n.º 24
0
def create_app():
    app = Flask(__name__)
    # 加载配置文件
    app.config.from_object('app.config.secure')
    app.config.from_object('app.config.settings')

    # 加载插件
    register_extensions(app)

    # 初始化数据库
    db.init_app(app)
    db.create_all(app=app)

    # 注册api
    register_api(app)
    api = Api(app)
    # 注册命令
    register_commands(app)
    # 解决跨域请求问题
    CORS(app)
    return app
Exemplo n.º 25
0
def create_app(dev_name=None):
    app = Flask(__name__)
    app.config.from_object(config[dev_name])
    db.init_app(app)
    app.register_blueprint(admin)
    app.register_blueprint(auth)
    app.register_blueprint(blog)
    # 注册登录管理
    login_manager = LoginManager()
    # 初始化
    login_manager.init_app(app)
    # 拦截登录,重定向视图
    login_manager.login_view = "login"
    # 登录验证时LoginManger从数据库加载用户
    login_manager.session_protection = "strong"

    @login_manager.user_loader
    def load_user(uid):
        return User.query.get(int(uid))

    return app
Exemplo n.º 26
0
def create_app(config_name, config_path=None):
    app = Flask(__name__)

    if not config_path:
        pwd = os.getcwd()
        config_path = os.path.join(pwd, 'config/main_config.yaml')
    if not config_name:
        config_name = 'PRODUCTION'

    # 获取配置
    conf = read_yaml(config_name, config_path)
    app.config.update(conf)

    # 读取msg配置
    with open(app.config['RESPONSE_MESSAGE'], 'r', encoding='utf-8') as f:
        msg = yaml.safe_load(f.read())
        app.config.update(msg)

    # 注册接口到蓝图
    register_api(app=app, routers=router)

    # 返回json格式转换
    app.json_encoder = JSONEncoder

    # 数据库初始化
    migrate = Migrate(app, db)
    db.init_app(app)

    # 日志文件目录
    if not os.path.exists(app.config['LOGGING_PATH']):
        os.mkdir(app.config['LOGGING_PATH'])

    # 日志设置
    with open(app.config['LOGGING_CONFIG_PATH'], 'r', encoding='utf-8') as f:
        dict_conf = yaml.safe_load(f.read())
    logging.config.dictConfig(dict_conf)

    return app
Exemplo n.º 27
0
def create_app():

    app = Flask(__name__)

    # app.wsgi_app = CasbinMiddleware(app.wsgi_app)

    app.config.from_object('conf.setting')
    app.config.from_object('conf.secret')

    register_blueprint(app)

    # 注册SQLAlchemy
    db.init_app(app)

    # 注册login模块
    login_manager.init_app(app)
    login_manager.login_view = 'web.login'
    # login_manager.login_message = '请先登录或注册'

    # 注册flask-cache模块
    # cache.init_app(app)

    return app
from flask import Flask
from flask.ext.login import LoginManager
from flask import render_template
from threading import Thread

login_manager = LoginManager()
login_manager.session_protection = 'strong'
login_manager.login_view = 'login'

app = Flask(__name__)
app.config.from_object('config')

from app.model import db
db.init_app(app)  

login_manager.init_app(app)

from flask.ext.mail import Mail, Message

app.config['FLASKY_MAIL_SUBJECT_PREFIX'] = '[Flasky]'
app.config['FLASKY_MAIL_SENDER'] = 'Flasky Admin <*****@*****.**>'
mail = Mail(app)

from flask.ext.moment import Moment
moment = Moment(app)

from model import Permission

@app.context_processor
def inject_permissions():
	return dict(Permission = Permission)
Exemplo n.º 29
0
def create_app(config=None):
    app = Flask(__name__)
    app.config.from_object(config)
    db.init_app(app)
    return app
Exemplo n.º 30
0
def init_ext(app):

    db.init_app(app=app)
    session.init_app(app=app)
Exemplo n.º 31
0
def tdb(app):
    db.init_app(app)
    return db
Exemplo n.º 32
0
from flask import Flask
from flask_script import Manager

from app.model import db
from app.views import blue, mail

app = Flask(__name__)

app.register_blueprint(blueprint=blue, url_prefix='/app')

app.config[
    'SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:[email protected]:3306/flask'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS]'] = False

app.config["MAIL_SERVER"] = "mail.qq.com"
app.config["MAIL_PORT"] = 465  # 设置邮箱端口为465,默认为25,由于阿里云禁止了25端口,所以需要修改
app.config["MAIL_USE_SSL"] = True  # 163邮箱需要开启SSL
app.config["MAIL_USERNAME"] = "******"
app.config["MAIL_PASSWORD"] = "******"

db.init_app(app)
mail.init_app(app)
manager = Manager(app=app)

if __name__ == '__main__':
    manager.run()
Exemplo n.º 33
0
def create_api():
    from flask import Flask
    app = Flask(__name__)
    config = load_config()
    logging.basicConfig(level=config.LOG_LEVEL,
                        format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                        datefmt='[%Y-%m-%d %H:%M:%S]')

    app.config.from_object(config)
    db.init_app(app)

    # 管理端
    from app.api.admin.assets import assets_bp
    app.register_blueprint(assets_bp, url_prefix='/admin/assets')

    from app.api.admin.currency import currency_bp
    app.register_blueprint(currency_bp, url_prefix='/admin/currency')

    from app.api.admin.member import member_bp
    app.register_blueprint(member_bp, url_prefix='/admin/member')

    from app.api.admin.order import order_bp
    app.register_blueprint(order_bp, url_prefix='/admin/order')

    from app.api.admin.payment import payment_bp
    app.register_blueprint(payment_bp, url_prefix='/admin/payment')

    from app.api.admin.setting import setting_bp
    app.register_blueprint(setting_bp, url_prefix='/admin/setting')

    from app.api.admin.team import team_bp
    app.register_blueprint(team_bp, url_prefix='/admin/team')

    from app.api.admin.user import user_bp
    app.register_blueprint(user_bp, url_prefix='/admin/user')

    from app.api.admin.news import news_bp
    app.register_blueprint(news_bp, url_prefix='/admin/news')

    # 会员端
    from app.api.member.assets import assets_bp
    app.register_blueprint(assets_bp, url_prefix='/member/assets')

    from app.api.member.currency import currency_bp
    app.register_blueprint(currency_bp, url_prefix='/member/currency')

    from app.api.member.order import order_bp
    app.register_blueprint(order_bp, url_prefix='/member/order')

    from app.api.member.payment import payment_bp
    app.register_blueprint(payment_bp, url_prefix='/member/payment')

    from app.api.member.setting import setting_bp
    app.register_blueprint(setting_bp, url_prefix='/member/setting')

    from app.api.member.team import team_bp
    app.register_blueprint(team_bp, url_prefix='/member/team')

    from app.api.member.news import news_bp
    app.register_blueprint(news_bp, url_prefix='/member/news')

    from app.api.member.upload import upload_bp
    app.register_blueprint(upload_bp, url_prefix='/member/upload')

    from app.api.member.user import user_bp
    app.register_blueprint(user_bp, url_prefix='/member/user')

    # 测试用
    from app.api.test import test
    app.register_blueprint(test)

    from app.api.pin_code import pin_code_bp
    app.register_blueprint(pin_code_bp)

    from app.api.qr_code import qr_code_bp
    app.register_blueprint(qr_code_bp)

    return app