Exemplo n.º 1
1
def create_app(config=None, blueprints=None):
    """
    Create and initialise the application.
    """
    app = Flask(__name__)
    app.config.from_pyfile("%s/config/default.py" % app.root_path)
    app.url_map.converters["regex"] = RegexConverter

    app.add_template_filter(slugify)

    if blueprints is None:
        blueprints = DEFAULT_BLUEPRINTS

    configure_blueprints(app, blueprints)

    return app
Exemplo n.º 2
0
def create_app(config_name):
    app = Flask(__name__)

    app.config.from_object(config_dict[config_name])

    # 使用session
    Session(app)
    # 通过函数调用,让db和程序实例进行关联
    db.init_app(app)

    # 项目开启csrf保护
    CSRFProtect(app)
    # 生成csrf_token,写入到客户端浏览器的cookie中
    # 请求钩子,在每次请求后都会执行
    @app.after_request
    def after_request(response):
        csrf_token = csrf.generate_csrf()
        response.set_cookie("csrf_token", csrf_token)
        return response

    # 导入蓝图对象,注册蓝图
    from info.modules.news import api
    app.register_blueprint(api)

    # 导入蓝图对象,注册蓝图
    from info.modules.passport import passport_blue
    app.register_blueprint(passport_blue)

    #导入过滤器
    from info.utils.conmos import index_filter
    app.add_template_filter(index_filter, "index_filter")
    return app
def create_app(config_name):

    application = Flask(__name__,
                        static_folder='static/',
                        static_url_path=configs[config_name].ASSET_PATH)

    init_app(
        application,
        configs[config_name],
        bootstrap=bootstrap,
        data_api_client=data_api_client,
        login_manager=login_manager
    )

    application.permanent_session_lifetime = timedelta(hours=1)
    from .main import main as main_blueprint
    from .status import status as status_blueprint

    url_prefix = application.config['URL_PREFIX']
    application.register_blueprint(status_blueprint, url_prefix=url_prefix)
    application.register_blueprint(main_blueprint, url_prefix=url_prefix)
    login_manager.login_view = 'main.render_login'
    main_blueprint.config = application.config.copy()

    init_frontend_app(application, data_api_client, login_manager)

    application.add_template_filter(parse_document_upload_time)

    @application.context_processor
    def extra_template_variables():
        return {
            'generic_contact_email': application.config['GENERIC_CONTACT_EMAIL'],
        }

    return application
Exemplo n.º 4
0
def create_app(config):

    app = Flask(__name__)

    # 使用配置信息
    app.config.from_object(config_dict[config])

    # 创建sqlalchemy实例对象
    # db = SQLAlchemy(app)
    db.init_app(app)

    # 实例化session
    Session(app)
    CSRFProtect(app)

    @app.after_request
    def after_request(respnose):
        csrf_token = csrf.generate_csrf()
        respnose.set_cookie('csrf_token', csrf_token)
        return respnose

    # 导入蓝图,注册蓝图
    from info.modules.news import news_blue
    app.register_blueprint(news_blue)
    # 注册蓝图 表单
    from info.modules.passport import passport_blue
    app.register_blueprint(passport_blue)

    from info.utils.commons import index_filter
    app.add_template_filter(index_filter, 'index_filter')

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

    application = Flask(__name__,
                        static_folder='static/',
                        static_url_path=configs[config_name].STATIC_URL_PATH)

    init_app(
        application,
        configs[config_name],
        bootstrap=bootstrap,
        data_api_client=data_api_client,
        feature_flags=feature_flags,
        login_manager=login_manager
    )
    # Should be incorporated into digitalmarketplace-utils as well
    csrf.init_app(application)

    application.permanent_session_lifetime = timedelta(hours=1)
    from .main import main as main_blueprint
    from .status import status as status_blueprint

    application.register_blueprint(status_blueprint, url_prefix='/admin')
    application.register_blueprint(main_blueprint, url_prefix='/admin')
    login_manager.login_view = 'main.render_login'
    main_blueprint.config = application.config.copy()

    @application.before_request
    def remove_trailing_slash():
        if request.path != '/' and request.path.endswith('/'):
            return redirect(request.path[:-1], code=301)

    application.add_template_filter(parse_document_upload_time)

    return application
Exemplo n.º 6
0
def create_app(config_name):
    app = Flask(__name__)

    class_name = config_map.get(config_name)

    app.config.from_object(class_name)
    db.init_app(app)
    global redis_store
    # 当前这个redis是用来存储对象用的
    redis_store = redis.StrictRedis(host=class_name.REDIS_HOST,
                                    port=class_name.REDIS_PORT,
                                    decode_responses=True)

    # 设置session
    Session(app)
    # 开启CSRF保护
    CSRFProtect(app)

    # 往浏览器写入csrf_token
    @app.after_request
    def after_request(response):
        # 调用函数生成 csrf_token
        csrf_token = generate_csrf()
        # 通过 cookie 将值传给前端
        response.set_cookie("csrf_token", csrf_token)
        return response

    from info.utils.common import index_class
    app.add_template_filter(index_class, "indexClass")
    from info.utils.common import user_login_data
    # 当前的404页面表示全局所有的,所以把当前代码写到__init__
    # errorhandler:表示捕获http异常
    @app.errorhandler(404)
    @user_login_data
    def not_found(e):
        user = g.user
        data = {"user_info": user.to_dict() if user else None}
        return render_template("news/404.html", data=data)

    # 这个下面会放置所有的蓝图
    from info.index import index_blue
    app.register_blueprint(index_blue)

    # 这个下面会放置所有的蓝图
    from info.passport import passport_blue
    app.register_blueprint(passport_blue)

    # 这个下面会放置所有的蓝图
    from info.news import news_blue
    app.register_blueprint(news_blue)

    # 这个下面会放置所有的蓝图
    from info.user import profile_blue
    app.register_blueprint(profile_blue)

    # 这个下面会放置所有的蓝图
    from info.admin import admin_blue
    app.register_blueprint(admin_blue)

    return app
Exemplo n.º 7
0
def create_app(config_type,):
    config_class = config_dict.get(config_type)
    app = Flask(__name__)
    app.config.from_object(config_class)
    global db, sr

    db = SQLAlchemy(app)
    sr = StrictRedis(host=Config.REDIS_HOST, port=Config.REDIS_PORT,decode_responses=True)
    # 创建session存储对象
    Session(app)
    Migrate(app, db)

    from info.modules.passport import passport_blu
    app.register_blueprint(passport_blu)
    from info.modules.home import home_blu
    app.register_blueprint(home_blu)
    from info.modules.news import news_blu
    app.register_blueprint(news_blu)

    setup_log(config_class.LOG_LEVEL)
    # 管理表模型文件
    import info.models
    # 在utils中定义的函数想要变成过滤器,需要在app中注册,并且转换成过滤器
    from info.utils.common import func_index_convert
    app.add_template_filter(func_index_convert,"index_convert")

    return app
Exemplo n.º 8
0
def create_app(config_name):
    app = Flask(__name__)

    CSRFProtect(app)
    # 加载配制
    app.config.from_object(config[config_name])

    Session(app)
    db.init_app(app)

    @app.after_request
    def after_request(resp):
        csrf_token = csrf.generate_csrf()
        resp.set_cookie('csrf_token', csrf_token)
        return resp

    from info.utils.commons import index_class
    app.add_template_filter(index_class, 'index_class')

    # 注册蓝图
    from info.modules.index import index_blue
    app.register_blueprint(index_blue)
    from info.modules.passport import passport_blue
    app.register_blueprint(passport_blue, url_prefix="/passport")
    from info.modules.news import news_blue
    app.register_blueprint(news_blue)
    from info.modules.user import user_blue
    app.register_blueprint(user_blue)
    from info.modules.admin import admin_blue
    app.register_blueprint(admin_blue)

    return app
Exemplo n.º 9
0
def creat_app(ms="ts"):
    global db, rs
    app = Flask(__name__)
    app.config.from_object(zd[ms])
    db = SQLAlchemy(app=app)
    rs = StrictRedis(host=zd[ms].REDIS_HOST, port=zd[ms].REDIS_PORT)
    Session(app=app)
    app.add_template_filter(djpmglq, name='cssxz')
    # print(zd[ms].DEBUG)

    #scrf 开启
    CSRFProtect(app)
    from csh import models
    #开启日志
    setup_log()
    # @app.errorhandler(404)
    # def cwxd(e):
    #     return render_template('news/404.html')
    @app.after_request
    def szscrf(resp):
        token = generate_csrf()
        # session['field_name']=token
        # resp.headers['X-CSRFToken'] = token
        resp.set_cookie('X-CSRFToken', token)
        return resp

    # @app.after_request
    # def after_request(response):
    #     from flask_wtf.csrf import generate_csrf
    #     token = generate_csrf()
    #
    #     response.set_cookie('csrf_token', token)
    #
    #     return response
    return app, db
Exemplo n.º 10
0
def add_template_filters(app: Flask):
    """
    注册自定义模板验证器
    :param app: Flask 核心对象
    :return: None
    """
    app.add_template_filter(switch_link_tag)
Exemplo n.º 11
0
def create_app(config_name):
    #初始化flask对象
    app = Flask(__name__)
    #根据字典的key,获取到字典的value
    config_class = config_map.get(config_name)

    #将配置文件添加到flask对象中
    app.config.from_object(config_class)

    db.init_app(app)
    # 初始化数据库对象
    # db = SQLAlchemy(app)
    # 创建redis(存储验证码,存储短信验证码和图片验证码) 第一个参数ip 第二个参数端口,第三个参数表示解码,在redis里面进行操作,用来取数据的时候,byte,string
    global redis_store
    redis_store = redis.StrictRedis(host=config_class.REDIS_HOST,
                                    port=config_class.REDIS_PORT,
                                    decode_responses=True)
    # 导入session:目的用来进行持久化操作,不需要每次都让用户进行登陆,我们需要把session存储到redis当中
    Session(app)
    # 开启CSRF保护,把整个flask对象丢进去,需要添加一个SECRET_KEY秘钥
    CSRFProtect(app)

    @app.after_request
    def after_request(response):
        # 调用函数生成 csrf_token
        csrf_token = generate_csrf()
        # 通过cookie将值传递给前端
        response.set_cookie("csrf_token", csrf_token)
        return response

    # 添加自定义过滤器
    from info.utils.common import do_index_class
    app.add_template_filter(do_index_class, "indexClass")

    from info.utils.common import user_login_data

    @app.errorhandler(404)
    @user_login_data
    def error_404_handler(error):
        user = g.user
        data = {"user_info": user.to_dict() if user else None}
        return render_template("news/404.html", data=data)

    # 注册首页的蓝图
    from info.index import index_blue
    app.register_blueprint(index_blue)
    # 登陆注册的蓝图
    from info.passport import passport_blue
    app.register_blueprint(passport_blue)
    # 新闻详情的蓝图
    from info.news import news_blue
    app.register_blueprint(news_blue)
    # 个人中心的蓝图
    from info.user import profile_blue
    app.register_blueprint(profile_blue)
    # 后台管理系统蓝图
    from info.admin import admin_blue
    app.register_blueprint(admin_blue)

    return app
Exemplo n.º 12
0
Arquivo: app.py Projeto: yarons/newdle
def create_app(config_override=None, use_env_config=True):
    app = Flask('newdle')
    _configure_app(app, from_env=use_env_config)
    if config_override:
        app.config.update(config_override)
    if not app.config['SKIP_LOGIN']:
        _configure_multipass(app)
    _configure_db(app)
    _configure_errors(app)
    cache.init_app(app)
    mm.init_app(app)
    app.add_template_filter(dedent)
    app.register_blueprint(api)
    app.register_blueprint(auth)
    app.register_blueprint(cli)
    app.add_url_rule('/', 'index', build_only=True)
    app.add_url_rule('/newdle/<code>', 'newdle', build_only=True)
    app.add_url_rule('/newdle/<code>/<participant_code>',
                     'newdle',
                     build_only=True)
    app.add_url_rule('/newdle/<code>/summary',
                     'newdle_summary',
                     build_only=True)
    app.add_url_rule('/logo_color.svg', 'logo', build_only=True)
    return app
Exemplo n.º 13
0
def create_app(config_name):
    # 配置项目日志
    setup_log(config_name)
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    # 初始化一个sqlALchemy对象
    db.init_app(app)
    # 创建redis存储对象
    global redis_store
    redis_store = StrictRedis(host=config[config_name].REDIS_HOST,
                              port=config[config_name].REDIS_PORT,
                              decode_responses=True)
    # 开启CSRF保护
    CSRFProtect(app)
    # 设置session保存指定位置
    Session(app)
    # 将自己定义的过滤器添加到app中
    app.add_template_filter(do_index_class, "index_class")

    @app.after_request
    def after_request(response):
        # 生成随机的csrf_token
        csrf_token = generate_csrf()
        # 设置cookie
        response.set_cookie("csrf_token", csrf_token)
        return response

    # 将蓝图注册到app里
    from info.modules.index import index_blu
    app.register_blueprint(index_blu)

    from info.modules.passport import passport_blu
    app.register_blueprint(passport_blu)
    # 切记一定要返回一个app,否则创建不成功
    return app
Exemplo n.º 14
0
def create_app(config_name):
    # 0日志
    setup_log(config_name)
    # 1创建app对象
    app = Flask(__name__)
    app.config.from_object(config_dict[config_name])
    # 2创建db对象
    # db = SQLAlchemy(app)
    db.init_app(app)
    # 3创建redis_store对象
    global redis_store
    redis_store = StrictRedis(host=config_dict[config_name].REDIS_HOST, port=config_dict[config_name].REDIS_PORT,
                              decode_responses=True)
    # 4csrf包含请求体都需要csrf,保护
    CSRFProtect(app)
    # 添加自定义过滤器
    app.add_template_filter(set_rank_class, "set_rank_class")

    # 借助钩子函数请求完毕页面显示的时候就在cookie中设置csrf_token
    @app.after_request
    def after_request(response):  # 请求结束后来调用
        # 1. 生成csrf_token随机值
        csrf_token = generate_csrf()
        # 2. 借助response响应对象值设置到cookie中
        response.set_cookie("csrf_token", csrf_token)
        # 3. 返回响应对象
        return response

    # 5Session将数据存放到redis中
    Session(app)

    # 3 注册蓝图
    # 注册蓝图的时候再使用,可以避免循环导入
    from info.module.index import index_bp
    app.register_blueprint(index_bp)

    # 注册登陆蓝图
    from info.module.password import passport_bp
    app.register_blueprint(passport_bp)

    # 注册新闻详情蓝图
    from info.module.news import news_detail_bp
    app.register_blueprint(news_detail_bp)

    # 注册用户个人中心蓝图
    from info.module.profile import profile_bp
    app.register_blueprint(profile_bp)

    # 注册管理员蓝图
    from info.module.admin import admin_bp
    app.register_blueprint(admin_bp)

    @app.errorhandler(404)
    @user_login_data
    def handler(e):
        user = g.user
        data = {"user_info": user.to_dict() if user else None}
        return render_template("news/404.html", data=data)

    return app
Exemplo n.º 15
0
def create_app(config_name):
    '''通过传入不同配置名i,初始化器对应配置的应用实例'''
    #  配置日志,并且传入配置名字,以便获取到指定配置所对应的日志等级
    setup_log(config_name)
    # 创建 Flask 对象
    app = Flask(__name__)

    # 加载配置
    app.config.from_object(Config[config_name])
    # 配置数据库
    db.init_app(app)
    # 配置redis
    global redis_store
    redis_store = StrictRedis(host=Config[config_name].REDIS_HOST,
                              port=Config[config_name].REDIS_PORT,
                              decode_responses=True)
    # 开启当前项目 CSRF 保护,制作服务器验证功能
    # 帮我们做了:从 cookie 中取出随机值,从表单中取出随机值,然后进行校验,并且响应校验结果
    # 我们需要做:1.在界面加载的时候,往 cookie 中添加一个csrf_token 并且在表单中添加一个隐藏的csrf_token
    CSRFProtect(app)
    # 设置session的保存位置
    Session(app)

    from info.utils.common import do_index_class
    app.add_template_filter(do_index_class, 'index_class')
    # 注册蓝图
    from info.utils.common import user_login_data

    @app.errorhandler(404)
    @user_login_data
    def page_not_found(e):
        user = g.user
        data = {"user": user.to_dict() if user else None}
        return render_template('news/404.html', data=data)

    @app.after_request
    def after_request(response):
        # 生成一个随机的 csrf_token 的值
        csrf_token = generate_csrf()
        # 设置一个 cookie
        response.set_cookie('csrf_token', csrf_token)
        return response

    # 添加模板过滤器

    from info.modules.index import index_blu
    app.register_blueprint(index_blu)

    from info.modules.passport import passport_blu
    app.register_blueprint(passport_blu)

    from info.modules.news import news_blu
    app.register_blueprint(news_blu)

    from info.modules.admin import admin_blu
    app.register_blueprint(admin_blu, url_prefix="/admin")

    from info.modules.profile import profile_blu
    app.register_blueprint(profile_blu)
    return app
Exemplo n.º 16
0
def create_app(config_name):
    """创建app工厂方法"""

    setup_log(configs[config_name].LEVEL_LOG)

    app = Flask(__name__)
    # 获取配置信息
    app.config.from_object(configs[config_name])

    # 创建连接数据库对象
    db.init_app(app)
    #创建连接到redis 数据库的对象
    global redis_store
    redis_store = StrictRedis(host=configs[config_name].REDIS_HOST,
                              port=configs[config_name].REDIS_PORT,
                              decode_responses=True)

    #开启CSRF保护
    CSRFProtect(app)

    #
    @app.after_request
    def setip_csrftoken(response):
        csrf_token = generate_csrf()
        response.set_cookie('csrf_token', csrf_token)
        return response

    #将自定义的过滤器函数,添加到app的过滤器列表中
    #rank在模版中使用的别名
    from info.utils.comment import do_rank
    app.add_template_filter(do_rank, 'rank')

    # from info.utils.comment import user_login_data
    @app.errorhandler(404)
    # @user_login_data
    def page_not_found(e):
        # user  = g.user
        context = {
            # 'user':user.to_dict() if user else None
        }
        return render_template('news/404.html', context=context)

    # 将session数据存储在后端的位置
    Session(app)
    from info.modules.index import index_blue
    # 注册路由
    # from info.modules.index import index_blue
    app.register_blueprint(index_blue)
    from info.modules.passport import passport_blue
    # 注册路由
    # from info.modules.index import index_blue
    app.register_blueprint(passport_blue)

    from info.modules.news import news_blue
    app.register_blueprint(news_blue)
    from info.modules.user import user_blue
    app.register_blueprint(user_blue)
    from info.modules.admin import admin_blue
    app.register_blueprint(admin_blue)
    return app
Exemplo n.º 17
0
def create_app(config_name):  # config_name=development  main.py中的参数
    from app.views.index import index_blu
    from app.views.admin import admin_blu
    from app.views.passport import passport_blu
    from app.views.user import user_blu
    from app.views.news import news_blu

    # 创建flask应用程序
    app = Flask(__name__)

    # 对flask对象进行配置
    app.config.from_object(CONFIG.get(config_name))

    # 注册蓝图
    app.register_blueprint(index_blu)
    app.register_blueprint(admin_blu, url_prefix="/admin")
    app.register_blueprint(passport_blu, url_prefix="/passport")
    app.register_blueprint(user_blu, url_prefix="/user")
    app.register_blueprint(news_blu, url_prefix="/news")
    # 创建SQLAlchemy对象
    # db = SQLAlchemy(app)  # 需要将创建的flask对象当做参数进行传递,它会自动与flask对象进行关联
    # 应用程序初始化
    # 与此数据库设置一起使用
    # 对db进行配置
    db.init_app(app)

    # 注册过滤器
    app.add_template_filter(show_index_colorful,
                            "show_index_colorful")  # 后面的名字代表了使用过滤器的名字

    return app
Exemplo n.º 18
0
def con(conf):
    Longing(conf)
    app = Flask(__name__)
    app.config.from_object(deta_config[conf])
    # 创建redis连接对象
    global session_redis
    session_redis = StrictRedis(host=deta_config[conf].REDIS_HOST, port=deta_config[conf].REDIS_PORT,decode_responses=True)
    from .modules.index import blu
    app.register_blueprint(blu)
    from .modules.passport import passport_blue
    app.register_blueprint(passport_blue)
    from .modules.news import news_blue
    app.register_blueprint(news_blue)
    from info.utils.comment import do_rank
    app.add_template_filter(do_rank,'rank')
    Session(app)
    CSRFProtect(app)
    @app.after_request
    def after(respose):
        # 生成csrf随机值
        csrf_token = csrf.generate_csrf()
        # 将csrf_toke写入cookie
        respose.set_cookie('csrf_token',csrf_token)
        return respose

    db.init_app(app)
    return app
Exemplo n.º 19
0
def set_config(config_name):
    set_logging(config_name)
    app = Flask(__name__)
    # 1、集成配置类
    app.config.from_object(config[config_name])
    # 2、集成sqlalchemy
    db.init_app(app)
    # 3、集成redis
    global redis_store
    redis_store = StrictRedis(host=config[config_name].REDIS_HOST, port=config[config_name].REDIS_PORT, decode_responses=True)
    # 4、集成CSRFProtect
    @app.after_request
    def akter_request(response):
        csrf_token = generate_csrf()
        response.set_cookie("csrf_token", csrf_token)
        return response

    CSRFProtect(app)
    # 5、集成flask_session
    # 说明:flask中Session是用户保存用户数据的容器(上下文),而flask_session是指定session指定保存路径
    Session(app)

    # 添加过滤器
    app.add_template_filter(do_index_class, "index_class")

    # 为避免循环导入,注册蓝图,随时使用随时调用
    from info.modules.index import index_blu
    app.register_blueprint(index_blu)
    from info.modules.passport import passport_blu
    app.register_blueprint(passport_blu)

    return app
Exemplo n.º 20
0
def create_app(config_name):
    app = Flask(__name__)

    nowConfig = config_map.get(config_name)

    app.config.from_object(nowConfig)

    db.init_app(app)
    global redis_store
    redis_store = redis.StrictRedis(host=nowConfig.REDIS_HOST,
                                    port=nowConfig.REDIS_PORT,
                                    decode_responses=True)

    Session(app)

    app.add_template_filter(specify_style, "specify_style")

    @app.after_request
    def after_request(response):
        csrf_token = generate_csrf()
        response.set_cookie("csrf_token", csrf_token)
        return response

    from info.utils.common import user_login_data

    @app.errorhandler(404)
    @user_login_data
    def page_not_found(response):
        user = g.user
        data = {"user_info": user.to_dict() if user else None}
        return render_template('news/404.html', data=data)

    CSRFProtect(app)

    return app
def create_app(config_name):

    application = Flask(__name__,
                        static_folder='static/',
                        static_url_path=configs[config_name].STATIC_URL_PATH)

    init_app(application,
             configs[config_name],
             bootstrap=bootstrap,
             data_api_client=data_api_client,
             feature_flags=feature_flags,
             login_manager=login_manager)
    # Should be incorporated into digitalmarketplace-utils as well
    csrf.init_app(application)

    application.permanent_session_lifetime = timedelta(hours=1)
    from .main import main as main_blueprint
    from .status import status as status_blueprint

    application.register_blueprint(status_blueprint, url_prefix='/admin')
    application.register_blueprint(main_blueprint, url_prefix='/admin')
    login_manager.login_view = 'main.render_login'
    main_blueprint.config = application.config.copy()

    @application.before_request
    def remove_trailing_slash():
        if request.path != '/' and request.path.endswith('/'):
            return redirect(request.path[:-1], code=301)

    application.add_template_filter(parse_document_upload_time)

    return application
Exemplo n.º 22
0
def create_app(config_name):
    app = Flask(__name__)
    config = Config_dict[config_name]
    #调用日志方法
    log_file(config.LEVEL)
    app.config.from_object(config)
    db.init_app(app)
    global redis_store
    redis_store = redis.StrictRedis(host=Config.REDIS_HOST,
                                    port=Config.REDIS_PORT,
                                    decode_responses=True)
    Session(app)
    #开启CSRF保护之后,会对[POST,'PUT','PATCH','DELETE]类型的请求方法做校验
    #获取cookie中的csrfToken,获取headers请求头里的csrfToken做校验
    #开发者需要手动设置cookie和headers中的csrfToken
    #设置CSRF程序保护
    CSRFProtect(app)
    #首页蓝图注册app
    from info.modules.index import index_blu
    app.register_blueprint(index_blu)
    #验证蓝图注册app
    from info.modules.passport.views import passport_blu
    app.register_blueprint(passport_blu)

    #设置请求钩子afterrequest,每次请求完成之后,都会走该钩子装饰的方法
    @app.after_request
    def after_request(resp):
        #由CSRFProtect提供的一个generate_csrf方法生成csrf_token
        csrf_token = generate_csrf()
        resp.set_cookie("csrf_token", csrf_token)
        return resp

    #将过滤器添加到模板过滤器当中
    app.add_template_filter(do_index_filter, "index_filter")
    return app
Exemplo n.º 23
0
def app_factory(extra_config=None):
    """Builds the flask application"""
    app = Flask(__name__)

    # App defaults
    app.config.update(dict(
        DEBUG=True,
        CLEANCSS_EXTRA_ARGS=['--skip-rebase'],
        FLATPAGES_ROOT='blog',
        FLATPAGES_EXTENSION='.md',
        FLATPAGES_MARKDOWN_EXTENSIONS=['codehilite', JavierExtensions()],
        FLATPAGES_AUTO_RELOAD=True))
    # Extra config
    if extra_config:
        app.config.update(extra_config)

    # Blueprints
    app.register_blueprint(BLOG, url_prefix='/blog')
    app.register_blueprint(INDIVIDUAL)
    app.register_blueprint(FEEDS)

    # Other configuration
    app.context_processor(template_settings)
    app.add_template_filter(l10n_date)
    register_assets(app)
    register_pages(app)
    return app
Exemplo n.º 24
0
def create_app():
    """Create an instance of the app."""
    app = Flask(__name__)

    # Load the app configuration
    app.config.update(config.get_app_config("default"))
    app.config.update(config.get_app_config(app.config["ENV"]))

    # Put the app secret key into the expected key
    app.config["SECRET_KEY"] = app.config["SECRET_KEY_ADMIN"]
    del app.config["SECRET_KEY_ADMIN"]

    # Load the extensions
    init_extensions(app)

    # Load any injection/special app handler methods
    with app.app_context():
        import_module("src.middleware")

    # Register all of the blueprints
    for bp in all_blueprints:
        import_module(bp.import_name)
        app.register_blueprint(bp)

    # Register the filters
    for name, method in ALL_FILTERS.items():
        app.add_template_filter(method, name=name)

    return app
Exemplo n.º 25
0
def create_app(config_style):
    app = Flask(__name__)
    Config = config_dic.get(config_style)
    app.config.from_object(Config)
    db.init_app(app)
    global redis_store
    redis_store = redis.StrictRedis(host=Config.REDIS_HOST,
                                    port=Config.REDIS_PORT,
                                    decode_responses=True)
    Session(app)

    CSRFProtect(app)

    @app.after_request
    def create_csrf(resp):
        csrf_token = generate_csrf()
        resp.set_cookie("csrf_token1", csrf_token)
        return resp

    from Information.news import news_bluprt
    app.register_blueprint(news_bluprt)

    from Information.utils.common import class_filter
    app.add_template_filter(class_filter, "classtrans")

    from Information.passport import passport_blueprint
    app.register_blueprint(passport_blueprint)

    from Information.HomePage import blueprint_objt
    app.register_blueprint(blueprint_objt)

    return app
Exemplo n.º 26
0
def create_app(config_name):
    """通过传入不通的配置名字, 初始化其对应的应用实例"""
    setup_log(config_name)
    app = Flask(__name__)
    app.config.from_object(Config)
    db.init_app(app)
    global redis_store
    redis_store = redis.StrictRedis(host=Config.REDIS_HOST,
                                    port=Config.REDIS_PORT)
    CSRFProtect(app)
    Session(app)

    @app.after_request
    def after_Request(response):
        # 生成随机的csrf_token值
        csfr_token = generate_csrf()
        response.set_cookie("csrf_token", csfr_token)
        return response

    # 注册蓝图
    from info.modules.index import index_blu
    app.register_blueprint(index_blu)
    from info.modules.passport import passport_blu
    app.register_blueprint(passport_blu)
    from info.utils.common import do_index_class
    app.add_template_filter(do_index_class, "index_class")
    from info.modules.news import news_blu
    app.register_blueprint(news_blu)
    from info.modules.profile import profile_blu
    app.register_blueprint(profile_blu)

    return app
Exemplo n.º 27
0
def init_app(app: Flask) -> None:
    @app.context_processor
    def _inject_logged_in():  # 是否已登录
        logged_in = session.get('logged_in', False)
        return dict(logged_in=logged_in)

    app.add_url_rule('/', 'home', home)
    app.add_url_rule('/favicon.ico', 'favicon', favicon)
    app.add_url_rule('/add', 'add', add, methods=['GET', 'POST'])
    app.add_url_rule('/delete/<int:id>', 'delete', delete)
    app.add_url_rule('/update/<int:id>',
                     'update',
                     update,
                     methods=['GET', 'POST'])
    app.add_url_rule('/detail/<int:id>', 'detail', detail)
    app.add_url_rule('/login', 'login', login, methods=['GET', 'POST'])
    app.add_url_rule('/logout', 'logout', logout)
    app.add_url_rule('/change_key',
                     'change_key',
                     change_key,
                     methods=['GET', 'POST'])
    app.add_url_rule('/about', 'about', about)

    app.before_request(before_request)
    app.after_request(after_request)

    app.add_template_filter(_jinja2_filter_datetime, 'strftime')

    app.register_error_handler(404, not_found)
Exemplo n.º 28
0
def create_app(app_mode='DEBUG'):
    """ Create application, register blueprints, etc """
    if app_mode == '':
        app_mode = os.environ.get('APP_MODE', 'DEBUG')
    # create an application
    app = Flask(__name__)
    app.config['SECRET_KEY'] = b'\x88~\x17h\xdc;,\x9f\x1do\x98\xcd\xaf|\x1c\x19\xec\xcf\xb1\x12\xd4\x8b\xcdQ'
    # set logging
    configure_logging(app_mode, app)
    if app_mode == 'DEBUG':
        # debugging in VSCode works only if following 2 lines are commented out
        #app.debug = True
        #app.config['DEBUG'] = True
        app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0
    # register blueprints
    app.register_blueprint(public_ui)
    app.register_blueprint(member_ui)
    app.register_blueprint(customer_ui)
    # register jinja exts
    app.add_template_filter(f=points, name='points')
    # configure uploads
    app.config['UPLOAD_FOLDER'] = os.path.join(BASE_DIR, 'uploads')
    # app started
    logging.info('Application started in %s mode', app_mode)
    return app
Exemplo n.º 29
0
def create_app(config_name):
    """通过传入不同的配置名字,初始化其对应配置的应用实例"""
    setup_log(config_name)
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    db.init_app(app)
    global redis_store
    redis_store = redis.StrictRedis(host=config[config_name].REDIS_HOST,
                                    port=config[config_name].REDIS_PORT,
                                    decode_responses=True)
    CSRFProtect(app)
    Session(app)
    app.add_template_filter(do_index_class, "index_class")

    from info.module.index import index_blu
    from info.module.passport import passport_blu
    from info.module.news import news_blu
    from info.module.profile import profile_blu
    from info.module.admin import admin_blu
    app.register_blueprint(news_blu)
    app.register_blueprint(index_blu)
    app.register_blueprint(passport_blu)
    app.register_blueprint(profile_blu)
    app.register_blueprint(admin_blu)

    @app.errorhandler(404)
    @user_login_data
    def page_not_found(_):
        user = g.user
        data = {"user_info": user.to_dict() if user else None}
        return render_template('news/404.html', data=data)

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

    app.config.from_mapping(SECRET_KEY='AplikacjaDlaStasia',
                            DATABASE=os.path.join(app.root_path, '..',
                                                  'db.sqlite'),
                            SITE_NAME='Zeton')

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

    app.teardown_appcontext(db.close_db)

    app.add_template_filter(jinja2_ban_datetime_filter, 'ban_time')

    app.register_blueprint(auth.bp)
    app.register_blueprint(views.bp)
    app.register_blueprint(api.bp)
    app.register_blueprint(errors.bp)

    app.before_request(users.load_logged_in_user_data)

    return app
Exemplo n.º 31
0
def create_app():  # create_app 返回的app没有传入到app.py中, 成为导致配置属性未生效的原因
    app = Flask(__name__)
    app.config.from_object(config)  # 从一个对象里面导入
    # 初始化 db
    # 配置文件的加载需要放在前面
    db.init_app(app)
    # 初始化配置文件
    # migrate init
    migrate = Migrate(app, db)
    # migrate.init_app(app, db)

    # 自定义的错误处理机制
    # 模板过滤器
    # ------7.11----------
    # 蓝图定义之后需要注册  蓝图只需要使用一次,则即用即导入,避免出现循环导入
    from app.web import web
    app.register_blueprint(web)
    # -------7.13
    # 添加过滤器
    app.add_template_filter(str_time)

    # csrf  flask 的任何插件在使用的时候都要与app进行绑定
    # 代码的话就是任何插件都会有init_app方法来进行绑定初始化
    csrf.init_app(app)
    return app
Exemplo n.º 32
0
def create_app(config_name):
    setup_log(config_name)

    app = Flask(__name__)

    app.config.from_object(config[config_name])

    db.init_app(app)

    global redis_store
    redis_store = StrictRedis(host=config[config_name].REDIS_HOST,
                              port=config[config_name].REDIS_PORT,
                              decode_responses=True)

    CSRFProtect(app)

    Session(app)

    app.add_template_filter(do_index_class, "index_class")

    @app.after_request
    def after_request(response):
        csrf_token = generate_csrf()
        response.set_cookie("csrf_token", csrf_token)
        return response

    from info.modules.index import index_blu
    app.register_blueprint(index_blu)

    from info.modules.passport import passport_blu
    app.register_blueprint(passport_blu)

    return app
Exemplo n.º 33
0
def create_app(config_name):
    set_log(config_name)
    app = Flask(__name__)
    app.secret_key = "sadfasdf"
    app.config.from_object(config[config_name])
    # 初始化数据库对象
    db.init_app(app)
    global redis_store
    redis_store = redis.StrictRedis(host=config[config_name].REDIS_HOST,
                                    port=config[config_name].REDIS_PORT,
                                    decode_responses=True)
    # 开启csrf
    CSRFProtect(app)
    # 在响应后设置csrftoken
    @app.after_request
    def after_request(resp):
        csrf_token = generate_csrf()
        resp.set_cookie("csrf_token", csrf_token)
        return resp

    # 初始化Session
    Session(app)
    # TODO 3:只用一次的模块什么时候用什么时候导入
    from info.modules.index import index_blu
    app.register_blueprint(index_blu)
    # 注册图片验证码蓝图
    from info.modules.passport import passport_blu
    app.register_blueprint(passport_blu)
    # 注册新闻详情页蓝图
    from info.modules.news import news_blu
    app.register_blueprint(news_blu)
    # 注册过滤器
    app.add_template_filter(news_hot_filter, "hot_filter")
    return app
Exemplo n.º 34
0
def create_app(test_config=None):
    app = Flask(__name__, instance_relative_config=True)
    app.config['DATABASE'] = os.path.join(app.instance_path, 'prodty.sqlite')

    if not os.path.exists(app.instance_path):
        os.makedirs(app.instance_path)

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

    db.init_app(app)
    app.register_blueprint(auth.bp)
    app.register_blueprint(task.bp)
    # the following line lets us use ``` url_for('index') ```
    # instead of ``` url_for('task.index') ```
    app.add_url_rule('/', endpoint='index')

    app.add_template_filter(tstamp_to_dt, 'todt')

    @app.route('/hello')
    def hello():
        return 'Hello!'

    @app.errorhandler(404)
    def page_not_found(e):
        return render_template('page_not_found.html'), 404

    return app
Exemplo n.º 35
0
    def _create_app(self, config=None):
        app = Flask(__name__)
        app.psdash = self
        app.config.from_envvar('PSDASH_CONFIG', silent=True)

        if config and isinstance(config, dict):
            app.config.update(config)

        # CUSTOM

        app.config.update(
            DEBUG=False,
            SECRET_KEY='\x19&\xbbb1ls\xb4i\xcfg\x1f"%d\x9eF.\xae\x92GH@\r',
            PSDASH_NODES=[{
                'name': 'mywebnode',
                'host': '192.168.28.54',
                'port': 5000
            }])

        self._load_allowed_remote_addresses(app)

        # If the secret key is not read from the config just set it to something.
        if not app.secret_key:
            app.secret_key = 'whatisthissourcery'
        app.add_template_filter(fromtimestamp)

        from psdash.web import webapp
        prefix = app.config.get('PSDASH_URL_PREFIX')
        if prefix:
            prefix = '/' + prefix.strip('/')
        webapp.url_prefix = prefix
        app.register_blueprint(webapp)

        return app
Exemplo n.º 36
0
def create_app():
    app = Flask(__name__, static_folder="../static", static_url_path="/static")

    from api import api as api_blueprint
    app.register_blueprint(api_blueprint, url_prefix='/api')

    app.register_blueprint(web, url_prefix='')
    app.debug = True
    app.add_template_filter(human_date)

    return app
def create_app(config_name):
    application = Flask(__name__,
                        static_folder='static/',
                        static_url_path=configs[config_name].STATIC_URL_PATH)

    init_app(
        application,
        configs[config_name],
        data_api_client=data_api_client,
        feature_flags=feature_flags,
        login_manager=login_manager,
    )

    from .main import main as main_blueprint
    from .status import status as status_blueprint

    application.register_blueprint(status_blueprint,
                                   url_prefix='/suppliers')
    application.register_blueprint(main_blueprint,
                                   url_prefix='/suppliers')
    login_manager.login_message_category = "must_login"
    main_blueprint.config = application.config.copy()

    csrf.init_app(application)

    @csrf.error_handler
    def csrf_handler(reason):
        if 'user_id' not in session:
            application.logger.info(
                u'csrf.session_expired: Redirecting user to log in page'
            )

            return application.login_manager.unauthorized()

        application.logger.info(
            u'csrf.invalid_token: Aborting request, user_id: {user_id}',
            extra={'user_id': session['user_id']})

        abort(400, reason)

    @application.before_request
    def remove_trailing_slash():
        if request.path.endswith('/'):
            return redirect(request.path[:-1], code=301)

    @application.before_request
    def refresh_session():
        session.permanent = True
        session.modified = True

    application.add_template_filter(question_references)
    application.add_template_filter(parse_document_upload_time)

    return application
Exemplo n.º 38
0
def create_app(config):
    app = Flask(__name__)
    app.config.from_object(configs.get(config))

    register_extensions(app)
    # 用于创建测试数据
    Migrate(app, db)
    register_blueprints(app)
    # 注册自定义过滤器
    app.add_template_filter(get_jobdelta)

    return app
def create_app(config_name):
    asset_path = os.environ.get('ASSET_PATH', configs[config_name].ASSET_PATH)
    application = Flask(__name__,
                        static_folder='static/',
                        static_url_path=asset_path)

    init_app(
        application,
        configs[config_name],
        data_api_client=data_api_client,
        login_manager=login_manager,
    )

    from .main import main as main_blueprint
    from .status import status as status_blueprint

    url_prefix = application.config['URL_PREFIX']
    application.register_blueprint(status_blueprint,
                                   url_prefix=url_prefix)
    application.register_blueprint(main_blueprint,
                                   url_prefix=url_prefix)
    login_manager.login_message_category = "must_login"
    main_blueprint.config = application.config.copy()

    application.add_template_filter(question_references)
    application.add_template_filter(parse_document_upload_time)

    init_frontend_app(application, data_api_client, login_manager)

    @application.context_processor
    def extra_template_variables():
        return {
            'marketplace_home': urlparse.urljoin('/', application.config['BASE_PREFIX']),
            'generic_contact_email': application.config['GENERIC_CONTACT_EMAIL'],
        }

    def component_filter(x, thing, *args, **kwargs):
        from jinja2 import Markup  # , escape
        from flask import current_app

        COMPONENTS = 'components'
        EXTENSION = '.html'

        t = current_app.jinja_env.get_template(
            COMPONENTS + '/' + thing + EXTENSION)
        return Markup(t.render(x=x, **kwargs))

    application.jinja_env.filters['as'] = component_filter
    application.jinja_env.globals.update(render_component=render_component)

    return application
Exemplo n.º 40
0
def create_app(method):
    my_app = Flask('test_filter')

    filters = make_filters(FILTERS, method)
    for name, function in filters.items():
        my_app.add_template_filter(function, name)

    @my_app.route('/my_hex/<int:number>', endpoint='my_hex')
    @my_app.route('/my_bin/<int:number>', endpoint='my_bin')
    @my_app.route('/my_oct/<int:number>', endpoint='my_oct')
    def use_filter(number):
        filter_ = request.url_rule.endpoint
        template = '{{ filter_ }} {{ number|%s }}' % filter_
        pytest.set_trace()
        return render_template_string(template, **locals())
    return my_app
Exemplo n.º 41
0
def create_app(config_name):
    application = Flask(
        __name__,
        static_folder='static/',
        static_url_path=configs[config_name].STATIC_URL_PATH
    )

    application.config['NOTIFY_ENVIRONMENT'] = config_name
    application.config.from_object(configs[config_name])

    init_app(application)
    csrf.init_app(application)

    @csrf.error_handler
    def csrf_handler(reason):
        if 'user_id' not in session:
            application.logger.info(
                u'csrf.session_expired: Redirecting user to log in page'
            )

            return application.login_manager.unauthorized()

        application.logger.info(
            u'csrf.invalid_token: Aborting request, user_id: {user_id}',
            extra={'user_id': session['user_id']})

        abort(400, reason)

    login_manager.init_app(application)
    admin_api_client.init_app(application)
    proxy_fix.init_app(application)

    from .main import main as main_blueprint
    application.permanent_session_lifetime = timedelta(hours=1)
    application.register_blueprint(main_blueprint, url_prefix='/admin')
    login_manager.login_view = 'main.render_login'

    main_blueprint.config = application.config.copy()

    @application.before_request
    def remove_trailing_slash():
        if request.path != '/' and request.path.endswith('/'):
            return redirect(request.path[:-1], code=301)

    application.add_template_filter(datetimeformat)

    return application
Exemplo n.º 42
0
class App(object):
    def __init__(self):
        self._indices = {}
        templateFolder = os.path.join(
            os.path.dirname(os.path.abspath(__file__)), 'templates')
        staticFolder = os.path.join(
            os.path.dirname(os.path.abspath(__file__)), 'static')
        self._app = Flask('pyaci Query App',
                          static_folder=staticFolder,
                          template_folder=templateFolder)
        self._app.add_template_test(isDn, 'Dn')
        self._app.add_template_filter(getParentDn, 'parentDn')

    def addIndex(self, index):
        # TODO: Handle duplicate index.
        self._indices[index.name] = index
        self._app.add_url_rule(
            '/{}/dn/<path:dn>'.format(index.name),
            view_func=DnView.as_view('dn_view_{}'.format(index.name),
                                     index, self),
            methods=['GET']
        )
        self._app.add_url_rule(
            '/{}/class/<className>'.format(index.name),
            view_func=ClassView.as_view('class_view_{}'.format(index.name),
                                        index, self),
            methods=['GET']
        )

        if index.name == 'audit':
            self._app.add_url_rule(
                '/{}/affected/<path:dn>'.format(index.name),
                view_func=AuditView.as_view(
                    'affected_view_{}'.format(index.name),
                    index, self),
                methods=['GET']
            )

    def indices(self):
        return self._indices

    def run(self, debug=False):
        self._app.debug = debug
        self._app.run(host='0.0.0.0')
Exemplo n.º 43
0
def create_app_by_config(config=None, profile=False):
    app = Flask(__name__)
    # 初始化环境配置
    app.config.from_object("config.default")
    if config:
        try:
            app.config.from_object(config)
        except:
            raise ValueError("[%s] config is not exists" % config)

    from qsapp.views.qsmain_view import qsmain
    from qsapp.views.wechat_view import wechat
    app.register_blueprint(qsmain)
    app.register_blueprint(wechat)

    # 增加过滤器
    for value in template_filters.__dict__.values():
        if callable(value):
            app.add_template_filter(value)
    return app
Exemplo n.º 44
0
    def _create_app(self, config=None):
        app = Flask(__name__)
        app.psdash = self
        app.config.from_envvar('PSDASH_CONFIG', silent=True)

        if config and isinstance(config, dict):
            app.config.update(config)

        self._load_allowed_remote_addresses(app)

        # If the secret key is not read from the config just set it to something.
        if not app.secret_key:
            app.secret_key = 'whatisthissourcery'
        app.add_template_filter(fromtimestamp)

        from psdash.web import webapp
        prefix = app.config.get('PSDASH_URL_PREFIX')
        if prefix:
            prefix = '/' + prefix.strip('/')
        webapp.url_prefix = prefix
        app.register_blueprint(webapp)

        return app
Exemplo n.º 45
0
    def _crea_app(self, config=None):
        app = Flask(__name__, template_folder="plantillas" )
        app.psdash = self
        app.config.from_envvar('PSDASH_CONFIG', silent=True)

        if config and isinstance(config, dict):
            app.config.update(config)

        self._cargar_direccciones_remotas_permitidas(app)

        # If the secret key is not read from the config just set it to something.
        if not app.secret_key:
            app.secret_key = 'whatisthissourcery'
        app.add_template_filter(fromtimestamp)

        from controlador_web import webapp
        prefix = app.config.get('PSDASH_URL_PREFIX')
        if prefix:
            prefix = '/' + prefix.strip('/')
        webapp.url_prefix = prefix
        app.register_blueprint(webapp)

        return app
Exemplo n.º 46
0
app.add_url_rule('/atlases', 'get atlases', get_atlases)
app.add_url_rule('/atlas', 'post atlas', post_atlas, methods=['POST'])
app.add_url_rule('/atlas-hints/<id>', 'post atlas hints', post_atlas_hints, methods=['GET', 'POST'])
app.add_url_rule('/atlas/<id>', 'get atlas', get_atlas)
app.add_url_rule('/map/<id>', 'get map', get_map) 
app.add_url_rule('/maps', 'get maps', get_maps)
app.add_url_rule('/atlases-list', 'get atlases list', get_atlases_list)
app.add_url_rule('/maps-list', 'get maps list', get_maps_list)
app.add_url_rule('/check-map-status/<id>', 'get map status', check_map_status, methods=['GET']) 
app.add_url_rule('/tile/<path:path>', 'tile', tile)

app.add_url_rule('/tile/map/<id>/<path:path>', 'tilemap', tile_by_id)
app.add_url_rule('/tile/atlas/<id>/<path:path>', 'tileatlas', tile_by_id)
 
app.add_url_rule('/map-sandwich', 'map-sandwich', map_sandwich)
app.add_url_rule('/map-sandwich/map/<id>', 'map-sandwich-map', map_sandwich)
app.add_url_rule('/map-sandwich/atlas/<id>', 'map-sandwich-atlas', map_sandwich) 

app.add_url_rule('/faq', 'faq', faq) 
app.add_url_rule('/faq-public', 'faq-public', faq_public)
app.add_url_rule('/docs', 'docs', docs)

app.error_handler_spec[None][404] = page_not_found

app.add_template_filter(sumiter)
app.add_template_filter(datetimeformat)

if __name__ == '__main__':
    app.debug = True
    app.run(host='0.0.0.0', port=8080)
Exemplo n.º 47
0
# Blueprints
from .tf2.views import tf2 as tf2_blueprint
from .users.views import users as users_blueprint
from .mods.views import mods as mods_blueprint

# Admin
from .users.models import User
from .mods.models import ModAuthor
from .admin.views import admin

admin.init_app(app)

# TF2 Schema
from .tf2.models import TF2Item, TF2EquipRegion, TF2BodyGroup

app.register_blueprint(users_blueprint)
app.register_blueprint(mods_blueprint)
app.register_blueprint(tf2_blueprint)

# Assets
from assets import assets

# Jinja2 Filters
from filters import format_thousands, pluralize, datetime_to_datestring
app.add_template_filter(format_thousands)
app.add_template_filter(pluralize)
app.add_template_filter(datetime_to_datestring)

# Load current app version into globals
from functions import current_version
app.config['VERSION'] = current_version()
Exemplo n.º 48
0
# -*- coding: utf-8 -*-
__author__ = 'venking'

from flask import Flask
from web import loginctrl
from module.util import fromtimestamp

app = Flask(__name__)
app.register_blueprint(loginctrl,url_prefix='/login')

app.add_template_filter(fromtimestamp)
app.secret_key = 'zoupan19940907'

# @app.route('/')
# def index():
#     return 'Index Page!'
#
#
# @app.route('/hello')
# def hello_world():
#     return 'Hello World!'
#
#
# @app.route('/user/<username>')
# def show_user_profile(username):
#     # show the user profile for that user
#     flash('你好,%s'%(username))
#     return 'User %s' % username
#
#
# @app.route('/post/<int:post_id>')
Exemplo n.º 49
0
#!/usr/bin/env python

import json

import argparse
from flask import Flask, make_response, render_template

import app_config
from render_utils import make_context, smarty_filter, urlencode_filter
import static

from gentrification import make_ca_context

app = Flask(__name__)

app.add_template_filter(smarty_filter, name='smarty')
app.add_template_filter(urlencode_filter, name='urlencode')

# Filters
def format_currency(value):
    value = int(value)
    return "${:,}".format(value)

def format_comma(value):
    value = int(value)
    return "{:,}".format(value)

app.jinja_env.filters['format_currency'] = format_currency
app.jinja_env.filters['format_comma'] = format_comma

# Example application views
Exemplo n.º 50
0
import os

from boto.s3.key import Key
from boto.s3.connection import S3Connection
from flask import Flask, request, render_template
from pbkdf2 import crypt

import forms
import filters
import models
import settings


app = Flask(__name__)
app.config.update(SECRET_KEY=settings.FLASK_SECRET_KEY)
app.add_template_filter(filters.nl2br)


@app.route('/', methods=['GET', 'POST'])
def create_page():
    """ Main view to present the user with a form to create a signup page. """
    form = forms.PageForm(request.form)
    error = None

    if request.method == 'POST' and form.validate():

        # if password incorrect or not entered, show an error
        if not valid_password(form.password.data):
            error = "Must enter correct password."
            return render_template('main.html', form=form, error=error)
Exemplo n.º 51
0
from mongokit import Connection
import steam

from models import Profile, Job, Match, User
from filters import unix_strftime, prettyprint
app = Flask(__name__)

app.config.from_pyfile("settings.cfg")
connection = Connection(app.config['MONGODB_HOST'],
                        app.config['MONGODB_PORT'])

cache = Cache(app)
oid = OpenID(app)

connection.register([Profile, Job, Match, User])
app.add_template_filter(unix_strftime)
app.add_template_filter(prettyprint)

# Setup steamodd
steam.api.key.set(app.config['STEAM_API_KEY'])
steam.api.socket_timeout.set(10)

# Helpers
@cache.cached(timeout=60*60, key_prefix="league_passes")
def get_league_passes():
    try:
        return [x for x in steam.items.schema(570, "en_US") if x.type == "League Pass"]
    except steam.api.APIError:
        return []

Exemplo n.º 52
0
# Setup steamodd
steam.api.key.set(app.config['STEAM_API_KEY'])
steam.api.socket_timeout.set(5)

# Setup debugtoolbar if we're in debug mode.
if app.debug:
    from flask.ext.debugtoolbar import DebugToolbarExtension
    toolbar = DebugToolbarExtension(app)


# Set up jinja2 filters.
from app.filters import escape_every_character,\
    timestamp_to_datestring,\
    datetime_to_datestring,\
    seconds_to_time
app.add_template_filter(escape_every_character)
app.add_template_filter(timestamp_to_datestring)
app.add_template_filter(datetime_to_datestring)
app.add_template_filter(seconds_to_time)


# Load current app version into globals
from helpers import current_version
app.config['VERSION'] = current_version()

# Load views
import views

# Load blueprints
from app.users.views import mod as users_module
app.register_blueprint(users_module)
Exemplo n.º 53
0
Arquivo: manage.py Projeto: qxbug/zsky

def make_cache_key(*args, **kwargs):
    path = request.path
    args = str(hash(frozenset(request.args.items())))
    return (path + args).encode('utf-8')

def filelist_filter(info_hash):
    try:
        return json.loads(Search_Filelist.query.filter_by(info_hash=info_hash).first().file_list)
    except:
        return [{
       'path':Search_Hash.query.filter_by(info_hash=info_hash).first().name, 
       'length':Search_Hash.query.filter_by(info_hash=info_hash).first().length
       }]
app.add_template_filter(filelist_filter,'filelist')


def todate_filter(s):
    return datetime.datetime.fromtimestamp(int(s)).strftime('%Y-%m-%d')
app.add_template_filter(todate_filter,'todate')


def tothunder_filter(magnet):
    return base64.b64encode('AA'+magnet+'ZZ')
app.add_template_filter(tothunder_filter,'tothunder')

def sphinx_conn():
    conn = pymysql.connect(host=DB_HOST, port=DB_PORT_SPHINX, user=DB_USER, password=DB_PASS, db=DB_NAME_SPHINX,
                           charset=DB_CHARSET, cursorclass=pymysql.cursors.DictCursor)
    curr = conn.cursor()
Exemplo n.º 54
0
def create_app(config=None):
    """ config should be a python file """
    from pathlib import Path

    from flask import (Flask,
            current_app,
            g,
            session,
            url_for,
            render_template)

    from flask_sqlalchemy import SQLAlchemy
    from flask_security import (Security, SQLAlchemyUserDatastore)

    from flask_wtf.csrf import CsrfProtect

    from flask_assets import (Environment, Bundle)

    from .app_setup import (init_db, setup_dirs)
    from .core import (db, load_blueprints, setup_logger)
    from .lib.template_filters import (
        fmt_datetime,
        none_as_str,
        next_page_url,
        prev_page_url,
        get_page_url,
        get_images)

    from .models.user import (User, Role, user_datastore)

    from .Admin import (index, series, images, texts, contact)
    from .Public import (index, contact, texts)
    from .Security import user

    app = Flask(__name__.split('.')[0], instance_relative_config=True)

    app.config.from_object('config')
    app.config.from_pyfile('config.py')

    if config is not None:
        app.config.from_pyfile(config)
        setup_logger(app)
        app.logger.info('Started with config from: {}'.format(config))
    else:
        setup_logger(app)
        app.logger.info('Started App')

    # Flask.sqlalchemy
    db.init_app(app)

    load_blueprints(app)

    # make sure db tables and required directories exist
    before_first_request_funcs = [setup_dirs(app),
                                  init_db(app)]

    #Security
    csrf = CsrfProtect()
    csrf.init_app(app)
    security = Security()
    security.init_app(app, user_datastore, register_blueprint=False)

    # Assets
    assets = Environment(app=app)
    assets.from_yaml('assets.yml')

    # template filters
    app.add_template_filter(fmt_datetime)
    app.add_template_filter(none_as_str)
    app.add_template_filter(next_page_url)
    app.add_template_filter(prev_page_url)
    app.add_template_filter(get_page_url)
    app.add_template_filter(get_images)

    return app
Exemplo n.º 55
0
app = Flask(__name__)
app.debug = app_config.DEBUG

try:
    file_handler = logging.FileHandler('%s/public_app.log' % app_config.SERVER_LOG_PATH)
    file_handler.setLevel(logging.INFO)
    app.logger.addHandler(file_handler)
except IOError:
    pass

app.logger.setLevel(logging.INFO)

app.register_blueprint(static.static, url_prefix='/%s' % app_config.PROJECT_SLUG)

app.add_template_filter(smarty_filter, name='smarty')
app.add_template_filter(urlencode_filter, name='urlencode')
app.add_template_filter(format_commas_filter, name='format_commas')

# Example of rendering index.html with public_app 
@app.route('/%s/' % app_config.PROJECT_SLUG, methods=['GET'])
def index():
    """
    Example view rendering a simple page.
    """
    context = make_context(asset_depth=1)

    context['users'] = SITE_USERS

    return make_response(render_template('admin/index.html', **context))
Exemplo n.º 56
0
from kagami.config import Config
from kagami.models import KagamiStatus
from kagami.i18n import i18n


def get_api(access_token: str, access_secret: str):
    tw_auth = tweepy.OAuthHandler(current_app.config['CK'], current_app.config['CS'])
    tw_auth.set_access_token(access_token, access_secret)
    return tweepy.API(tw_auth)


app = Flask(__name__)
app.config.from_object(Config)
app.config['STRINGS'] = i18n()
import kagami.handler
import kagami.auth
import kagami.status
import kagami.user
import kagami.user_config
import kagami.direct_message
import kagami.cookie

app.add_template_filter(nl2br)
app.jinja_env.globals.update(handler=kagami.handler)
app.jinja_env.globals.update(int=int, str=str)
app.jinja_env.globals.update(session=session)
app.jinja_env.globals.update(KagamiStatus=KagamiStatus)
Bootstrap(app)
if app.config['ENABLE_HTTPS']:
    SSLify(app)
Exemplo n.º 57
0
def create_app(config={}):
    app = Flask(__name__, instance_relative_config=True)
    app.config.update(DEFAULT_CONFIG)
    app.config.from_pyfile('settings.py', silent=True)
    app.config.update(config)

    babel = Babel(app)

    @babel.localeselector
    def get_locale():
        return getattr(g, 'language', 'en')

    assets_env.init_app(app)
    db.init_app(app)

    app.register_blueprint(admin)
    app.register_blueprint(auth)
    app.register_blueprint(meetings)

    app.add_template_filter(activity_map)
    app.add_template_filter(countries)
    app.add_template_filter(country_in)
    app.add_template_filter(region_in)
    app.add_template_filter(crop)
    app.add_template_filter(nl2br)
    app.add_template_filter(convert_to_dict, name='dict')
    app.add_template_filter(no_image_cache)
    app.add_template_filter(pluralize)
    app.add_template_filter(slugify)
    app.add_template_filter(sort_by_tuple_element)
    app.add_template_filter(clean_html)
    app.add_template_global(active)
    app.add_template_global(date_processor)
    app.add_template_global(inject_static_file)
    app.add_template_global(inject_badge_context)
    app.add_template_global(has_perm)
    app.add_template_global(Logo, name='get_logo')

    @app.context_processor
    def inject_context():
        return {
            'CustomField': {
                'TEXT': CustomField.TEXT,
                'IMAGE': CustomField.IMAGE,
                'EMAIL': CustomField.EMAIL,
                'CHECKBOX': CustomField.CHECKBOX,
                'SELECT': CustomField.SELECT,
                'COUNTRY': CustomField.COUNTRY,
                'LANGUAGE': CustomField.LANGUAGE,
                'CATEGORY': CustomField.CATEGORY,
                'EVENT': CustomField.EVENT,
            },
            'Participant': {
                'PARTICIPANT': Participant.PARTICIPANT,
                'MEDIA': Participant.MEDIA,
                'DEFAULT': Participant.DEFAULT,
                'DEFAULT_MEDIA': Participant.DEFAULT_MEDIA,
            },
        }

    login_manager = LoginManager()
    login_manager.init_app(app)
    login_manager.login_view = 'auth.login'
    login_manager.login_message_category = 'warning'

    mail.init_app(app)
    redis_store.init_app(app, strict=True)

    if app.config.get('SENTRY_DSN'):
        sentry.init_app(app)

    _configure_uploads(app)
    _configure_logging(app)

    app.config['REPRESENTING_TEMPLATES'] = (
        path('meetings/participant/representing'))

    _translations = app.config['TRANSLATIONS']
    if _DEFAULT_LANG not in _translations:
        _translations = [_DEFAULT_LANG] + _translations
    app.config['TRANSLATIONS'] = _translations

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

    @app.route('/')
    def index():
        return redirect(url_for('meetings.home'))

    @app.errorhandler(413)
    def file_too_large(error):
        mb = 1024 * 1024
        max_size = app.config.get('UPLOAD_SIZE', mb) / mb
        return render_template('_file_too_large.html',
                               max_size=max_size,
                               url=request.url), 413

    return app
Exemplo n.º 58
0
def create_app():
    from config import configs

    application = Flask(__name__)

    application.config.from_object(configs[os.environ["NOTIFY_ENVIRONMENT"]])

    init_app(application)
    statsd_client.init_app(application)
    logging.init_app(application, statsd_client)
    init_csrf(application)
    request_id.init_app(application)

    service_api_client.init_app(application)
    user_api_client.init_app(application)
    api_key_api_client.init_app(application)
    job_api_client.init_app(application)
    notification_api_client.init_app(application)
    status_api_client.init_app(application)
    invite_api_client.init_app(application)
    template_statistics_client.init_app(application)
    events_api_client.init_app(application)
    provider_client.init_app(application)
    organisations_client.init_app(application)

    login_manager.init_app(application)
    login_manager.login_view = "main.sign_in"
    login_manager.login_message_category = "default"
    login_manager.session_protection = None

    from app.main import main as main_blueprint

    application.register_blueprint(main_blueprint)

    from .status import status as status_blueprint

    application.register_blueprint(status_blueprint)

    proxy_fix.init_app(application)

    application.session_interface = ItsdangerousSessionInterface()

    application.add_template_filter(format_datetime)
    application.add_template_filter(format_datetime_24h)
    application.add_template_filter(format_datetime_normal)
    application.add_template_filter(format_datetime_short)
    application.add_template_filter(format_time)
    application.add_template_filter(syntax_highlight_json)
    application.add_template_filter(valid_phone_number)
    application.add_template_filter(linkable_name)
    application.add_template_filter(format_date)
    application.add_template_filter(format_date_normal)
    application.add_template_filter(format_date_short)
    application.add_template_filter(format_datetime_relative)
    application.add_template_filter(format_delta)
    application.add_template_filter(format_notification_status)
    application.add_template_filter(format_notification_status_as_time)
    application.add_template_filter(format_notification_status_as_field_status)
    application.add_template_filter(format_notification_status_as_url)

    application.after_request(useful_headers_after_request)
    application.after_request(save_service_after_request)
    application.before_request(load_service_before_request)

    @application.context_processor
    def _attach_current_service():
        return {"current_service": current_service}

    register_errorhandlers(application)

    setup_event_handlers()

    return application
Exemplo n.º 59
0
@app.route('/index')
def index():
    """docstring for index"""
    data = {
        'name': 'ai',
        'age': 18,
        'my_dic': {'city': 'Beijing'},
        'my_list': [1, 2, 3, 4, 5],
        'my_int': 0,
    }
    # return render_template('index.html', name='ai', age=18)
    # data前面的**表示按键-值对解析字典
    return render_template('index.html', **data)


# 自定义过滤器方法一
def list_split2(li):
    """自定义过滤器方法一 list_split2"""
    return li[::2]


# 注册过滤器
app.add_template_filter(list_split2, 'lis2')


# 自定义过滤器方法二
@app.template_filter('lis3')
def list_split3(li):
    """自定义过滤器方法一 list_split2"""
    return li[::3]
App Template for static publishing.
"""

import app_config
import json
import oauth
import static

from flask import Flask, make_response, render_template
from render_utils import make_context, smarty_filter, urlencode_filter
from werkzeug.debug import DebuggedApplication

app = Flask(__name__)
app.debug = app_config.DEBUG

app.add_template_filter(smarty_filter, name="smarty")
app.add_template_filter(urlencode_filter, name="urlencode")


@app.route("/")
@oauth.oauth_required
def index():
    """
    Example view demonstrating rendering a simple HTML page.
    """
    context = make_context()

    with open("data/featured.json") as f:
        context["featured"] = json.load(f)

    return make_response(render_template("index.html", **context))