예제 #1
0
def init_for(env):
    coaster.app.init_app(app, env)
    db.init_app(app)
    db.app = app

    RQ(app)

    lastuser.init_app(app)
    lastuser.init_usermanager(UserManager(db, User))
    app.config['tz'] = timezone(app.config['TIMEZONE'])
    baseframe.init_app(app, requires=['boxoffice'], ext_requires=['baseframe-bs3', 'fontawesome>=4.0.0', 'ractive', 'ractive-transitions-fly', 'validate', 'nprogress', 'baseframe-footable'])

    mail.init_app(app)
    wtforms_json.init()

    # This is a temporary solution for an admin interface, only
    # to be used until the native admin interface is ready.
    try:
        admin = Admin(app, name=u"Boxoffice Admin", template_mode='bootstrap3', url='/siteadmin')
        admin.add_view(OrganizationModelView(Organization, db.session))
        admin.add_view(ItemCollectionModelView(ItemCollection, db.session))
        admin.add_view(CategoryModelView(Category, db.session))
        admin.add_view(ItemModelView(Item, db.session))
        admin.add_view(PriceModelView(Price, db.session))
        admin.add_view(DiscountPolicyModelView(DiscountPolicy, db.session))
        admin.add_view(DiscountCouponModelView(DiscountCoupon, db.session))
    except AssertionError:
        pass
예제 #2
0
파일: app.py 프로젝트: andyzt/tceh
def home(version):

    class F(Form):
        pass

    wtforms_json.init()
    v_version = int(version[1])

    for name, validtrs in API_validators[v_version-1].items():
        setattr(F, name, StringField(label=name, validators=validtrs))

    jsondata = request.get_json()
    flatten_json=flatten_dict(jsondata)

    form = F.from_json(flatten_json)

    res = form.validate()
    for field, errors in form.errors.items():
        for error in errors:
            print(u"Error in the %s field - %s" % (
                getattr(form, field).label.text,
                error
            ))
    if res:
        persons_file = os.path.join('files', 'objects.json')

        with open(persons_file,'a') as _file:
            _file.write(request.data)
        if v_version == 2:
            print("Request Saved!")

    return ('valid', 200) if res else ('invalid', 400)
예제 #3
0
def create_app():
    app_init = Flask(__name__)
    wtforms_json.init()

    from . import payment
    app_init.register_blueprint(payment.api)

    return app_init
예제 #4
0
    def pre_init(self) -> None:
        """
        Called before all other init tasks are complete
        """
        wtforms_json.init()

        if not os.path.exists(self.config["DATA_DIR"]):
            os.makedirs(self.config["DATA_DIR"])
예제 #5
0
def configure_extensions(app):
    """Initialize any extensions that we're using."""
    # flask-sqlalchemy
    db.init_app(app)

    # wtforms_json
    # this extends wtforms to use json request bodies
    wtforms_json.init()
예제 #6
0
 def __init__(self):
     wtforms_json.init()
     objects = Manager(database_async)
     database_async.set_allow_sync(False)
     web.Application.objects = objects
     super(Application, self).__init__(route.urls,
                                       debug=settings.DEBUG,
                                       **settings.TORNADO_CONF)
def validate_rsvp_field(form):
    wtforms_json.init()

    form = RsvpForm.from_json(json.loads(form))
    if form.validate():
        return form
    else:
        print 'validation errors:'
        print form.errors
예제 #8
0
def launch(_ike_instance):
    global ike_instance
    ike_instance = _ike_instance
    wtforms_json.init()

    api_url_prefix = '/api/v1'

    app = flask.Flask('ike', static_folder=config.STATIC_FILES)

    # beer
    register_api(app, BeerApi, 'beers', api_url_prefix + '/beers/', pk='id')

    # users
    register_api(app, UserApi, 'users', api_url_prefix + '/users/', pk='id')

    # kegs
    view_func = KegApi.as_view('kegs')
    app.add_url_rule(api_url_prefix + '/kegs/',
                     defaults={'id': None},
                     view_func=view_func,
                     methods=[
                         'GET',
                     ])
    app.add_url_rule(api_url_prefix + '%s<%s:%s>' % ('/kegs/', 'int', 'id'),
                     view_func=view_func,
                     methods=['GET', 'PUT'])

    # sensors
    app.add_url_rule(api_url_prefix + '/thermostat/',
                     view_func=ThermostatApi.as_view('thermostat'),
                     methods=['GET', 'PUT'])
    app.add_url_rule(api_url_prefix + '/carbonation/',
                     view_func=CarbonationApi.as_view('carbonation'),
                     methods=['GET'])
    app.add_url_rule(api_url_prefix + '/adc/',
                     view_func=AdcApi.as_view('adc'),
                     methods=['GET'])
    app.add_url_rule(api_url_prefix + '/flow/',
                     view_func=FlowApi.as_view('flow'),
                     methods=['GET'])

    # kegerator settings
    app.add_url_rule(api_url_prefix + '/kegerator/',
                     view_func=KegeratorSettingsApi.as_view('kegerator'),
                     methods=['GET', 'PUT'])

    # logs
    app.add_url_rule(api_url_prefix + '/events/',
                     view_func=EventApi.as_view('events'),
                     methods=['GET'])

    # serve the frontend
    app.add_url_rule('/', 'root', lambda: app.send_static_file('index.html'))
    app.add_url_rule('/<path:path>', 'send_static',
                     lambda path: app.send_static_file(path))

    app.run(host='0.0.0.0', debug=config.FLASK_DEBUG)
예제 #9
0
def CreateApp(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    db.init_app(app)
    mongo.init_app(app)
    wtforms_json.init()
    app.register_blueprint(main)
    app.add_url_rule('/', 'index', lambda: app.send_static_file('index.html'))
    from api_server import assign_resources
    api.init_app(app)
    return app
예제 #10
0
def init_app(app):
    # app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///../instance/flaskr.sqlite'
    app.config[
        'SQLALCHEMY_DATABASE_URI'] = 'postgres://*****:*****@localhost:5432/pm3'
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    app.config['SECRET_KEY'] = b'_5#y2L"F4Q8z\n\xec]/'
    db.init_app(app)
    migrate.init_app(app, db)
    csrf.init_app(app)
    wtforms_json.init()
    app.cli.add_command(init_db_command)
    app.cli.add_command(load_default)
def init_for(env):
    coaster.app.init_app(app, env)
    db.init_app(app)
    db.app = app

    lastuser.init_app(app)
    lastuser.init_usermanager(UserManager(db, User))
    app.config['tz'] = timezone(app.config['TIMEZONE'])

    baseframe.init_app(app, requires=['boxoffice'], ext_requires=['baseframe-bs3', 'fontawesome>=4.0.0', 'ractive', 'ractive-transitions-fly', 'validate'])

    mail.init_app(app)
    wtforms_json.init()
예제 #12
0
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])

    config[config_name].init_app(app)

    wtforms_json.init()

    mongodb.init_app(app)

    from .api import api as api_blueprint
    app.register_blueprint(api_blueprint)

    return app
예제 #13
0
def serve():
    wtforms_json.init()
    # init_log()

    app = make_app(False)

    app.listen(options.port)

    # No need for sync anymore!
    objects = Manager(database)
    database.set_allow_sync(False)
    app.objects = objects

    sys.stdout.write(f"Start server at:http://0.0.0.0:{options.port} \nSettings: {options.settings}\n")
    tornado.ioloop.IOLoop.current().start()
예제 #14
0
def create_app():
    """Initialize the core application."""
    app = Flask(__name__)
    app.config.from_object(load_config())

    # Initialize Plugins
    db.init_app(app)
    wtforms_json.init()

    # Blueprint Register
    app.register_blueprint(v1, url_prefix='/v1')

    # init error handlers
    register_error_handlers(app)
    return app
예제 #15
0
def init_for(env):
    coaster.app.init_app(app, env)
    db.init_app(app)
    db.app = app

    RQ(app)

    lastuser.init_app(app)
    lastuser.init_usermanager(UserManager(db, User))
    app.config['tz'] = timezone(app.config['TIMEZONE'])
    baseframe.init_app(app, requires=['outreach'], ext_requires=['baseframe-bs3', 'fontawesome>=4.0.0', 'ractive', 'ractive-transitions-fly', 'validate', 'nprogress', 'baseframe-footable'])

    mail.init_app(app)
    wtforms_json.init()

    init_flask_admin()
예제 #16
0
def create_application():
    wtforms_json.init()

    static_path = os.path.join(os.path.dirname(__file__), "static")
    application = tornado.web.Application(
        api_handlers + frontend_handlers,
        debug=options.debug,
        cookie_secret=options.cookie_secret,
        static_path=static_path)

    # config database
    src_dir = os.path.dirname(os.path.dirname(__file__))
    database = SqliteExtDatabase(os.path.join(src_dir, 'database.db'),
                                 threadlocals=True)
    database_proxy.initialize(database)
    # database.connect()

    return application
예제 #17
0
def init_for(env):
    coaster.app.init_app(app, env)
    db.init_app(app)
    db.app = app

    lastuser.init_app(app)
    lastuser.init_usermanager(UserManager(db, User))
    app.config['tz'] = timezone(app.config['TIMEZONE'])

    baseframe.init_app(app,
                       requires=['boxoffice'],
                       ext_requires=[
                           'baseframe-bs3', 'fontawesome>=4.0.0', 'ractive',
                           'ractive-transitions-fly', 'validate'
                       ])

    mail.init_app(app)
    wtforms_json.init()
예제 #18
0
파일: __init__.py 프로젝트: ghostry/tvee
def create_application():
    wtforms_json.init()

    static_path = os.path.join(os.path.dirname(__file__), "static")
    application = tornado.web.Application(
        api_handlers + frontend_handlers,
        debug=options.debug,
        cookie_secret=options.cookie_secret,
        static_path=static_path,
    )

    # config database
    src_dir = os.path.dirname(os.path.dirname(__file__))
    database = SqliteExtDatabase(os.path.join(src_dir, "database.db"), threadlocals=True)
    database_proxy.initialize(database)
    # database.connect()

    return application
예제 #19
0
def ficha_registro():
    import wtforms_json
    wtforms_json.init()
    "carga de registros de produccion"
    form = formProduccionCarga(request.form)
    if request.method == 'GET':
        return render_template('produccion_ficha.html', form=form)
    elif request.method == 'POST':
        # print ">>", form.patch_data

        o = data_produccion()
        o.setProduccion(form.patch_data)
        data = o.getProduccion(form.codpro.data, form.legajo.data, form.lote.data)
        return render_template('produccion_ficha.html', form=form, data=data)

    form.legajo.data = ''
    form.horas_trabajadas.data = ''
    form.horas.data = 'P'
    return render_template('produccion_ficha.html', form=form)
예제 #20
0
파일: views.py 프로젝트: teamhead/lan
 def post(self, request):
     """
     规则增加功能
     """
     argument = json.loads(request.body)
     wtforms_json.init()
     try:
         if argument["rule_complexity"] == "simple":
             form = SimpleForm.from_json(argument, skip_unknown_keys=False)
         elif argument["rule_complexity"] == "complex":
             form = ComplexForm.from_json(argument, skip_unknown_keys=False)
         if not form.validate():
             message = list(form.errors.values())[0][0]
             return {"errcode": 30061, "message": message}
         if argument["rule_complexity"] == "complex":
             filename = argument["rule_name"].lower() + ".py"
             if not os.path.exists("../rule_analysis/rule/extend/" +
                                   filename):
                 return {"errcode": 30063, "message": u"需要先上传脚本"}
         record = self.mongo_client.get_collection("rule").find_one({
             "rule_name":
             argument["rule_name"].upper(),
             "db_type":
             argument["db_type"]
         })
         if record:
             return {"errcode": 30062, "message": u"规则已经存在"}
         argument["rule_name"] = argument["rule_name"].upper()
         argument["solution"] = argument["rule_solution"].split("\n")
         argument["max_score"] = float(argument["max_score"])
         argument["weight"] = float(argument["weight"])
         if argument["input_parms"]:
             for index, value in enumerate(argument["input_parms"]):
                 argument["input_parms"][index]["parm_value"] = \
                     float(value["parm_value"])
         self.mongo_client.get_collection("rule").insert_one(argument)
         return {"errcode": 80061, "message": u"增加规则成功"}
     except wtforms_json.InvalidData as e:
         return {"errcode": 30060, "message": str(e)}
예제 #21
0
파일: factory.py 프로젝트: CalPolyIEEE/ieee
def create_app(package_name, package_path, settings_override=None):
    """Returns a :class:`Flask` application instance configured with common
    functionality for the IEEE platform.

    :param package_name: application package name
    :param package_path: application package path
    :param settings_override: a dictionary of setings to override
    """
    app = Flask(package_name, instance_relative_config=True)
    app.config.from_object(config)

    # Initialize extensions.
    db.init_app(app)
    mail.init_app(app)
    login_manager.init_app(app)
    gravatar.init_app(app)
    compress.init_app(app)
    # I may need to put this in core.py later on.
    wtforms_json.init()

    register_blueprints(app, package_name, package_path)

    return app
예제 #22
0
def launch(_ike_instance):
    global ike_instance
    ike_instance = _ike_instance
    wtforms_json.init()
    
    api_url_prefix = '/api/v1'

    app = flask.Flask('ike', static_folder=config.STATIC_FILES)

    # beer
    register_api(app, BeerApi, 'beers', api_url_prefix + '/beers/', pk='id')
    
    # users
    register_api(app, UserApi, 'users', api_url_prefix + '/users/', pk='id')

    # kegs
    view_func = KegApi.as_view('kegs')
    app.add_url_rule(api_url_prefix + '/kegs/', defaults={'id': None}, view_func=view_func, methods=['GET',])
    app.add_url_rule(api_url_prefix + '%s<%s:%s>' % ('/kegs/', 'int', 'id'), view_func=view_func, methods=['GET', 'PUT'])
    
    # sensors
    app.add_url_rule(api_url_prefix + '/thermostat/', view_func=ThermostatApi.as_view('thermostat'), methods=['GET', 'PUT'])
    app.add_url_rule(api_url_prefix + '/carbonation/', view_func=CarbonationApi.as_view('carbonation'), methods=['GET'])
    app.add_url_rule(api_url_prefix + '/adc/', view_func=AdcApi.as_view('adc'), methods=['GET'])
    app.add_url_rule(api_url_prefix + '/flow/', view_func=FlowApi.as_view('flow'), methods=['GET'])

    # kegerator settings
    app.add_url_rule(api_url_prefix + '/kegerator/', view_func=KegeratorSettingsApi.as_view('kegerator'), methods=['GET','PUT'])

    # logs
    app.add_url_rule(api_url_prefix + '/events/', view_func=EventApi.as_view('events'), methods=['GET'])
    
    # serve the frontend
    app.add_url_rule('/', 'root', lambda: app.send_static_file('index.html'))
    app.add_url_rule('/<path:path>', 'send_static', lambda path: app.send_static_file(path))

    app.run(host='0.0.0.0', debug=config.FLASK_DEBUG)
예제 #23
0
파일: view.py 프로젝트: aspros-zhong/Themis
 def post(self):
     """
     规则增加功能
     """
     argument = json.loads(self.request.body)
     wtforms_json.init()
     try:
         if argument["rule_complexity"] == "simple":
             form = SimpleForm.from_json(argument, skip_unknown_keys=False)
         elif argument["rule_complexity"] == "complex":
             form = ComplexForm.from_json(argument, skip_unknown_keys=False)
         if not form.validate():
             message = form.errors.values()[0][0]
             return {"errcode": 30061, "message": message}
         if argument["rule_complexity"] == "complex":
             filename = argument["rule_name"].lower() + ".py"
             if not os.path.exists(
                 "../rule_analysis/rule/extend/" + filename):
                 return {"errcode":30063, "message": u"需要先上传脚本"}
         record = self.mongo_client.get_collection("rule").find_one({
             "rule_name": argument["rule_name"].upper(),
             "db_type": argument["db_type"]})
         if record:
             return {"errcode": 30062, "message": u"规则已经存在"}
         argument["rule_name"] = argument["rule_name"].upper()
         argument["rule_solution"] = argument["rule_solution"].split("\n")
         argument["max_score"] = float(argument["max_score"])
         argument["weight"] = float(argument["weight"])
         if argument["input_parms"]:
             for index, value in enumerate(argument["input_parms"]):
                 argument["input_parms"][index]["parm_value"] = \
                     float(value["parm_value"])
         self.mongo_client.get_collection("rule").insert_one(argument)
         return {"errcode": 80061, "message": u"增加规则成功"}
     except wtforms_json.InvalidData as e:
         return {"errcode": 30060, "message": str(e)}
예제 #24
0
파일: users.py 프로젝트: jinxiu89/torWones
class EditForm(Form):
    wtforms_json.init()
    name = wtforms.StringField(label="用户名",
                               validators=[DataRequired("请输入用户名")],
                               description="用户名",
                               render_kw={
                                   "id": "name",
                                   "class": "input-text size-L",
                                   "placeholder": "name"
                               })
    nickname = wtforms.StringField(label="昵称",
                                   validators=[DataRequired("请输入昵称")],
                                   description="昵称",
                                   render_kw={
                                       "id": "nickname",
                                       "class": "input-text size-L",
                                       "placeholder": "nickname"
                                   })
    email = wtforms.StringField(label="email",
                                validators=[],
                                description="email",
                                render_kw={
                                    "id": "email",
                                    "class": "input-text size-L",
                                    "placeholder": "email"
                                })
    mobile = wtforms.StringField(label="电话",
                                 validators=[],
                                 description="电话",
                                 render_kw={
                                     "id": "phone",
                                     "class": "input-text size-L",
                                     "placeholder": "phone"
                                 })
    qq = wtforms.StringField(label="QQ",
                             validators=[],
                             description="qq",
                             render_kw={
                                 "id": "qq",
                                 "class": "input-text size-L",
                                 "placeholder": "2447376396"
                             })
    submit = wtforms.SubmitField(
        render_kw={
            "class": "btn btn-success radius size-L button",
            "value": "       提      交     ",
            "type": "button"
        })
예제 #25
0
class AddPermissionGroupForm(Form):
    """
        wtforms_json 是用于Json数据格式的验证引入的。
        1、在有JSON数据的Form 里init()它,即可解决JSON数据无法通过验证的问题
        """
    wtforms_json.init()
    name = wtforms.StringField(label="权限组名",
                               validators=[
                                   DataRequired("权限组名"),
                                   Length(4, 16, message="权限组名长度必须在4-16个字符之间")
                               ],
                               description="权限组名称",
                               render_kw={
                                   "id": "name",
                                   "class": "input-text size-L",
                                   "placeholder": "权限组名"
                               })

    @staticmethod
    def validate_name(self, field):
        """
        如果名称已经有了,就不让重新加组
        :param field:
        :return:
        """
        if PermissionGroup.by_name(field.data) is not None:
            raise ValidationError("以存在同名权限组,不必重复添加")

    description = wtforms.StringField(label="权限组描述",
                                      validators=[
                                          DataRequired("请输入权限组名描述"),
                                          Length(4,
                                                 32,
                                                 message="描述长度必须在4-32个字符之间")
                                      ],
                                      description="权限组名描述",
                                      render_kw={
                                          "id": "description",
                                          "class": "input-text size-L",
                                          "placeholder": "该权限组是负责搞什么的呢?"
                                      })

    submit = wtforms.SubmitField(
        render_kw={
            "class": "btn btn-success radius size-L button",
            "value": "       提      交     ",
            "type": "button"
        })
예제 #26
0
class RoleAddForm(Form):
    """
        wtforms_json 是用于Json数据格式的验证引入的。
        1、在有JSON数据的Form 里init()它,即可解决JSON数据无法通过验证的问题
        """
    wtforms_json.init()
    name = wtforms.StringField(
        label="角色名",
        validators=[DataRequired("请输入角色名"), Length(4, 16, message="长度必须在4-16个字符之间")],
        description="角色名",
        render_kw={
            "id": "name",
            "class": "input-text size-L",
            "placeholder": "Role name"
        }
    )

    @staticmethod
    def validate_name(self, field):
        """
        如果角色名已经有了,就不让重新加角色
        :param field:
        :return:
        """
        if Role.by_name(field.data) is not None:
            raise ValidationError("以存在同名角色")

    description = wtforms.StringField(
        label="角色描述",
        validators=[DataRequired("请输入描述"), Length(12, 64, message="长度必须在12-64个字符之间")],
        description="角色描述",
        render_kw={
            "id": "description",
            "class": "input-text size-L",
            "placeholder": "该角色能够干很么事情呢?"
        }
    )

    submit = wtforms.SubmitField(
        render_kw={
            "class": "btn btn-success radius size-L button", "value": "       提      交     ",
            "type": "button"
        })
예제 #27
0
class EditPermissionForm(Form):
    wtforms_json.init()
    id = wtforms.IntegerField(render_kw={"type": "hidden"})
    name = wtforms.StringField(label="权限名",
                               validators=[
                                   DataRequired("请输入权限名"),
                                   Length(4, 16, message="权限名长度必须在4-16个字符之间")
                               ],
                               description="权限名称",
                               render_kw={
                                   "id": "name",
                                   "class": "input-text size-L",
                                   "placeholder": "权限名"
                               })
    handler = wtforms.StringField(label="Handler",
                                  validators=[DataRequired("请输入Handler")],
                                  description="Handler 地址",
                                  render_kw={
                                      "id": "handler",
                                      "class": "input-text size-L",
                                      "placeholder": "哪个权限"
                                  })
    description = wtforms.StringField(label="组描述",
                                      validators=[
                                          DataRequired("请输入描述"),
                                          Length(6,
                                                 64,
                                                 message="描述长度必须在6-64个字符之间")
                                      ],
                                      description="组描述",
                                      render_kw={
                                          "id": "description",
                                          "class": "input-text size-L",
                                          "placeholder": "该组是负责搞什么的呢?"
                                      })

    submit = wtforms.SubmitField(
        render_kw={
            "class": "btn btn-success radius size-L button",
            "value": "       提      交     ",
            "type": "button"
        })
예제 #28
0
class EditPermissionGroupForm(Form):
    """
        wtforms_json 是用于Json数据格式的验证引入的。
        1、在有JSON数据的Form 里init()它,即可解决JSON数据无法通过验证的问题
        """
    wtforms_json.init()
    id = wtforms.IntegerField(render_kw={"type": "hidden"})

    name = wtforms.StringField(label="权限组",
                               validators=[
                                   DataRequired("请输入权限组"),
                                   Length(4, 16, message="权限组长度必须在4-16个字符之间")
                               ],
                               description="权限组",
                               render_kw={
                                   "id": "name",
                                   "class": "input-text size-L",
                                   "placeholder": "Role name"
                               })

    description = wtforms.StringField(label="组描述",
                                      validators=[
                                          DataRequired("请输入描述"),
                                          Length(4,
                                                 32,
                                                 message="组描述长度必须在4-32个字符之间")
                                      ],
                                      description="组描述",
                                      render_kw={
                                          "id": "description",
                                          "class": "input-text size-L",
                                          "placeholder": "该组是负责搞什么的呢?"
                                      })
    submit = wtforms.SubmitField(
        render_kw={
            "class": "btn btn-success radius size-L button",
            "value": "       提      交     ",
            "type": "button"
        })
예제 #29
0
class SignUpForm(Form):
    wtforms_json.init()
    name = wtforms.StringField(label="用户名",
                               validators=[
                                   DataRequired("请输入用户名"),
                               ],
                               description="用户名",
                               render_kw={
                                   "id": "name",
                                   "class": "input-text size-L",
                                   "placeholder": "username"
                               })

    @staticmethod
    def validate_name(self, field):
        """
        如果用户已经有了,就不让注册
        :param self:
        :param field:
        :return:
        """
        if User.by_name(field.data) is not None:
            raise ValidationError("该用户已经有人注册")

    password = wtforms.StringField(label="密码",
                                   validators=[DataRequired("请输入密码")],
                                   description="密码",
                                   render_kw={
                                       "type": "password",
                                       "class": "input-text size-L",
                                       "id": "password",
                                       "autocomplete": "off",
                                       "placeholder": "密码"
                                   })
    confirmation = wtforms.StringField(label="确认密码",
                                       validators=[
                                           DataRequired("请重输密码"),
                                           EqualTo("password",
                                                   message="两次密码输入不一致")
                                       ],
                                       description="重复输入密码",
                                       render_kw={
                                           "type": "password",
                                           "class": "input-text size-L",
                                           "id": "password",
                                           "autocomplete": "off",
                                           "placeholder": "密码"
                                       })
    captcha = wtforms.StringField(validators=[DataRequired("请输入验证码")],
                                  description="验证码",
                                  render_kw={
                                      "id": "captcha",
                                      "class": "input-text size-L",
                                      "style": "width:140px"
                                  })

    @staticmethod
    def validate_captcha(field):
        """
        通过Form自定义验证,作用是用于验证码校验
        :param field:
        :return:
        """
        captcha = redis.get('captcha')
        if captcha is None:
            raise ValidationError("验证码不合法!")
        elif str(redis.get('captcha'),
                 encoding='utf-8').lower() != field.data.lower():
            raise ValidationError('验证码不正确!')
예제 #30
0
def create_app(package_name, static_url_path=None, settings_override=None):
    """Creates a configured Flask instance.

    :param package_name: application package name
    :param package_path: application package path
    :param settings_override: a dictionary of settings to override
    """


    app = SilentlyFlask(package_name, instance_relative_config=True,
                static_url_path=static_url_path)

    # Load the config file.
    # TODO: This could be refactored to be more dynamic.
    app.config.from_object('silently.config')

    # Override config where specified.
    if settings_override:
        app.config.update(**settings_override)

    # Let's use a regex converter for more power.
    app.url_map.converters['regex'] = RegexConverter

    loader = jinja2.ChoiceLoader([
        app.jinja_loader,
        jinja2.FileSystemLoader(path.join(path.dirname(__file__), 'templates'))
    ])
    app.jinja_loader = loader

    # TODO: These error handler inits must be refactored.
    security.init_app(app, MongoEngineUserDatastore(None, User, Role),
                      register_blueprint=False)

    # Initialize flask_redis.
    redis.init_app(app)

    # Initialize flask_cache for memoize functionality.
    cache.init_app(app)

    # Initialize mongo_engine for MongoDB ORM like features.
    mongo_engine.init_app(app)

    # Use Redis as the simple key value store for sessions.
    store = RedisStore(redis)
    KVSessionExtension().init_app(app, session_kvstore=store)

    # Initialize flask_login manager.
    login_manager.init_app(app)

    # Set a custom anonymous object.
    login_manager.anonymous_user = AnonymousUser

    # Initialize flask_principal for resource access control.
    principals.init_app(app)

    # There are lots of legacy proxy servers in the wild that do not allow
    # certain methods like PATCH. To overcome this it is necessary to specify
    # the method in a header, and use middleware to transform the request
    # before it is routed.
    app.wsgi_app = ProxyFix(HTTPMethodOverrideMiddleware(app.wsgi_app))

    # Send emails in case of server errors. This handler is used with calls
    # to flask.log_exception.
    if app.config['ENABLE_ERROR_EMAIL']:
        email_errors.init_app(app)

    # Allow CSRF tokens to be transmitted in JSON data.
    wtforms_json.init()

    # Init CSRF helper.
    csrf.init_app(app)

    # Initialize signal handlers.
    signals.init_app(app)

    # Initialize Error Handler
    error_handler.init_app(app)

    # Initialize the ordrin API.
    ordrin_api.init_app(app)

    return app
예제 #31
0
from wtforms_json import init

init()
예제 #32
0
from __future__ import unicode_literals
import logging
import pkg_resources

from pyramid.i18n import TranslationStringFactory
import wtforms_json
wtforms_json.init()  # flake8: noqa

from . import models

log = logging.getLogger('occams').getChild(__name__)

_ = TranslationStringFactory(__name__)

__prefix__ = '/imports'
__title__ = _(u'Imports')
__version__ = pkg_resources.require(__name__)[0].version


def initdb(connectable):  # pragma: no cover
    models.ImportsModel.metadata.create_all(connectable)


def includeme(config):

    config.registry.settings['occams.apps']['occams_imports'] = {
        'name': 'imports',
        'title': _(u'Imports'),
        'package': 'occams_imports',
        'route': 'imports.index',
        'version': __version__
예제 #33
0
from __future__ import unicode_literals
import logging
import pkg_resources

from pyramid.i18n import TranslationStringFactory
import wtforms_json; wtforms_json.init()  # flake8: noqa

from . import models


log = logging.getLogger('occams').getChild(__name__)

_ = TranslationStringFactory(__name__)

__prefix__ = '/imports'
__title__ = _(u'Imports')
__version__ = pkg_resources.require(__name__)[0].version


def initdb(connectable): # pragma: no cover
    models.ImportsModel.metadata.create_all(connectable)


def includeme(config):

    config.registry.settings['occams.apps']['occams_imports'] = {
        'name': 'imports',
        'title': _(u'Imports'),
        'package': 'occams_imports',
        'route': 'imports.index',
        'version': __version__
예제 #34
0
def _initialize_wtforms_json(app):
    wtforms_json.init()
    return app
예제 #35
0
from flask import Flask, redirect
from flask_appbuilder import AppBuilder, IndexView, SQLA
from flask_appbuilder.baseviews import expose
from flask_compress import Compress
from flask_migrate import Migrate
from flask_talisman import Talisman
from flask_wtf.csrf import CSRFProtect
import wtforms_json

from superset import config
from superset.connectors.connector_registry import ConnectorRegistry
from superset.security import SupersetSecurityManager
from superset.utils.core import pessimistic_connection_handling, setup_cache
from superset.utils.log import DBEventLogger, get_event_logger_from_cfg_value

wtforms_json.init()

APP_DIR = os.path.dirname(__file__)
CONFIG_MODULE = os.environ.get("SUPERSET_CONFIG", "superset.config")

if not os.path.exists(config.DATA_DIR):
    os.makedirs(config.DATA_DIR)

app = Flask(__name__)
app.config.from_object(CONFIG_MODULE)
conf = app.config

#################################################################
# Handling manifest file logic at app start
#################################################################
MANIFEST_FILE = APP_DIR + "/static/assets/dist/manifest.json"
예제 #36
0
from __future__ import unicode_literals
import logging
import pkg_resources

from pyramid.i18n import TranslationStringFactory
import wtforms_json
wtforms_json.init()  # monkey-patch wtforms to accept JSON data

from . import models

log = logging.getLogger('occams').getChild(__name__)

_ = TranslationStringFactory(__name__)

__prefix__ = '/lims'
__title__ = _(u'LIMS')
__version__ = pkg_resources.require(__name__)[0].version


def initdb(connectable):
    assert 'blame' in connectable.info, 'Need someone to blame!'
    models.LimsModel.metadata.create_all(connectable)


def includeme(config):

    config.registry.settings['occams.apps']['occams_lims'] = {
        'name': 'lims',
        'title': _(u'LIMS'),
        'package': 'occams_lims',
        'route': 'lims.index',
예제 #37
0
 def setup(self):
     wtforms_json.init()
예제 #38
0
from __future__ import unicode_literals
import decimal
import datetime
import logging
from importlib import import_module
import pkg_resources

import six
from pyramid.authorization import ACLAuthorizationPolicy
from pyramid.config import Configurator
from pyramid.i18n import TranslationStringFactory
from pyramid.renderers import JSON
from pyramid.settings import aslist
from pyramid_who.whov2 import WhoV2AuthenticationPolicy
from pyramid.settings import asbool
import wtforms_json; wtforms_json.init()

__version__ = pkg_resources.require(__name__)[0].version

_ = TranslationStringFactory(__name__)

log = logging.getLogger(__name__)

from .settings import piwik_from_config
from .security import RootFactory, groupfinder  # NOQA


settings_defaults = {
    'piwik.enabled': False,

    # Ignored unless static_view is set to true
예제 #39
0
파일: login.py 프로젝트: jinxiu89/torWones
class LoginForm(Form):
    """
    wtforms_json 是用于Json数据格式的验证引入的。
    1、在有JSON数据的Form 里init()它,即可解决JSON数据无法通过验证的问题
    """
    wtforms_json.init()
    name = wtforms.StringField(label="用户名",
                               validators=[
                                   DataRequired("请输入用户名"),
                                   Length(4, 16, message="长度必须在4-16个字符之间")
                               ],
                               description="用户名",
                               render_kw={
                                   "id": "name",
                                   "class": "input-text size-L",
                                   "placeholder": "username"
                               })

    @staticmethod
    def validate_name(self, field):
        """
        如果用户已经有了,就不让注册
        :param self:
        :param field:
        :return:
        """
        if User.by_name(field.data) is None:
            raise ValidationError("用户没注册")

    password = wtforms.StringField(label="管理员密码",
                                   validators=[DataRequired("请输入密码")],
                                   description="密码",
                                   render_kw={
                                       "type": "password",
                                       "class": "input-text size-L",
                                       "id": "password",
                                       "autocomplete": "off",
                                       "placeholder": "密码"
                                   })

    @staticmethod
    def validate_password(self, password):

        pass

    captcha = wtforms.StringField(validators=[DataRequired("请输入验证码")],
                                  description="验证码",
                                  render_kw={
                                      "id": "captcha",
                                      "class": "input-text size-L",
                                      "style": "width:140px"
                                  })

    @staticmethod
    def validate_captcha(self, field):
        """
        通过Form自定义验证,作用是用于验证码校验
        :param self:
        :param field:
        :return:
        """
        captcha = redis.get('captcha')
        if captcha is None:
            raise ValidationError("验证码不合法!")
        elif str(redis.get('captcha'),
                 encoding='utf-8').lower() != field.data.lower():
            raise ValidationError('验证码不正确!')

    submit = wtforms.SubmitField(
        render_kw={
            "class": "btn btn-success radius size-L button",
            "value": "       登      录     ",
            "type": "button"
        })
예제 #40
0
def create_app(config, name=__name__):
    app = FlaskAPI(__name__, static_folder='../build')

    app.config.from_object(config)

    if app.config.get("IS_DEVELOPMENT", False):
        logging.basicConfig(level=logging.DEBUG)
        coloredlogs.install()

        # To enable logging for flask-cors,
        # logging.getLogger('flask_cors').level = logging.DEBUG
    else:
        logging.basicConfig(level=logging.ERROR)

    JWT(app, authenticate, identity)
    CORS(app, automatic_options=True, supports_credentials=True)

    db.init_app(app)
    ma.init_app(app)

    is_sqlite = app.config.get("SQLALCHEMY_DATABASE_URI",
                               "").startswith('sqlite:')

    logging.debug("%s", app.config.get("SQLALCHEMY_DATABASE_URI"))

    if is_sqlite:
        migrate.init_app(app, db, render_as_batch=is_sqlite)
    else:
        migrate.init_app(app, db, render_as_batch=is_sqlite)

    wtforms_json.init()

    app.register_blueprint(auth_blueprint)
    app.register_blueprint(views_blueprint)

    def dir_last_updated(folder):
        return str(
            max(
                os.path.getmtime(os.path.join(root_path, f))
                for root_path, dirs, files in os.walk(folder) for f in files))

    # Handle errors and turn them into json
    @app.errorhandler(Exception)
    def handle_error(e):
        trace = traceback.format_exc()

        app.logger.error("%s", trace)
        return err(str(e)), status.HTTP_500_INTERNAL_SERVER_ERROR

    # Serve React App
    @app.route('/', defaults={'path': ''})
    @app.route('/<path:path>')
    def serve(path):
        if path != "" and os.path.exists(app.static_folder + '/' + path):
            return send_from_directory(app.static_folder, path)
        else:
            return send_from_directory(app.static_folder, 'index.html')

    app.logger.debug(f"* App running in mode: {app.config.get('ENV')}")

    return app
def validate_registration_field(attendee):
    wtforms_json.init()
    form = RegistrationForm.from_json(json.loads(attendee))
    
    # if form.validate():
    return form
예제 #42
0
 def json_init(cls):
     wtforms_json.init()
예제 #43
0
def configure_extentions(app):
    from app.extensions import db
    import wtforms_json
    db.init_app(app)
    wtforms_json.init()
예제 #44
0
filename = os.path.join(os.path.dirname(__file__), '..', '..', 'conf')
with open(filename) as conf:
    for line in conf:
        line_array = line.split('=')
        if line_array[0] == "DATABASE_NAME":
            DATABASE_NAME = line_array[1].strip()
        if line_array[0] == "DATABASE_USER":
            DATABASE_USER = line_array[1].strip()
        if line_array[0] == "DATABASE_PASSWORD":
            DATABASE_PASSWORD = line_array[1].strip()

app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://{}:{}@localhost:5432/{}'.format(DATABASE_USER, DATABASE_PASSWORD, DATABASE_NAME)

db = SQLAlchemy(app)

wtforms_json.init()


class ModelObject(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    date_updated = db.Column(db.TIMESTAMP, server_default=db.func.now(), onupdate=db.func.current_timestamp())

    # Added methods
    def save(self):
        db.session.add(self)
        db.session.commit()

    def update(self, json):
        self.set_columns(**json)
        db.session.commit()
예제 #45
0
from __future__ import unicode_literals
import decimal
import datetime
import logging
from importlib import import_module
import pkg_resources

import six
from pyramid.authorization import ACLAuthorizationPolicy
from pyramid.config import Configurator
from pyramid.i18n import TranslationStringFactory
from pyramid.renderers import JSON
from pyramid.settings import aslist
from pyramid_who.whov2 import WhoV2AuthenticationPolicy
from pyramid.settings import asbool
import wtforms_json; wtforms_json.init()

__version__ = pkg_resources.require(__name__)[0].version

_ = TranslationStringFactory(__name__)

log = logging.getLogger(__name__)

from .settings import piwik_from_config
from .security import RootFactory, groupfinder  # NOQA


settings_defaults = {
    'piwik.enabled': False,

    # Ignored unless static_view is set to true
예제 #46
0
def create_app():
    app = Flask(__name__)

    app.config.from_object('sampleserve.config.settings')

    # Turn off strict slashes
    app.url_map.strict_slashes = False

    # Initialize Flask_Mail
    mail.init_app(app)

    app.register_blueprint(api, url_prefix='/api/v1', subdomain='<lab_id>')
    app.register_blueprint(auth,
                           url_prefix='/api/v1/auth',
                           subdomain='<lab_id>')
    app.register_blueprint(reports,
                           url_prefix='/api/v1/reports',
                           subdomain='<lab_id>')
    app.register_blueprint(imports,
                           url_prefix='/api/v1/imports',
                           subdomain='<lab_id>')
    app.register_blueprint(bplabs, url_prefix='/api/v1/labs')

    register_api(app, labs, '/api/v1/labs/', subdomain='<lab_id>')
    register_api(app, roles, '/api/v1/roles/', subdomain='<lab_id>')
    register_api(app, samples, '/api/v1/samples/', subdomain='<lab_id>')
    register_api(app, substances, '/api/v1/substances/', subdomain='<lab_id>')
    register_api(app,
                 substancegroups,
                 '/api/v1/substancegroups/',
                 subdomain='<lab_id>')
    register_api(app, substances, '/api/v1/substances/', subdomain='<lab_id>')
    register_api(app, criterias, '/api/v1/criterias/', subdomain='<lab_id>')
    register_api(app, states, '/api/v1/states/', subdomain='<lab_id>')
    register_api(app, sites, '/api/v1/sites/', subdomain='<lab_id>')
    register_api(app, sitedata, '/api/v1/sitedata/', subdomain='<lab_id>')
    register_api(app, clients, '/api/v1/clients/', subdomain='<lab_id>')
    register_api(app, uploads, '/api/v1/uploads/', subdomain='<lab_id>')
    register_api(app, schedules, '/api/v1/schedules/', subdomain='<lab_id>')
    register_api(app,
                 schedulewelltests,
                 '/api/v1/schedulewelltests/',
                 subdomain='<lab_id>')
    register_api(app, contacts, '/api/v1/contacts/', subdomain='<lab_id>')
    register_api(app, users, '/api/v1/users/', subdomain='<lab_id>')
    register_api(app,
                 consultants,
                 '/api/v1/consultants/',
                 subdomain='<lab_id>')
    register_api(app, companies, '/api/v1/companies/', subdomain='<lab_id>')
    register_api(app, managers, '/api/v1/managers/', subdomain='<lab_id>')
    register_api(app, samplers, '/api/v1/samplers/', subdomain='<lab_id>')
    register_api(app, offices, '/api/v1/offices/', subdomain='<lab_id>')
    register_api(app, wells, '/api/v1/wells/', subdomain='<lab_id>')
    register_api(app, wellimages, '/api/v1/wellimages/', subdomain='<lab_id>')
    register_api(app,
                 frequencies,
                 '/api/v1/frequencies/',
                 subdomain='<lab_id>')
    register_api(app, tests, '/api/v1/tests/', subdomain='<lab_id>')
    register_api(app,
                 testmaterials,
                 '/api/v1/testmaterials/',
                 subdomain='<lab_id>')
    register_api(app, sitemaps, '/api/v1/sitemaps/', subdomain='<lab_id>')
    register_api(app,
                 sitemapwells,
                 '/api/v1/sitemapwells/',
                 subdomain='<lab_id>')

    app.add_url_rule('/api/v1/user', 'user', get_user, subdomain='<lab_id>')
    app.add_url_rule('/api/v1/lab', 'lab', get_lab, subdomain='<lab_id>')

    app.register_error_handler(UnprocessableEntity,
                               handle_unprocessable_entity)
    app.register_error_handler(BadUpload, handle_bad_upload)
    app.register_error_handler(BadInvite, handle_bad_invite)
    app.register_error_handler(BadRequest, handle_bad_request)
    app.register_error_handler(httplib.NOT_FOUND, handle_page_not_found)
    app.register_error_handler(httplib.METHOD_NOT_ALLOWED,
                               handle_method_not_allowed)
    app.register_error_handler(httplib.UNAUTHORIZED, handle_unauthorized)
    app.register_error_handler(FormError, handle_form_error)

    # register some custom app filters
    app.jinja_env.filters['firstname'] = firstname

    db.init_app(app)
    bcrypt.init_app(app)
    auth_manager.init_app(app)

    if app.config.get('DEBUG'):
        CORS(app,
             origins=app.config.get('CORS_SERVER_NAME'),
             supports_credentials=True)

    # Activate wtforms json helpers
    wtforms_json.init()

    # Activate sentry
    if not app.config.get('DEBUG'):
        sentry = Sentry(
            app,
            dsn=
            'http://*****:*****@sentry.nickwoodhams.com/19'
        )

    return app
예제 #47
0
import logging
import pkg_resources

from pyramid.i18n import TranslationStringFactory
import wtforms_json; wtforms_json.init()  # monkey-patch wtforms to accept JSON data

log = logging.getLogger('occams').getChild(__name__)

_ = TranslationStringFactory(__name__)

__prefix__ = '/forms'
__title__ = _(u'Forms')
__version__ = pkg_resources.require(__name__)[0].version


def includeme(config):

    config.registry.settings['occams.apps']['occams_forms'] = {
        'name': 'forms',
        'title': _(u'Forms'),
        'package': 'occams_forms',
        'route': 'forms.index',
        'version': __version__
    }

    config.include('.assets')
    config.include('.routes')
    config.scan()