Python flask.json.load() Examples

The following are code examples for showing how to use flask.json.load(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: Python24   Author: HaoZhang95   File: demo1.py    MIT License 6 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
Project: Seq2Seq-Vis   Author: HendrikStrobelt   File: server.py    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
Project: BloodTestReportOCR   Author: csxiaoyaojianxian   File: view.py    Apache License 2.0 6 votes vote down vote up
def update_report(fid,ss):
    # load json example
    with open('bloodtestdata.json') as json_file:
        data = json.load(json_file)

    for i in range(22):
        data['bloodtest'][i]['value'] = ss[i]
    json_data = json.dumps(data, ensure_ascii=False, indent=4)

    db.files.update_one({
        '_id': bson.objectid.ObjectId(fid)}, {
        '$set': {
            'report_data': json_data
        }
    }, upsert=False)


    file = db.files.find_one(bson.objectid.ObjectId(fid))
    report_data = bson.json_util.dumps(file['report_data'])
    print report_data 
Example 4
Project: rebble-appstore-api   Author: pebble-dev   File: commands.py    MIT License 6 votes vote down vote up
def import_likes():
    known_apps = set(x.id for x in App.query.options(load_only('id')))
    with open('users.txt') as f:
        for entry in f:
            uid, token = entry.strip().split()
            uid = int(uid)
            print(f"Importing user {uid}...")
            dev_portal = requests.get('https://dev-portal.getpebble.com/api/users/me',
                                      headers={'Authorization': f"Bearer {token}"})
            if dev_portal.status_code != 200:
                print(f"Skipping user {uid}: dev portal didn't load: {dev_portal.status_code}.")
                continue
            voted = set(dev_portal.json()['users'][0]['voted_ids'])
            db.session.add_all(UserLike(user_id=uid, app_id=x) for x in voted if x in known_apps)
            db.session.commit()
            print(f"Imported {len(voted)} likes.")
    print("Done.") 
Example 5
Project: rebble-appstore-api   Author: pebble-dev   File: commands.py    MIT License 6 votes vote down vote up
def new_release(pbw_file, release_notes):
    pbw = PBW(pbw_file, 'aplite')
    with pbw.zip.open('appinfo.json') as f:
        j = json.load(f)
    uuid = j['uuid']
    version = j['versionLabel']
    app = App.query.filter_by(app_uuid = uuid).one()
    release_old = Release.query.filter_by(app = app).order_by(Release.published_date).limit(1).one()
    print(f"Previous version {release_old.version}, new version {version}, release notes {release_old.release_notes}")
    if version == release_old.version:
        version = f"{version}-rbl"
    release_new = release_from_pbw(app, pbw_file,
                                   release_notes = release_notes,
                                   published_date = datetime.datetime.utcnow(),
                                   version = version,
                                   compatibility = release_old.compatibility)
    print(f"Uploading new version {version} of {release_old.app.id} ({release_old.app.title})...")
    upload_pbw(release_new, pbw_file)
    db.session.commit() 
Example 6
Project: bendercoin   Author: matejcik   File: storage.py    MIT License 5 votes vote down vote up
def load_transactions():
    global BLOCKS
    BLOCKS = {}
    with open("transactions.json") as f:
        data = json.load(f)
    for key, val in data.items():
        bl = Block.from_dict(val)
        num = bl.header.num
        BLOCKS[num] = bl

    return BLOCKS 
Example 7
Project: beavy   Author: beavyHQ   File: app.py    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 8
Project: beavy   Author: beavyHQ   File: app.py    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 9
Project: beavy   Author: beavyHQ   File: app.py    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 10
Project: Portfolio-Optimize   Author: IBM   File: run.py    Apache License 2.0 5 votes vote down vote up
def load():
    '''
    Populates investment portfolio with universe, benchmark(s), and current portfolio(s).
    Also populates variables needed for the drop-downs like what attributes to consider.
    '''
    constraints = parse_universe()
    data ={
        'user_portfolios':get_user_portfolio_list(),
        'benchmark_portfolios':get_benchmark_list(),
        'hard_constraints':constraints['hard_constraints'],
        'esg_constraints':constraints['esg_constraints'],
        'allocation_constraints':constraints['allocation_constraints']
    }
    return Response(json.dumps(data, indent=4,sort_keys=True), mimetype='application/json') 
Example 11
Project: vibe   Author: 3ll3d00d   File: targetcontroller.py    MIT License 5 votes vote down vote up
def readCache(self):
        cacheFile = os.path.join(self._dataDir, 'targetcache.json')
        if os.path.exists(cacheFile):
            try:
                with open(cacheFile, 'r') as outfile:
                    return json.load(outfile)
            except:
                logger.exception('Failed to load ' + cacheFile)
        return {} 
Example 12
Project: vibe   Author: 3ll3d00d   File: measurementcontroller.py    MIT License 5 votes vote down vote up
def reloadCompletedMeasurements(self):
        """
        Reloads the completed measurements from the backing store.
        """
        from pathlib import Path
        reloaded = [self.load(x.resolve()) for x in Path(self.dataDir).glob('*/*/*') if x.is_dir()]
        logger.info('Reloaded ' + str(len(reloaded)) + ' completed measurements')
        self.completeMeasurements = [x for x in reloaded if x is not None and x.status == MeasurementStatus.COMPLETE]
        self.failedMeasurements = [x for x in reloaded if x is not None and x.status == MeasurementStatus.FAILED] 
Example 13
Project: vibe   Author: 3ll3d00d   File: measurementcontroller.py    MIT License 5 votes vote down vote up
def load(self, path):
        """
        Loads a CompletedMeasurement from the path.á
        :param path: the path at which the data is found.
        :return: the measurement
        """
        meta = self._loadMetaFromJson(path)
        return CompleteMeasurement(meta, self.dataDir) if meta is not None else None 
Example 14
Project: vibe   Author: 3ll3d00d   File: measurementcontroller.py    MIT License 5 votes vote down vote up
def _loadMetaFromJson(self, path):
        """
        Reads the json meta into memory.
        :return: the meta.
        """
        try:
            with (path / 'metadata.json').open() as infile:
                return json.load(infile)
        except FileNotFoundError:
            logger.error('Metadata does not exist at ' + str(path))
            return None 
Example 15
Project: nebula   Author: nebula-orchestrator   File: api-manager.py    GNU General Public License v3.0 5 votes vote down vote up
def rabbit_login():
    rabbit_connection = rabbit_connect(rabbit_user, rabbit_password, rabbit_host, rabbit_port, rabbit_vhost,
                                       rabbit_heartbeat)
    rabbit_connection_channel = rabbit_create_channel(rabbit_connection)
    return rabbit_connection_channel


# read config file at startup
# load the login params from auth.json file or envvar 
Example 16
Project: Hands-on-Microservices-with-Python-User-Service   Author: PacktPublishing   File: routes.py    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 17
Project: Hands-on-Microservices-with-Python-Order-Service   Author: PacktPublishing   File: routes.py    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 18
Project: superdesk-ntb   Author: superdesk   File: ping_scanpix_test.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def setUp(self):
        with open(os.path.join(os.path.dirname(__file__), 'fixtures', 'published_item.json')) as f:
            self.item = json.load(f)
        self.app.data.insert('search_providers', [
            {
                '_id': bson.ObjectId(self.item['associations']['featuremedia']['ingest_provider']),
                'search_provider': 'scanpix(ntbkultur)',
                'config': {'username': 'foo', 'password': 'bar'},
            },
        ]) 
Example 19
Project: notifications-api   Author: alphagov   File: __init__.py    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 20
Project: Scrummage   Author: matamorphosis   File: Scrummage.py    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(General.Date() + " Loading web application's configuration data.")

        with open(Configuration_File) as JSON_File:
            Configuration_Data = json.load(JSON_File)

        for WA_Details in 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']

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

            else:
                return None

    except Exception as e:
        logging.warning(General.Date() + " " + str(e))
        sys.exit() 
Example 21
Project: WebCADViewer   Author: drhlxiao   File: routes.py    GNU General Public License v3.0 5 votes vote down vote up
def get_stat(fuuid):
    js="{'status':'error'}"
    try:
        server_filename=os.path.join(conf.project_directory(), '{}/stat.json'.format(fuuid))
        with open(server_filename) as f:
            #js=json.load(f)
            js=f.read()
            print type(js)
    except:
        pass
    resp = Response(js, status=200, mimetype='application/json')
    return resp 
Example 22
Project: WebCADViewer   Author: drhlxiao   File: routes.py    GNU General Public License v3.0 5 votes vote down vote up
def load_data(fuuid,puuid):
    js="{'status':'error'}"
    try:
        server_filename=os.path.join(conf.project_directory(), '{}/{}.json'.format(fuuid,puuid))
        with open(server_filename) as f:
            #js=json.load(f)
            js=f.read()
            print type(js)
    except:
        pass
    resp = Response(js, status=200, mimetype='application/json')
    return resp 
Example 23
Project: Hands-on-Microservices-with-Python-Product-Service   Author: PacktPublishing   File: routes.py    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 24
Project: examples   Author: WoTTsecurity   File: app.py    MIT License 5 votes vote down vote up
def check_auth(username, password):

    # Loading credentials from json file
    with open('/opt/wott/credentials/my_simple_web_app.json', 'r') as creds:
        creds_info = json.load(creds)

    creds_values = creds_info['web_app_credentials'].split(":")
    new_username = creds_values[0]
    new_password = creds_values[1]

    return username == new_username and password == new_password 
Example 25
Project: rc-niceties   Author: mjec   File: rc.py    MIT License 5 votes vote down vote up
def get(self, url):
        for matcher in self.url_matches:
            if matcher[0].fullmatch(url):
                return SimpleNamespace(data=json.load(
                    open(os.path.join(app.root_path, 'mock/fixtures/' + matcher[1]))
                ))
        return SimpleNamespace(data={}) 
Example 26
Project: notify-api   Author: alphagov   File: validators.py    MIT License 5 votes vote down vote up
def load_schemas(schemas_path, schema_names):
    loaded_schemas = {}
    for schema_name in schema_names:
        schema_path = os.path.join(schemas_path, '{}.json'.format(schema_name))

        with open(schema_path) as f:
            schema = json.load(f)
            validator = validator_for(schema)
            validator.check_schema(schema)
            loaded_schemas[schema_name] = schema
    return loaded_schemas 
Example 27
Project: steam-flask-openid   Author: izogain   File: providers.py    MIT License 5 votes vote down vote up
def get_steam_userinfo(steam_id):
    options = {
        'key': current_app.config['STEAM_KEY'],
        'steamids': steam_id
    }
    url = 'http://api.steampowered.com/ISteamUser/' \
          'GetPlayerSummaries/v0002/?%s' % urllib.urlencode(options)
    rv = json.load(urllib2.urlopen(url))
    return rv['response']['players'][0] or {} 
Example 28
Project: rebble-appstore-api   Author: pebble-dev   File: commands.py    MIT License 4 votes vote down vote up
def new_app(conf):
    params = yaml.load(open(conf, "r"))
    
    def path(base):
        return f"{os.path.dirname(conf)}/{base}"

    pbw_file = params['pbw_file']
    pbw = PBW(path(pbw_file), 'aplite')
    with pbw.zip.open('appinfo.json') as f:
        appinfo = json.load(f)
    
    if App.query.filter(App.app_uuid == appinfo['uuid']).count() > 0:
        raise ValueError("app already exists!")
    
    if 'developer_id' in params:
        developer = Developer.query.filter(Developer.id == params['developer_id']).one()
    else:
        developer = Developer(id = id_generator.generate(), name = appinfo['companyName'])
        db.session.add(developer)
        print(f"Created developer {developer.id}")
    
    header_asset = upload_asset(path(params['header']))
    
    app_obj = App(
        id = id_generator.generate(),
        app_uuid = appinfo['uuid'],
        asset_collections = { x['name']: AssetCollection(
            platform=x['name'],
            description=params['description'],
            screenshots=[upload_asset(path(s)) for s in x['screenshots']],
            headers = [header_asset],
            banner = None
        ) for x in params['assets']},
        category_id = category_map.get(params['category'], None),
        companions = {}, # companions not supported yet
        created_at = datetime.datetime.utcnow(),
        developer = developer,
        hearts = 0,
        releases = [],
        icon_large = upload_asset(path(params['large_icon'])),
        icon_small = upload_asset(path(params['small_icon'])),
        source = params['source'],
        title = params['title'],
        type = params['type'],
        timeline_enabled = False,
        website = params['website']
    )
    db.session.add(app_obj)
    print(f"Created app {app_obj.id}")
    
    release = release_from_pbw(app_obj, path(pbw_file),
                               release_notes = params['release_notes'],
                               published_date = datetime.datetime.utcnow(),
                               version = appinfo['versionLabel'],
                               compatibility = appinfo['targetPlatforms'])
    print(f"Created release {release.id}")
    upload_pbw(release, path(pbw_file))
    db.session.commit()
    
    if algolia_index:
        algolia_index.partial_update_objects([algolia_app(app_obj)], { 'createIfNotExists': True })