Python flask.json.load() Examples

The following are 15 code examples of flask.json.load(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module flask.json , or try the search function .
Example #1
Source File: demo1.py    From Python24 with MIT License 7 votes vote down vote up
def demo4():

    json_dict = {
        'name': 'zhangsan',
        'age': 18

    }

    # 使用falsk.json包下的dumps方法把一个字典对象转换为json格式的字符串
    json_str = json.dumps(json_dict)

    # 使用laod方法把json格式的字符串转换为一个字典对象
    # dict_obj = json.load('{ "name": "zhangsan","age": 18}')

    # json.dunps返回的json字符串在浏览器中Content-type是text/html
    # 但是使用jsonify来处理字典对象的话返回的也是str,但是浏览器的content-type就变成了application/json
    return jsonify(json_dict)


# 直接使用redirect函数进行重定向
# 重定向的反向解析:使用重定向路由的视图函数名字url_for(XXX),并且携带参数 
Example #2
Source File: server.py    From Seq2Seq-Vis with Apache License 2.0 6 votes vote down vote up
def preload_cache(cache):
    if len(cache) > 0 and os.path.exists(cache):
        all_files = [os.path.join(cache, f) for f in os.listdir(cache) if
                     os.path.isfile(os.path.join(cache, f))]
        for file in all_files:
            if file.endswith('.json'):
                with open(file, 'r') as f:
                    a = json.load(f)
                    print(a['request'])
                    request = a['request']
                    neighbors = request.get('neighbors', [''])
                    partials = request.get('partial', [''])
                    force_attn = request.get('force_attn', [''])
                    # Make empty lists empty:
                    partials = [] if partials == [''] else partials
                    neighbors = [] if neighbors == [''] else neighbors
                    force_attn = [] if force_attn == [''] else force_attn
                    translation_id = request['in'] + str(partials) + str(
                        force_attn)
                    cache_translate.preload(translation_id, [a])
                    pre_cached.append(request) 
Example #3
Source File: __init__.py    From FF.PyAdmin with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_conf_json(path, file):
    """
    通用: 获取 JSON 配置文件

    :param path: 相对于 conf, e.g. bgp
    :param file: 文件名, 不带扩展名, e.g. as-name
    :return: dict,e.g. {'123': '成都'}
    """
    ret = {}
    file = os.path.join(current_app.root_path, 'conf', path, file + '.json')

    try:
        with open(file, 'r', encoding='utf-8') as f:
            ret = json.load(f)
    except Exception as e:
        current_app.logger.error('{0!r} {1}'.format(e, file))

    return ret 
Example #4
Source File: instance.py    From huskar with MIT License 6 votes vote down vote up
def post(self):
        """Imports multiple instances of service, switch or config.

        The ``write`` authority is required. See :ref:`application_auth` also.

        The data which will be imported should be included in the request body
        as ``import_file`` field in ``multipart/form-data`` encoded.

        :form import_file: The data schema is the same as the exporting API.
        :form overwrite: ``1`` if you want to overwrite existed instances.
        :<header Content-Type: ``multipart/form-data``
        :<header Authorization: Huskar Token (See :ref:`token`)
        :status 200: The request is successful. ``import_num`` will be
                     responded also.
        """
        overwrite = request.values.get('overwrite', type=int, default=0)
        content = request.files.get('import_file', type=json.load) or {}
        content = instance_schema.load(content, many=True).data
        instance_list = self.set_instance_list(content, bool(overwrite))
        affected = sum(1 for i in instance_list if i is not None)
        audit_log.emit(
            self.IMPORT_ACTION_TYPES[self.subdomain], datalist=content,
            overwrite=bool(overwrite), affected=affected)
        return api_response({'import_num': affected}) 
Example #5
Source File: app.py    From beavy with Mozilla Public License 2.0 5 votes vote down vote up
def make_env(app):
    # environment-based configuration loading
    env = Environments(app, var_name="BEAVY_ENV")

    env.from_yaml(os.path.join(BASE_DIR, 'config.yml'))
    # env.from_yaml(os.path.join(os.getcwd(), 'config.yml'))
    with open(os.path.join(os.getcwd(), 'config.yml'), "r") as r:
        deepmerge(app.config, yaml.load(r))

    # allow for environment variables to update items
    if os.environ.get("BEAVY_CONFIG_FROM_ENV", False):
        app.config.update(os.environ)

        if "DATABASE_URL" in os.environ:
            app.config["SQLALCHEMY_DATABASE_URI"] = os.environ["DATABASE_URL"]
        if "RABBITMQ_URL" in os.environ:
            app.config["CELERY_BROKER_URL"] = os.environ["RABBITMQ_URL"]
        if "REDIS_URL" in os.environ:
            app.config["RATELIMIT_STORAGE_URL"] = os.environ["REDIS_URL"]
            app.config["CACHE_REDIS_URL"] = os.environ["REDIS_URL"]

    # update social buttons
    _FLBLPRE = "flask_social_blueprint.providers.{}"
    if "SOCIAL_BLUEPRINT" not in app.config:
        app.config["SOCIAL_BLUEPRINT"] = dict([
            ("." in name and name or _FLBLPRE.format(name), values)
            for name, values in app.config.get("SOCIAL_LOGINS").items()])

    return env 
Example #6
Source File: app.py    From beavy with Mozilla Public License 2.0 5 votes vote down vote up
def setup_statics(app):
    files = dict(main_js="main.js", main_css="main.css")
    if not app.debug:
        with open(os.path.join(STATIC_FOLDER, "manifest.json")) as r:
            manifest = json.load(r)

        files = dict([(key.replace(".", "_"), value)
                     for (key, value) in manifest.items()])

    @app.context_processor
    def injnect_manifest():
        return dict(static_files=files) 
Example #7
Source File: app.py    From beavy with Mozilla Public License 2.0 5 votes vote down vote up
def _limiter_key():
    if current_user.is_authenticated:
        return "u_{}".format(current_user.id)
    return "ip_{}".format(get_ipaddr())
# --------------------------- Setting stuff up in order ----------


# load the environment and configuration 
Example #8
Source File: __init__.py    From notifications-api with MIT License 5 votes vote down vote up
def validate_v0(json_to_validate, schema_filename):
    schema_dir = os.path.join(os.path.dirname(__file__), 'schemas/v0')
    resolver = jsonschema.RefResolver('file://' + schema_dir + '/', None)
    with open(os.path.join(schema_dir, schema_filename)) as schema:
        jsonschema.validate(
            json_to_validate,
            json.load(schema),
            format_checker=jsonschema.FormatChecker(),
            resolver=resolver
        ) 
Example #9
Source File: Scrummage.py    From Scrummage with GNU General Public License v3.0 5 votes vote down vote up
def Load_Web_App_Configuration():

        try:
            File_Dir = os.path.dirname(os.path.realpath('__file__'))
            Configuration_File = os.path.join(File_Dir, 'plugins/common/config/config.json')
            logging.info(f"{General.Date()} Loading web application's configuration data.")

            with open(Configuration_File) as JSON_File:
                Configuration_Data = json.load(JSON_File)
                WA_Details = Configuration_Data['web-app']
                WA_Debug = WA_Details['debug']
                WA_Host = WA_Details['host']
                WA_Port = WA_Details['port']
                WA_Cert_File = WA_Details['certificate-file']
                WA_Key_File = WA_Details['key-file']
                WA_API_Secret = WA_Details['api-secret']
                WA_API_Validity_Limit = int(WA_Details['api-validity-minutes'])
                WA_API_Max_Calls = int(WA_Details['api-max-calls'])
                WA_API_Period = int(WA_Details['api-period-in-seconds'])

            if WA_API_Validity_Limit < 60:
                sys.exit("[-] API Key Validity Limit too short. Minimum should be 60 minutes.")

            if WA_Host and WA_Port and WA_Cert_File and WA_Key_File and WA_API_Secret and WA_API_Validity_Limit and WA_API_Max_Calls and WA_API_Period:
                return [WA_Debug, WA_Host, WA_Port, WA_Cert_File, WA_Key_File, WA_API_Secret, WA_API_Validity_Limit, WA_API_Max_Calls, WA_API_Period]

            else:
                return None

        except Exception as e:
            logging.warning(f"{General.Date()} {str(e)}")
            sys.exit() 
Example #10
Source File: routes.py    From Hands-on-Microservices-with-Python-Product-Service with MIT License 5 votes vote down vote up
def swagger_api_docs_yml():
    with open('swagger.json') as fd:
        json_data = json.load(fd)

    return jsonify(json_data) 
Example #11
Source File: __init__.py    From cti-taxii-server with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def load_app(config_file):
    with open(config_file, "r") as f:
        configuration = json.load(f)

    set_config(application_instance, "users", configuration)
    set_config(application_instance, "taxii", configuration)
    set_config(application_instance, "backend", configuration)
    register_blueprints(application_instance)

    return application_instance 
Example #12
Source File: oauth.py    From nomad with Apache License 2.0 5 votes vote down vote up
def __init__(self):
        super(GoogleSignIn, self).__init__('google')
        googleinfo = urlopen('https://accounts.google.com/.well-known/openid-configuration')
        google_params = json.load(googleinfo)
        self.service = OAuth2Service(
            name='google',
            client_id=self.consumer_id,
            client_secret=self.consumer_secret,
            authorize_url=google_params.get('authorization_endpoint'),
            base_url=google_params.get('userinfo_endpoint'),
            access_token_url=google_params.get('token_endpoint')
        ) 
Example #13
Source File: cache_example_page.py    From gateway-workflows with Apache License 2.0 5 votes vote down vote up
def _get_file(file, exp=0):
    print(file)
    try:
        seconds = int(_file_age(file))
        if exp != 0 and seconds > exp:
            return {}
    except Exception as e:
        print(e)
    try:
        with open(file, 'r') as f:

            datastore = json.load(f)
    except:
        datastore = {}
    return datastore 
Example #14
Source File: statusclient.py    From llvm-zorg with Apache License 2.0 4 votes vote down vote up
def main():
    import os
    import sys
    from optparse import OptionParser, OptionGroup
    parser = OptionParser("""\
%%prog [options] <path> <master url>

A simple tool for testing the BuildBot StatusClient.
""")
    opts, args = parser.parse_args()
    if len(args) != 2:
        parser.error("invalid arguments")

    path,master_url = args

    # Load the static client object if it exists.
    sc = None
    if os.path.exists(path):
        file = open(path)
        object = json.load(file)
        file.close()

        sc = StatusClient.fromdata(object)

        # Check that this instance matches what the user requested.
        if (sc.master_url != master_url):
            sc = None

    # Create a new client instance if necessary.
    if sc is None:
        sc = StatusClient(master_url)

    # Now wait for events and print them
    try:
        while 1:
            for event in sc.pull_events():
                print time.time(), event
            time.sleep(.1)
    except KeyboardInterrupt:
        print "(interrupted, stopping)"

    # Save the current instance.
    file = open(path, "w")
    json.dump(sc.todata(), file)
    file.close() 
Example #15
Source File: __init__.py    From flask-bower with GNU General Public License v2.0 4 votes vote down vote up
def build_url(component, filename, **values):
    """
    search bower asset and build url

    :param component: bower component (package)
    :type component: str
    :param filename: filename in bower component - can contain directories (like dist/jquery.js)
    :type filename: str
    :param values: additional url parameters
    :type values: dict[str, str]
    :return: url
    :rtype: str | None
    """
    root = current_app.config['BOWER_COMPONENTS_ROOT']
    bower_data = None
    package_data = None

    # check if component exists in bower_components directory
    if not os.path.isdir(os.path.join(current_app.root_path, root, component)):
        # FallBack to default url_for flask
        return None

    # load bower.json of specified component
    bower_file_path = os.path.join(current_app.root_path, root, component, 'bower.json')
    if os.path.exists(bower_file_path):
        with open(bower_file_path, 'r') as bower_file:
            bower_data = json.load(bower_file)

    # check if package.json exists and load package.json data
    package_file_path = os.path.join(current_app.root_path, root, component, 'package.json')
    if os.path.exists(package_file_path):
        with open(package_file_path, 'r') as package_file:
            package_data = json.load(package_file)

    # check if specified file actually exists
    if not os.path.exists(os.path.join(current_app.root_path, root, component, filename)):
        return None

    # check if minified file exists (by pattern <filename>.min.<ext>
    # returns filename if successful
    if current_app.config['BOWER_TRY_MINIFIED']:
        if '.min.' not in filename:
            minified_filename = '%s.min.%s' % tuple(filename.rsplit('.', 1))
            minified_path = os.path.join(root, component, minified_filename)

            if os.path.exists(os.path.join(current_app.root_path, minified_path)):
                filename = minified_filename

    # determine version of component and append as ?version= parameter to allow cache busting
    if current_app.config['BOWER_QUERYSTRING_REVVING']:
        if bower_data is not None and 'version' in bower_data:
            values['version'] = bower_data['version']
        elif package_data is not None and 'version' in package_data:
            values['version'] = package_data['version']
        else:
            values['version'] = os.path.getmtime(os.path.join(current_app.root_path, root, component, filename))

    return url_for('bower.serve', component=component, filename=filename, **values)