当前位置: 首页>>代码示例>>Python>>正文


Python json.load方法代码示例

本文整理汇总了Python中flask.json.load方法的典型用法代码示例。如果您正苦于以下问题:Python json.load方法的具体用法?Python json.load怎么用?Python json.load使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在flask.json的用法示例。


在下文中一共展示了json.load方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: demo4

# 需要导入模块: from flask import json [as 别名]
# 或者: from flask.json import load [as 别名]
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),并且携带参数 
开发者ID:HaoZhang95,项目名称:Python24,代码行数:23,代码来源:demo1.py

示例2: preload_cache

# 需要导入模块: from flask import json [as 别名]
# 或者: from flask.json import load [as 别名]
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) 
开发者ID:HendrikStrobelt,项目名称:Seq2Seq-Vis,代码行数:23,代码来源:server.py

示例3: get_conf_json

# 需要导入模块: from flask import json [as 别名]
# 或者: from flask.json import load [as 别名]
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 
开发者ID:fufuok,项目名称:FF.PyAdmin,代码行数:20,代码来源:__init__.py

示例4: post

# 需要导入模块: from flask import json [as 别名]
# 或者: from flask.json import load [as 别名]
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}) 
开发者ID:huskar-org,项目名称:huskar,代码行数:26,代码来源:instance.py

示例5: make_env

# 需要导入模块: from flask import json [as 别名]
# 或者: from flask.json import load [as 别名]
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 
开发者ID:beavyHQ,项目名称:beavy,代码行数:31,代码来源:app.py

示例6: setup_statics

# 需要导入模块: from flask import json [as 别名]
# 或者: from flask.json import load [as 别名]
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) 
开发者ID:beavyHQ,项目名称:beavy,代码行数:14,代码来源:app.py

示例7: _limiter_key

# 需要导入模块: from flask import json [as 别名]
# 或者: from flask.json import load [as 别名]
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 
开发者ID:beavyHQ,项目名称:beavy,代码行数:10,代码来源:app.py

示例8: validate_v0

# 需要导入模块: from flask import json [as 别名]
# 或者: from flask.json import load [as 别名]
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
        ) 
开发者ID:alphagov,项目名称:notifications-api,代码行数:12,代码来源:__init__.py

示例9: Load_Web_App_Configuration

# 需要导入模块: from flask import json [as 别名]
# 或者: from flask.json import load [as 别名]
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() 
开发者ID:matamorphosis,项目名称:Scrummage,代码行数:34,代码来源:Scrummage.py

示例10: swagger_api_docs_yml

# 需要导入模块: from flask import json [as 别名]
# 或者: from flask.json import load [as 别名]
def swagger_api_docs_yml():
    with open('swagger.json') as fd:
        json_data = json.load(fd)

    return jsonify(json_data) 
开发者ID:PacktPublishing,项目名称:Hands-on-Microservices-with-Python-Product-Service,代码行数:7,代码来源:routes.py

示例11: load_app

# 需要导入模块: from flask import json [as 别名]
# 或者: from flask.json import load [as 别名]
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 
开发者ID:oasis-open,项目名称:cti-taxii-server,代码行数:12,代码来源:__init__.py

示例12: __init__

# 需要导入模块: from flask import json [as 别名]
# 或者: from flask.json import load [as 别名]
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')
        ) 
开发者ID:RagtagOpen,项目名称:nomad,代码行数:14,代码来源:oauth.py

示例13: _get_file

# 需要导入模块: from flask import json [as 别名]
# 或者: from flask.json import load [as 别名]
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 
开发者ID:bluecatlabs,项目名称:gateway-workflows,代码行数:17,代码来源:cache_example_page.py

示例14: main

# 需要导入模块: from flask import json [as 别名]
# 或者: from flask.json import load [as 别名]
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() 
开发者ID:llvm,项目名称:llvm-zorg,代码行数:47,代码来源:statusclient.py

示例15: build_url

# 需要导入模块: from flask import json [as 别名]
# 或者: from flask.json import load [as 别名]
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) 
开发者ID:lobeck,项目名称:flask-bower,代码行数:60,代码来源:__init__.py


注:本文中的flask.json.load方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。