Python flask.json.jsonify() Examples

The following are code examples for showing how to use flask.json.jsonify(). 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: hangouts-chat-samples   Author: gsuitedevs   File: main.py    Apache License 2.0 6 votes vote down vote up
def home_post():
    """Respond to POST requests to this endpoint.

    All requests sent to this endpoint from Hangouts Chat are POST
    requests.
    """

    data = request.get_json()

    resp = None

    if data['type'] == 'REMOVED_FROM_SPACE':
        logging.info('Bot removed from a space')

    else:
        resp_dict = format_response(data)
        resp = json.jsonify(resp_dict)

    return resp 
Example 2
Project: hangouts-chat-samples   Author: gsuitedevs   File: main.py    Apache License 2.0 6 votes vote down vote up
def home_post():
    """Respond to POST requests to this endpoint.

    All requests sent to this endpoint from Hangouts Chat are POST
    requests.
    """

    event_data = request.get_json()

    resp = None

    # If the bot is removed from the space, it doesn't post a message
    # to the space. Instead, log a message showing that the bot was removed.
    if event_data['type'] == 'REMOVED_FROM_SPACE':
        logging.info('Bot removed from  %s', event_data['space']['name'])
        return json.jsonify({})

    resp = format_response(event_data)
    space_name = event_data['space']['name']
    send_async_response(resp, space_name)

    # Return empty jsom respomse simce message already sent via REST API
    return json.jsonify({})

# [START async-response] 
Example 3
Project: interplanetary-album-box   Author: punica-box   File: interplanetary_album.py    MIT License 6 votes vote down vote up
def unlock_identity():
    ont_id_selected = request.json.get('ont_id_selected')
    ont_id_password = request.json.get('ont_id_password')
    global default_identity_account
    try:
        default_identity_account = app.config['WALLET_MANAGER'].get_control_account_by_index(ont_id_selected, 0,
                                                                                             ont_id_password)
    except SDKException as e:
        redirect_url = request.url.replace('unlock_identity', 'login')
        return json.jsonify({'result': e.args[1], 'redirect_url': redirect_url}), 500
    if isinstance(default_identity_account, Account):
        msg = ''.join(['unlock ', ont_id_selected, ' successful!'])
        redirect_url = request.url.replace('unlock_identity', '')
        return json.jsonify({'result': msg, 'redirect_url': redirect_url}), 200
    else:
        redirect_url = request.url.replace('unlock_identity', 'login')
        return json.jsonify({'result': 'unlock failed!', 'redirect_url': redirect_url}), 501 
Example 4
Project: interplanetary-album-box   Author: punica-box   File: interplanetary_album.py    MIT License 6 votes vote down vote up
def upload_file():
    file = request.files['file']
    global default_identity_account
    global default_wallet_account
    if not isinstance(default_identity_account, Account):
        return json.jsonify({'result': 'default identity is locked'}), 500
    if not isinstance(default_wallet_account, Account):
        return json.jsonify({'result': 'default account is locked'}), 501
    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        img_path = os.path.join(app.config['ASSETS_FOLDER'], filename)
        file.save(img_path)
        tx_hash = add_assets_to_ipfs(img_path, default_identity_account, default_wallet_account)
        remove_file_if_exists(img_path)
        return json.jsonify({'result': filename, 'tx_hash': tx_hash}), 200
    else:
        return json.jsonify({'result': 'file is not allowed'}), 502 
Example 5
Project: interplanetary-album-box   Author: punica-box   File: interplanetary_album.py    MIT License 6 votes vote down vote up
def account_change():
    b58_address_selected = request.json.get('b58_address_selected')
    password = request.json.get('password')
    global default_wallet_account
    old_wallet_account = default_wallet_account
    try:
        default_wallet_account = app.config['WALLET_MANAGER'].get_account_by_b58_address(b58_address_selected, password)
    except SDKException:
        default_wallet_account = old_wallet_account
        return json.jsonify({'result': 'invalid password'}), 400
    try:
        app.config['WALLET_MANAGER'].get_wallet().set_default_account_by_address(b58_address_selected)
    except SDKException:
        return json.jsonify({'result': 'invalid base58 address'})
    app.config['WALLET_MANAGER'].save()
    return json.jsonify({'result': 'Change successful'}), 200 
Example 6
Project: cds-service-example-python   Author: cds-hooks   File: app.py    MIT License 6 votes vote down vote up
def service():
  card1 = card('Success Card', 'success', link('Static CDS Service', 'http://example.com'))
  card1['detail'] = 'This is a test of a static success card.'
  card1['links'].append(link('Google', 'https://google.com'))
  card1['links'].append(link('Github', 'https://github.com'))

  source = link('Static CDS Service')

  card2 = card('Info card', 'info', source)
  card3 = card('Warning card', 'warning', source)
  card4 = card('Hard stop card', 'hard-stop', source)


  return json.jsonify({
    'cards': [card1, card2, card3, card4]
  }) 
Example 7
Project: RSVPBot   Author: recursecenter   File: __init__.py    MIT License 6 votes vote down vote up
def join(id):
    event = find_event(id)
    if event == None:
        return not_found()

    user = find_user(request.values.get('user_param'), request.values.get('user_param_value'))
    if user == None:
        return user_not_specified()

    join_event(user, event)

    return jsonify({
        'joined': True,
        'rsvps_disabled': False,
        'event_archived': False,
        'over_capacity': False,
        'past_deadline': False,
    }) 
Example 8
Project: sourceapi   Author: kradalby   File: app.py    MIT License 6 votes vote down vote up
def stats():
    total = Query.query.count()
    success = Query.query.filter_by(request_status='success').count()
    errors = Query.query.filter_by(request_status='error').count()
    user_agents_aggregated = db.session.query(Query.user_agent,
                                              label('amount', func.count(Query.user_agent))
                                             ).group_by(Query.user_agent).all()
    request_origin_aggregated = db.session.query(Query.request_origin,
                                              label('amount', func.count(Query.request_origin))
                                             ).group_by(Query.request_origin).all()
    response = {
        'total': total,
        'success': success,
        'errors': errors,
        'user_agents': user_agents_aggregated,
        'request_origin': request_origin_aggregated
    }
    return json.jsonify(response) 
Example 9
Project: iLID   Author: twerkmeister   File: server.py    MIT License 6 votes vote down vote up
def uploadAudio():

    def is_allowed(filename):
        return len(filter(lambda ext: ext in filename, ["wav", "mp3", "ogg"])) > 0

    file = request.files.getlist("audio")[0]

    if file and is_allowed(file.filename):
        filename = secure_filename(file.filename)
        file_path = path.join(app.config["UPLOAD_FOLDER"], filename)
        file.save(file_path)

        # convert_to_mono_wav(file_path, True)

        response = jsonify(get_prediction(file_path))
    else:
        response = bad_request("Invalid file")

    return response 
Example 10
Project: py12306   Author: amikey   File: stat.py    Apache License 2.0 6 votes vote down vote up
def dashboard():
    """
    状态统计
    任务数量,用户数量,查询次数
    节点信息(TODO)
    :return:
    """
    from py12306.log.query_log import QueryLog
    query_job_count = len(Query().jobs)
    user_job_count = len(User().users)
    query_count = QueryLog().data.get('query_count')
    res = {
        'query_job_count': query_job_count,
        'user_job_count': user_job_count,
        'query_count': query_count,
    }
    if Config().CDN_ENABLED:
        from py12306.helpers.cdn import Cdn
        res['cdn_count'] = len(Cdn().available_items)
    return jsonify(res) 
Example 11
Project: py12306   Author: amikey   File: stat.py    Apache License 2.0 6 votes vote down vote up
def clusters():
    """
    节点统计
    节点数量,主节点,子节点列表
    :return:
    """
    from py12306.cluster.cluster import Cluster
    nodes = Cluster().nodes
    count = len(nodes)
    node_lists = list(nodes)
    master = [key for key, val in nodes.items() if int(val) == Cluster.KEY_MASTER]
    master = master[0] if master else ''

    return jsonify({
        'master': master,
        'count': count,
        'node_lists': ', '.join(node_lists)
    }) 
Example 12
Project: urban-insights-backend   Author: mitevpi   File: app.py    MIT License 6 votes vote down vote up
def testRequest():
    try:
        data = json.loads(request.data)
    except:
        data = "empty"

    try:
        args = json.loads(request.args)
    except:
        args = "empty"

    try:
        values = json.loads(request.values)
    except:
        values = "empty"

    try:
        reqJson = request.json
    except:
        reqJson = "empty"

    return jsonify({'data':data, 'args': args, 'values': values, 'reqJson': reqJson}) 
Example 13
Project: oidc-fed   Author: its-dirg   File: rp.py    Apache License 2.0 6 votes vote down vote up
def handle_authn_response():
    # parse authn response
    authn_response = current_app.rp.client.parse_response(AuthorizationResponse,
                                              info=request.query_string.decode("utf-8"),
                                              sformat="urlencoded")

    auth_code = None
    if "code" in authn_response:
        auth_code = authn_response["code"]
        # make token request
        args = {
            "code": auth_code,
            "client_id": current_app.rp.client.client_id,
            "client_secret": current_app.rp.client.client_secret
        }

        token_response = current_app.rp.client.do_access_token_request(scope="openid", request_args=args)
        access_token = token_response["access_token"]
        id_token = token_response["id_token"].to_dict()
        # TODO do userinfo req
    else:
        id_token = authn_response["id_token"].to_dict()
        access_token = authn_response.get("access_token")

    return jsonify(dict(auth_code=auth_code, token=access_token, id_token=id_token)) 
Example 14
Project: eve-inc-waitlist   Author: SpeedProg   File: fittings.py    MIT License 6 votes vote down vote up
def waitlist():
    group_id_str = request.args.get('group')
    try:
        group_id = int(group_id_str)
    except ValueError:
        flask.abort(400, "You are missing a Waitlist Group.")
        return None
    jsonwls = []
    group = db.session.query(WaitlistGroup).get(group_id)
    waitlists = [group.xuplist, group.logilist, group.dpslist, group.sniperlist]
    if group.otherlist is not None:
        waitlists.append(group.otherlist)
    
    # is the requester allowed to see fits?
    exclude_fits = not perm_fits_view.can()
    include_fits_from = [current_user.get_eve_id()]
    for wl in waitlists:
        jsonwls.append(make_json_wl(wl, exclude_fits, include_fits_from,
                                    scramble_names=(config.scramble_names and exclude_fits),
                                    include_names_from=include_fits_from))
    return jsonify(waitlists=jsonwls, groupName=group.groupName, groupID=group.groupID, displayName=group.displayName) 
Example 15
Project: eve-inc-waitlist   Author: SpeedProg   File: fittings.py    MIT License 6 votes vote down vote up
def history_since():
    laststamp = int(request.args.get('last'))
    logger.info("last=%s", str(laststamp))
    since = datetime.utcfromtimestamp(laststamp / 1000.0)
    logger.info("Looking for %s", str(since))
    tnow = datetime.utcnow()

    if not perm_comp_unlimited.can():
        if perm_manager.get_permission('comphistory_view_240').can():
            max_time = timedelta(minutes=240)
            if tnow - since > max_time:
                since = tnow - max_time
        else:
            max_time = timedelta(minutes=30)
            if tnow - since > max_time:
                since = tnow - max_time

    new_history_entries = db.session.query(HistoryEntry).filter(HistoryEntry.time > since).all()

    # do access tracking here
    if get_access_duration(current_user.id, timedelta(hours=6), datetime.utcnow()) > timedelta(days=4):
        logger.error(f"User {current_user.username}"
                     f" is requesting fits since over 4days, without a break of at least 6h")

    return jsonify(make_history_json(new_history_entries)) 
Example 16
Project: dci-control-server   Author: redhat-cip   File: jobs_events.py    Apache License 2.0 6 votes vote down vote up
def get_current_sequence(user):
    if user.is_not_super_admin():
        raise dci_exc.Unauthorized()

    def create_sequence():
        etag = utils.gen_etag()
        q_add_counter = models.COUNTER.insert().values(name='jobs_events',
                                                       sequence=0,
                                                       etag=etag)
        flask.g.db_conn.execute(q_add_counter)

    def get_sequence():
        query = sql.select([models.COUNTER]).\
            where(models.COUNTER.c.name == 'jobs_events')
        return flask.g.db_conn.execute(query).fetchone()

    je_sequence = get_sequence()
    if not je_sequence:
        create_sequence()
        je_sequence = get_sequence()

    return json.jsonify({'sequence': {'sequence': je_sequence.sequence,
                                      'etag': je_sequence.etag}}) 
Example 17
Project: dci-control-server   Author: redhat-cip   File: files.py    Apache License 2.0 6 votes vote down vote up
def get_all_files(user, job_id):
    """Get all files.
    """
    args = check_and_get_args(flask.request.args.to_dict())
    job = v1_utils.verify_existence_and_get(job_id, models.JOBS)
    if (user.is_not_super_admin() and user.is_not_read_only_user()
        and user.is_not_epm()):
        if job['team_id'] not in user.teams_ids:
            raise dci_exc.Unauthorized()

    query = v1_utils.QueryBuilder(_TABLE, args, _FILES_COLUMNS)

    query.add_extra_condition(_TABLE.c.job_id == job_id)
    query.add_extra_condition(_TABLE.c.state != 'archived')

    nb_rows = query.get_number_of_rows()
    rows = query.execute(fetchall=True)
    rows = v1_utils.format_result(rows, _TABLE.name, args['embed'],
                                  _EMBED_MANY)
    return json.jsonify({'files': rows, '_meta': {'count': nb_rows}}) 
Example 18
Project: hassutnimet_net   Author: aajanki   File: namegenserver.py    MIT License 5 votes vote down vote up
def generate():
    return jsonify(name=generator.generate()) 
Example 19
Project: hassutnimet_net   Author: aajanki   File: namegenserver.py    MIT License 5 votes vote down vote up
def generate_male():
    return jsonify(name=generator.generate_male()) 
Example 20
Project: hassutnimet_net   Author: aajanki   File: namegenserver.py    MIT License 5 votes vote down vote up
def generate_female():
    return jsonify(name=generator.generate_female()) 
Example 21
Project: SGVHAK_Rover   Author: Roger-random   File: menu.py    MIT License 5 votes vote down vote up
def drive_command():
    """
    Allows user to send a single angle+velocity command to chassis.
    """
    chassis.ensureready()

    if request.method == 'GET':
      return render_template("drive_command.html",
        page_title = 'Velocity & Angle Commands')
    else:
      # TODO: Limit the frequency of updates to one every 50ms. If more
      # than one update arrive within the window, use the final one. This
      # reduces workload on RoboClaw serial network and the mechanical bits
      # can't respond super fast anyway.
      # EXCEPTION: If a stop command arrives, stop immediately.
      pct_angle = float(request.form['pct_angle'])
      magnitude = float(request.form['magnitude'])

      if pct_angle == 0:
        radius = float("inf")
      elif pct_angle>0:
        radius = chassis.minRadius + (chassis.maxRadius-chassis.minRadius) * (100-pct_angle)/100.0
      else:
        radius = -chassis.minRadius - (chassis.maxRadius-chassis.minRadius) * (100+pct_angle)/100.0

      chassis.move_velocity_radius(magnitude, radius)

      return json.jsonify({'Success':1}) 
Example 22
Project: SGVHAK_Rover   Author: Roger-random   File: menu.py    MIT License 5 votes vote down vote up
def request_wheel_status():
    """
    Return a JSON representation of current chassis wheel status. Use POST
    instead of GET to clearify this data should not be cached.
    Polled regularly by chassis_config.js to update onscreen display of
    chassis_config.html.
    """
    chassis.ensureready()
    wheelInfo = dict()
    for name, wheel in chassis.wheels.iteritems():
      wheelInfo[name] = dict()
      wheelInfo[name]['velocity'] = wheel.velocity
      wheelInfo[name]['angle'] = wheel.angle
    return json.jsonify(wheelInfo) 
Example 23
Project: SGVHAK_Rover   Author: Roger-random   File: menu.py    MIT License 5 votes vote down vote up
def steering_trim():
    """
    Steering control motor can go off-center for various reasons. The steering
    trim function allows the user to adjust the wheel center position.
    """
    chassis.ensureready()

    if request.method == 'GET':
      # Find all the wheels that we can steer
      steered_wheels = list()
      for name, wheel in chassis.wheels.iteritems():
        if wheel.steeringcontrol:
          steered_wheels.append(name)
      steered_wheels.sort()

      # Pass the list of wheels along for display
      return render_template("steering_trim.html",
        steered_wheels=steered_wheels,
        page_title = 'Steering Trim')
    else:
      adjWheel = chassis.wheels[request.form['wheel']]

      if "move_to" in request.form:
        # Steer wheel to requested angle
        adjWheel.steerto(int(request.form['move_to']))

        return json.jsonify({'wheel':adjWheel.name, 'move_to':request.form['move_to']})
      elif "set_zero" in request.form:
        # Accept the current steering angle as new zero
        adjWheel.steersetzero()

        return json.jsonify({'wheel':adjWheel.name, 'set_zero':request.form['set_zero']})
      else:
        raise ValueError("Invalid POST parameters.") 
Example 24
Project: hangouts-chat-samples   Author: gsuitedevs   File: main.py    Apache License 2.0 5 votes vote down vote up
def post():
    """Handle requests from Hangouts Chat

    Create new vote for ADDED_TO_SPACE and MESSAGE events
    Update existing card for 'upvote' or 'downvote' clicks
    Create new vote for 'newvote' clicks
    """
    event = request.get_json()
    user = event['user']['displayName']
    # Update vote when card button pressed
    if event['type'] == 'CARD_CLICKED':
        method = event['action']['actionMethodName']
        # Create new vote when "NEW" button clicked
        if method == 'newvote':
            body = create_message(user)
        else:
            # Update card in-place when "+1" or "-1" button clicked
            delta = 1 if method == 'upvote' else -1
            vote_count = int(event['action']['parameters'][0]['value']) + delta
            body = create_message(user, vote_count, True)
    # Create new vote for any msg
    elif event['type'] == 'MESSAGE':
        body = create_message(user)
    else: # no response for ADDED_TO_SPACE or REMOVED_FROM_SPACE
        return json.jsonify({})

    return json.jsonify(body) 
Example 25
Project: hangouts-chat-samples   Author: gsuitedevs   File: main.py    Apache License 2.0 5 votes vote down vote up
def home_post():
    """Respond to POST requests to this endpoint.

    All requests sent to this endpoint from Hangouts Chat are POST
    requests.
    """

    event_data = request.get_json()

    resp = None

    # If the bot is removed from the space, it doesn't post a message
    # to the space. Instead, log a message showing that the bot was removed.
    if event_data['type'] == 'REMOVED_FROM_SPACE':
        logging.info('Bot removed from  %s', event_data['space']['name'])
        return 'OK'

    if event_data['type'] == 'ADDED_TO_SPACE' and event_data['space']['type'] == 'ROOM':
        resp = {'text': ('Thanks for adding me to {}!'
                         .format(event_data['space']['name']))}

    elif event_data['type'] == 'ADDED_TO_SPACE' and event_data['space']['type'] == 'DM':
        resp = {'text': ('Thanks for adding me to a DM, {}!'
                         .format(event_data['user']['displayName']))}

    elif event_data['type'] == 'MESSAGE':
        resp = create_card_response(event_data['message']['text'])

    elif event_data['type'] == 'CARD_CLICKED':
        action_name = event_data['action']['actionMethodName']
        parameters = event_data['action']['parameters']
        resp = respond_to_interactive_card_click(action_name, parameters)

    logging.info(resp)
    return json.jsonify(resp) 
Example 26
Project: portingdb   Author: fedora-python   File: htmlreport.py    MIT License 5 votes vote down vote up
def jsonstats():
    data = current_app.config['data']

    packages = data['packages']
    grouped = group_by_status(packages.values())

    stats = {
        status: len(packages)
        for status, packages in grouped.items()
    }

    return jsonify(stats) 
Example 27
Project: interplanetary-album-box   Author: punica-box   File: interplanetary_album.py    MIT License 5 votes vote down vote up
def get_default_wallet_account_data():
    if isinstance(app.config['WALLET_MANAGER'], WalletManager):
        try:
            default_wallet_account_data = app.config['WALLET_MANAGER'].get_default_account_data()
            label = default_wallet_account_data.label
            b58_address = default_wallet_account_data.b58_address
            return json.jsonify({'label': label, 'b58_address': b58_address}), 200
        except SDKException as e:
            return json.jsonify({'result': e.args[1]}), 500
    return json.jsonify({'result': 'WalletManager error'}), 501 
Example 28
Project: interplanetary-album-box   Author: punica-box   File: interplanetary_album.py    MIT License 5 votes vote down vote up
def get_default_identity_data():
    wallet_manager = app.config['WALLET_MANAGER']
    if isinstance(wallet_manager, WalletManager):
        try:
            default_identity = wallet_manager.get_default_identity()
            return json.jsonify({'label': default_identity.label, 'ont_id': default_identity.ont_id}), 200
        except SDKException as e:
            return json.jsonify({'result': e.args[1]}), 500
    else:
        return json.jsonify({'result': 'Wallet manager error'}), 501 
Example 29
Project: interplanetary-album-box   Author: punica-box   File: interplanetary_album.py    MIT License 5 votes vote down vote up
def get_album_array():
    global default_identity_account
    if not isinstance(default_identity_account, Account):
        return json.jsonify({'result': 'default identity is locked'}), 500
    item_list = get_item_list_from_contract(default_identity_account)
    get_album_from_ipfs(item_list)
    album_img = os.listdir(app.config['ALBUM_FOLDER'])
    img_position = list()
    for img in album_img:
        img_position.append(''.join(['/static/album/', img]))
    return json.jsonify({'result': img_position}), 200 
Example 30
Project: interplanetary-album-box   Author: punica-box   File: interplanetary_album.py    MIT License 5 votes vote down vote up
def get_contract_address():
    contract_address = app.config['CONTRACT_ADDRESS_HEX']
    return json.jsonify({'result': contract_address}), 200 
Example 31
Project: interplanetary-album-box   Author: punica-box   File: interplanetary_album.py    MIT License 5 votes vote down vote up
def get_accounts():
    account_list = app.config['WALLET_MANAGER'].get_wallet().get_accounts()
    address_list = list()
    for acct in account_list:
        acct_item = {'b58_address': acct.b58_address, 'label': acct.label}
        address_list.append(acct_item)
    return json.jsonify({'result': address_list}), 200 
Example 32
Project: interplanetary-album-box   Author: punica-box   File: interplanetary_album.py    MIT License 5 votes vote down vote up
def is_default_wallet_account_unlock():
    global default_wallet_account
    if isinstance(default_wallet_account, Account):
        return json.jsonify({'result': True}), 200
    else:
        return json.jsonify({'result': False}), 200 
Example 33
Project: interplanetary-album-box   Author: punica-box   File: interplanetary_album.py    MIT License 5 votes vote down vote up
def create_account():
    password = request.json.get('password')
    label = request.json.get('label')
    hex_private_key = utils.get_random_hex_str(64)
    app.config['WALLET_MANAGER'].create_account_from_private_key(password, hex_private_key, label)
    app.config['WALLET_MANAGER'].save()
    return json.jsonify({'hex_private_key': hex_private_key}) 
Example 34
Project: interplanetary-album-box   Author: punica-box   File: interplanetary_album.py    MIT License 5 votes vote down vote up
def import_account():
    label = request.json.get('label')
    password = request.json.get('password')
    hex_private_key = request.json.get('hex_private_key')
    try:
        account = app.config['WALLET_MANAGER'].create_account_from_private_key(password, hex_private_key, label)
    except ValueError as e:
        return json.jsonify({'msg': 'account exists.'}), 500
    app.config['WALLET_MANAGER'].save()
    return json.jsonify({'result': account.b58_address}), 200 
Example 35
Project: interplanetary-album-box   Author: punica-box   File: interplanetary_album.py    MIT License 5 votes vote down vote up
def get_identities():
    identities = app.config['WALLET_MANAGER'].get_wallet().get_identities()
    ont_id_list = list()
    for item in identities:
        ont_id_item = {'ont_id': item.ont_id, 'label': item.label}
        ont_id_list.append(ont_id_item)
    return json.jsonify({'result': ont_id_list}), 200 
Example 36
Project: interplanetary-album-box   Author: punica-box   File: interplanetary_album.py    MIT License 5 votes vote down vote up
def create_identity():
    label = request.json.get('label')
    password = request.json.get('password')
    hex_private_key = utils.get_random_hex_str(64)
    try:
        new_identity = app.config['WALLET_MANAGER'].create_identity_from_private_key(label, password,
                                                                                     hex_private_key)
    except SDKException as e:
        return json.jsonify({'result': e}), 500
    app.config['WALLET_MANAGER'].save()
    return json.jsonify({'hex_private_key': hex_private_key, 'ont_id': new_identity.ont_id}), 200 
Example 37
Project: interplanetary-album-box   Author: punica-box   File: interplanetary_album.py    MIT License 5 votes vote down vote up
def import_identity():
    label = request.json.get('label')
    password = request.json.get('password')
    hex_private_key = request.json.get('hex_private_key')
    try:
        new_identity = app.config['WALLET_MANAGER'].create_identity_from_private_key(label, password,
                                                                                     hex_private_key)
    except SDKException as e:
        return json.jsonify({'result': e}), 500
    app.config['WALLET_MANAGER'].save()
    return json.jsonify({'hex_private_key': hex_private_key, 'ont_id': new_identity.ont_id}), 200 
Example 38
Project: interplanetary-album-box   Author: punica-box   File: interplanetary_album.py    MIT License 5 votes vote down vote up
def remove_identity():
    ont_id_remove = request.json.get('ont_id_remove')
    password = request.json.get('password')
    try:
        acct = app.config['WALLET_MANAGER'].get_account(ont_id_remove, password)
        if acct is None:
            return json.jsonify({'result': ''.join(['remove ', ont_id_remove, ' failed!'])}), 500
        app.config['WALLET_MANAGER'].get_wallet().remove_identity(ont_id_remove)
    except SDKException or RuntimeError:
        return json.jsonify({'result': ''.join(['remove ', ont_id_remove, ' failed!'])}), 500
    app.config['WALLET_MANAGER'].save()
    return json.jsonify({'result': ''.join(['remove ', ont_id_remove, ' successful!'])}), 200 
Example 39
Project: interplanetary-album-box   Author: punica-box   File: interplanetary_album.py    MIT License 5 votes vote down vote up
def change_net():
    network_selected = request.json.get('network_selected')
    if network_selected == 'MainNet':
        remote_rpc_address = 'http://dappnode1.ont.io:20336'
        app.config['ONTOLOGY'].set_rpc(remote_rpc_address)
        sdk_rpc_address = app.config['ONTOLOGY'].get_rpc().addr
        if sdk_rpc_address != remote_rpc_address:
            result = ''.join(['remote rpc address set failed. the rpc address now used is ', sdk_rpc_address])
            return json.jsonify({'result': result}), 409
    elif network_selected == 'TestNet':
        remote_rpc_address = 'http://polaris3.ont.io:20336'
        app.config['ONTOLOGY'].set_rpc(remote_rpc_address)
        sdk_rpc_address = app.config['ONTOLOGY'].get_rpc().addr
        if sdk_rpc_address != remote_rpc_address:
            result = ''.join(['remote rpc address set failed. the rpc address now used is ', sdk_rpc_address])
            return json.jsonify({'result': result}), 409
    elif network_selected == 'Localhost':
        remote_rpc_address = 'http://localhost:20336'
        app.config['ONTOLOGY'].set_rpc(remote_rpc_address)
        old_remote_rpc_address = app.config['ONTOLOGY'].get_rpc()
        sdk_rpc_address = app.config['ONTOLOGY'].get_rpc().addr
        if sdk_rpc_address != remote_rpc_address:
            result = ''.join(['remote rpc address set failed. the rpc address now used is ', sdk_rpc_address])
            return json.jsonify({'result': result}), 409
        try:
            app.config['ONTOLOGY'].rpc.get_version()
        except SDKException as e:
            app.config['ONTOLOGY'].set_rpc(old_remote_rpc_address)
            error_msg = 'Other Error, ConnectionError'
            if error_msg in e.args[1]:
                return json.jsonify({'result': 'Connection to localhost node failed.'}), 400
            else:
                return json.jsonify({'result': e.args[1]}), 500
    else:
        return json.jsonify({'result': 'unsupported network.'}), 501
    return json.jsonify({'result': 'succeed'}), 200 
Example 40
Project: arxiv-zero   Author: arXiv   File: external_api.py    MIT License 5 votes vote down vote up
def ok() -> Response:
    """Health check endpoint."""
    response: Response = jsonify({'status': 'nobody but us hamsters'})
    return response 
Example 41
Project: arxiv-zero   Author: arXiv   File: external_api.py    MIT License 5 votes vote down vote up
def read_baz(baz_id: int) -> Response:
    """Provide some data about the baz."""
    data, status_code, headers = controllers.get_baz(baz_id)
    response: Response = jsonify(data)
    response.headers.extend(headers)
    response.status_code = status_code
    return response 
Example 42
Project: arxiv-zero   Author: arXiv   File: external_api.py    MIT License 5 votes vote down vote up
def read_thing(thing_id: int) -> Response:
    """Provide some data about the thing."""
    data, status_code, headers = controllers.get_thing(thing_id)
    if isinstance(data, io.BytesIO):
        mimetype = headers.get('Content-type', 'text/plain')
        response: Response = send_file(data, mimetype=mimetype)
    else:
        response = jsonify(data)
    response.headers.extend(headers)
    response.status_code = status_code
    return response 
Example 43
Project: arxiv-zero   Author: arXiv   File: external_api.py    MIT License 5 votes vote down vote up
def create_thing() -> Response:
    """Create a new thing."""
    payload = request.get_json(force=True)    # Ignore Content-Type header.
    data, status_code, headers = controllers.create_a_thing(payload)
    response: Response = jsonify(data)
    response.headers.extend(headers)
    response.status_code = status_code
    return response 
Example 44
Project: arxiv-zero   Author: arXiv   File: external_api.py    MIT License 5 votes vote down vote up
def mutate_thing(thing_id: int) -> Response:
    """Request that the thing be mutated."""
    data, status_code, headers = controllers.start_mutating_a_thing(thing_id)
    response: Response = jsonify(data)
    response.headers.extend(headers)
    response.status_code = status_code
    return response 
Example 45
Project: arxiv-zero   Author: arXiv   File: external_api.py    MIT License 5 votes vote down vote up
def handle_exception(error: HTTPException) -> Response:
    """
    JSON-ify the error response.

    This works just like the handlers in zero.routes.ui, but instead of
    rendering a template we are JSON-ifying the response. Note that we are
    registering the same error handler for several different exceptions, since
    we aren't doing anything that is specific to a particular exception.
    """
    content = jsonify({'reason': error.description})

    # Each Werkzeug HTTP exception has a class attribute called ``code``; we
    # can use that to set the status code on the response.
    response: Response = make_response(content, error.code)
    return response 
Example 46
Project: lumberjack   Author: robertwatkins   File: server.py    GNU General Public License v3.0 5 votes vote down vote up
def get(self, agent_id):
        conn = db_connect.connect()
        query = conn.execute("select * from main.agents where agent_id =%d;" % int(agent_id))
        result = {'agent': [dict(zip(tuple(query.keys()), i)) for i in query.cursor]}
        return jsonify(result) 
Example 47
Project: lumberjack   Author: robertwatkins   File: server.py    GNU General Public License v3.0 5 votes vote down vote up
def get(self):
        conn = db_connect.connect()
        query = conn.execute("select * from main.notification_channels;")
        # result = {'notification_channels': [dict(zip(tuple(query.keys()), i)) for i in query.cursor]}
        # return jsonify(result)

        return {'notification_channels': [i[0] for i in query.cursor.fetchall()]} 
Example 48
Project: lumberjack   Author: robertwatkins   File: server.py    GNU General Public License v3.0 5 votes vote down vote up
def post(self):
        # This does not currently allow sending only some fields. All fields must be specified.
        try:
            channel_id = max(self.get().get('notification_channels')) + 1
        except:
            channel_id = 1

        if not request.json:
            abort(400)
        if 'channel_name' in request.json and type(request.json['channel_name']) != unicode:
            abort(400)
        if 'channel_type' in request.json and type(request.json['channel_type']) is not unicode:
            abort(400)
        if 'configuration' in request.json and type(request.json['configuration']) is not unicode:
            abort(400)

        new_channel_name = request.json.get('notification_channels')[0].get('channel_name')
        new_channel_type = request.json.get('notification_channels')[0].get('channel_type')
        new_configuration = request.json.get('notification_channels')[0].get('configuration')
        try:
            insert_query = ("insert into main.notification_channels  (channel_name, channel_type, configuration, channel_id ) "
            "values ('" + new_channel_name + "', '" + new_channel_type + "', '" + new_configuration + "', '" + str(channel_id) + "');")

            print(insert_query)
            conn = db_connect.connect()
            query = conn.execute(insert_query)
            result_json = jsonify({'result': 'success'})
        except TypeError:
            result_json = jsonify({'result': 'failure'})

        return result_json 
Example 49
Project: voting   Author: ephremdeme   File: auth.py    MIT License 5 votes vote down vote up
def gui_login():
    data = request.get_json()
    email = data['email']
    password = data['password']
    print(email, password)
    user = User.query.filter_by(email=email).first()
    vote_array = []

    if user:
        for vote in user.votes:
            vote_array.append((vote.vote_name, vote.hash))

    return jsonify({'list': vote_array}) 
Example 50
Project: cds-service-example-python   Author: cds-hooks   File: app.py    MIT License 5 votes vote down vote up
def discovery():
  return json.jsonify({
    'services': [
      {
        'hook': 'patient-view',
        'name': 'Static CDS Service in Python',
        'description': 'An example static CDS service in Python',
        'id': 'static',
        'prefetch': {
          'patient': 'Patient/{{Patient.id}}'
        }
      }
    ]
  }) 
Example 51
Project: RSVPBot   Author: recursecenter   File: __init__.py    MIT License 5 votes vote down vote up
def render_event(event):
    return jsonify(filter_participants(event)) 
Example 52
Project: RSVPBot   Author: recursecenter   File: __init__.py    MIT License 5 votes vote down vote up
def render_events(events):
    return jsonify([filter_participants(event) for event in events]) 
Example 53
Project: RSVPBot   Author: recursecenter   File: __init__.py    MIT License 5 votes vote down vote up
def not_found():
    response = jsonify({"message":"not_found"})
    response.status_code = 404
    return response 
Example 54
Project: RSVPBot   Author: recursecenter   File: __init__.py    MIT License 5 votes vote down vote up
def user_not_specified():
    response = jsonify({"message": "user_not_specified"})
    response.status_code = 422
    return response 
Example 55
Project: FoosballStatsServer   Author: shockema   File: statsServer.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _getPlayers(commandArgs, db, user):
    if (len(commandArgs) != 1):
        return "players comand requires no arguments.  Use \"/foosball help\"."
    players = []
    cursor = db.cursor()
    try:
        cursor.execute("SELECT name FROM Player")
        for row in cursor.fetchall():
            players.append(str(row[0]))
    except Exception as e:
        app.logger.error("Caught exception trying to retrieve all user names:  " + str(e))
        return "Error!"
    return jsonify({ "players" : players }) 
Example 56
Project: FoosballStatsServer   Author: shockema   File: statsServer.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _recent(commandArgs, db, user, client = "slack"):
    if (len(commandArgs) != 1):
        return "recent comand takes no arguments.  Use \"/foosball help\"."
    cursor = db.cursor()
    try:
        rows = []
        cursor.execute("SELECT * FROM Game as G WHERE timestamp > DATE_SUB(CURDATE(), INTERVAL 1 DAY) ORDER BY timestamp DESC")
        maxSideLen = 7
        maxAddedByLen = 7
        for row in cursor.fetchall():
            rows.append({ "gameid" : row[0], "timestamp" : row[1], "addedBy" : row[2], \
                          "side1" :  { "color" : "red", "defense" : _playerIdToName(db, row[5]), "offense" : _playerIdToName(db, row[6]), "score" : row[3] }, \
                          "side2" :  { "color" : "black", "defense" : _playerIdToName(db, row[7]), "offense" : _playerIdToName(db, row[8]), "score" : row[4] } })
            if (len(row[2]) > maxAddedByLen):
                maxAddedByLen = len(row[2])
            if (len(rows[-1]['side1']) > maxSideLen):
                maxSideLen = len(rows[-1]['side1'])
            if (len(rows[-1]['side2']) > maxSideLen):
                maxSideLen = len(rows[-1]['side2'])
        if (client == "slack"):
            addedBySpace = str(maxAddedByLen + 4)
            sideSpace = str(maxSideLen + 4) 
            formatStr = "%-6s\t%-32s\t%-" + sideSpace + "s\t%-" + sideSpace + "s\t%-" + addedBySpace + "s\n"
            result = formatStr % ("Game", "When", "Side 1", "Side 2", "Added By")
            formatStr = "%-6s\t\t%-16s\t%-" + sideSpace + "s\t%-" + sideSpace + "s\t%-" + addedBySpace + "s\n"
            for game in rows:
                result += formatStr % (str(game["gameid"]) + ':', str(game["timestamp"])[:-3], 
                                       GameSide("", game['side1']['color'], game['side1']['defense'], game['side1']['offense'], game['side1']['score']).toString(), \
                                       GameSide("", game['side2']['color'], game['side2']['defense'], game['side2']['offense'], game['side2']['score']).toString(), \
                                       game["addedBy"])
            return result
        else: 
            return jsonify({ "games" : rows })
    except Exception as e:
        app.logger.error("Caught exception trying to retrieve recent games:  " + str(e))
    return "Error!" 
Example 57
Project: Voyage   Author: hieusydo   File: lm_controllers.py    MIT License 5 votes vote down vote up
def getAll():
    if 'user_id' not in session:
        return redirect(url_for('auth.signin'))

    uid = session['user_id']
    landmarks = Landmark.query.filter_by(usrID=uid).all()
    print(landmarks)

    user = User.query.filter_by(id=session['user_id']).all()[0]

    if (user.theme == ''):
        theme = eval(ColorTheme().themeString)
    else:
        theme = eval(user.theme)
    
    # Extract and reformat each landmark info
    allLms = []
    for l in landmarks:
        #allLms.append((l.lmPlaceID, l.lmName, l.lmLat, l.lmLng, l.photoFileURL, l.lmRating, l.lmComments))
        allLms.append({"place_id": l.lmPlaceID, "name": l.lmName,
                       "date_created": l.date_created,
                       "lat": l.lmLat, "lng": l.lmLng,
                       "photo_url": l.photoFileURL, "rating": l.lmRating,
                       "comment": l.lmComments})

    return jsonify({'landmarks': allLms, 'theme': theme}) 
Example 58
Project: proxy_list   Author: sunlu123456   File: __init__.py    MIT License 5 votes vote down vote up
def proxy():
    anonymity = request.args.get('anonymity', None)
    protocol = request.args.get('protocol', None)
    count = request.args.get('count', 1, int)
    query = {}
    if anonymity:
        query['anonymity'] = anonymity
    if protocol:
        query['protocol'] = protocol
    return json.jsonify(db.list(count, query=query))
    # columns = 'protocol','ip','port'
    # return json.jsonify(db.list(count, query, columns)) 
Example 59
Project: Python-Programming-Blueprints   Author: PacktPublishing   File: web_server.py    MIT License 5 votes vote down vote up
def get(self):
        with ClusterRpcProxy(config) as rpc:
            messages = rpc.message_service.get_all_messages()

        return jsonify(messages) 
Example 60
Project: iLID   Author: twerkmeister   File: server.py    MIT License 5 votes vote down vote up
def use_example(example_id):
    if example_id <= 3:
        filename = "audio%s.wav" % example_id
        file_path = path.join(app.config["UPLOAD_FOLDER"], "examples", filename)
        response = jsonify(get_prediction(file_path))
    else:
        response = bad_request("Invalid Example")

    return response 
Example 61
Project: iLID   Author: twerkmeister   File: server.py    MIT License 5 votes vote down vote up
def bad_request(reason):
    response = jsonify({"error" : reason})
    response.status_code = 400
    return response


# -------- Prediction & Features -------- 
Example 62
Project: py12306   Author: amikey   File: app.py    Apache License 2.0 5 votes vote down vote up
def menus():
    """
    菜单列表
    """
    menus = [
        {"id": 10, "name": "首页", "url": "/", "icon": "fa fa-tachometer-alt"},
        {"id": 20, "name": "用户管理", "url": "/user", "icon": "fa fa-user"},
        {"id": 30, "name": "查询任务", "url": "/query", "icon": "fa fa-infinity"},
        {"id": 40, "name": "实时日志", "url": "/log/realtime", "icon": "fa fa-signature"},
        {"id": 50, "name": "帮助", "url": "/help", "icon": "fa fa-search"}
    ]
    return jsonify(menus) 
Example 63
Project: py12306   Author: amikey   File: app.py    Apache License 2.0 5 votes vote down vote up
def actions():
    """
    操作列表
    """
    actions = [
        {"text": "退出登录", "key": 'logout', "link": "", "icon": "fa fa-sign-out-alt"}
    ]
    return jsonify(actions) 
Example 64
Project: py12306   Author: amikey   File: user.py    Apache License 2.0 5 votes vote down vote up
def login():
    """
    用户登录
    :return:
    """
    username = request.json.get('username', None)
    password = request.json.get('password', None)
    if username and password and username == Config().WEB_USER.get('username') and password == Config().WEB_USER.get(
            'password'):
        access_token = create_access_token(identity=username)
        return jsonify(access_token=access_token)
    return jsonify({"msg": "用户名或密码错误"}), 422 
Example 65
Project: py12306   Author: amikey   File: user.py    Apache License 2.0 5 votes vote down vote up
def users():
    """
    用户任务列表
    :return:
    """
    jobs = User().users
    result = list(map(convert_job_to_info, jobs))
    return jsonify(result) 
Example 66
Project: py12306   Author: amikey   File: user.py    Apache License 2.0 5 votes vote down vote up
def user_info():
    """
    获取用户信息
    :return:
    """
    result = {
        'name': Config().WEB_USER.get('username')
    }
    return jsonify(result) 
Example 67
Project: py12306   Author: amikey   File: query.py    Apache License 2.0 5 votes vote down vote up
def query_lists():
    """
    查询任务列表
    :return:
    """
    jobs = Query().jobs
    result = list(map(convert_job_to_info, jobs))
    return jsonify(result) 
Example 68
Project: urban-insights-backend   Author: mitevpi   File: app.py    MIT License 5 votes vote down vote up
def home():
    return jsonify({'test': 1}) 
Example 69
Project: urban-insights-backend   Author: mitevpi   File: app.py    MIT License 5 votes vote down vote up
def runSunVector():
    data = json.loads(request.data)
    vector = getSunVector(data['address'], data['month'], data['day'], data['hour'])

    return jsonify({'sunVector': vector, 'request': data}) 
Example 70
Project: urban-insights-backend   Author: mitevpi   File: app.py    MIT License 5 votes vote down vote up
def runCutObj():
    flines = cutObj()
    return jsonify({'parsedModel': flines}) 
Example 71
Project: komoot-oauth2-connect-example   Author: komoot   File: test_client.py    Apache License 2.0 5 votes vote down vote up
def profile():
    """ Step 3: Fetching a protected resource using an OAuth 2 token.
    """
    if not 'oauth_token' in session:
        return redirect(url_for('.index'))

    token_url = base_url + 'oauth/token'
    oauth_session = OAuth2Session(client_id, token=session['oauth_token'])

    # the username is needed for most requests and therefore in the token response
    username = session['oauth_token']['username']

    # fetch json document from main api
    try:
        response = oauth_session.get('https://external-api.komoot.de/v007/users/{}/tours/'.format(username))
    except TokenExpiredError:
        # access_token has expired, refresh
        # Check 'expires_in' property before sending the request and act on 401 "error"="invalid_token"
        # Request uses Basic Authentication with client_id and client_secret

        new_token = oauth_session.refresh_token(token_url, refresh_token=session['oauth_token']['refresh_token'], auth=(client_id, client_secret))

        # retry request
        oauth_session = OAuth2Session(client_id, token=new_token)
        session['oauth_token'] = new_token
        url = 'https://external-api.komoot.de/v007/users/{}/tours/'.format(username)
        response = oauth_session.get(url, headers={'Accept': 'application/hal+json'})

    tours = response.json()
    return jsonify(tours) 
Example 72
Project: eve-inc-waitlist   Author: SpeedProg   File: fleet.py    MIT License 5 votes vote down vote up
def remove_fleet(fleet_id: int):
    logger.info("%s deletes crest fleet %i", current_user.username, fleet_id)
    db.session.query(CrestFleet).filter(CrestFleet.fleetID == fleet_id).delete()
    db.session.commit()
    return flask.jsonify(status_code=200, message="Fleet Deleted") 
Example 73
Project: eve-inc-waitlist   Author: SpeedProg   File: fleet.py    MIT License 5 votes vote down vote up
def fleet_actions_invite(name: str):
    character = get_character_by_name(name)
    fleet = current_user.fleet

    if fleet is None:
        logger.info("%s tried to invite someone by name while he has no fleet",
                    current_user)
        flask.abort(428, gettext('You are not associated with a fleet!'))

    if character is None:
        logger.info('%s tried to inviate character with name=%s who does not exist.',
                    current_user,
                    name)
        flask.abort(400,
                    gettext('The character you tried to invite could not be found!'))

    logger.info("%s invites %s by name to fleet %d", current_user.username,
                name, fleet.fleetID)
    status = invite(character.id, [(fleet.dpsWingID, fleet.dpsSquadID),
                                   (fleet.otherWingID, fleet.otherSquadID),
                                   (fleet.sniperWingID, fleet.sniperSquadID),
                                   (fleet.logiWingID, fleet.logiSquadID)])
    h_entry = create_history_object(character.get_eve_id(),
                                    HistoryEntry.EVENT_COMP_INV_BY_NAME,
                                    current_user.id)
    db.session.add(h_entry)
    resp = flask.jsonify({'status': status['status_code'],
                          'message': status['text']})
    resp.status_code = status['status_code']
    return resp 
Example 74
Project: goso.ga   Author: chinapao   File: webapp.py    GNU General Public License v3.0 5 votes vote down vote up
def config():
    return jsonify({'categories': categories.keys(),
                    'engines': [{'name': engine_name,
                                 'categories': engine.categories,
                                 'shortcut': engine.shortcut,
                                 'enabled': not engine.disabled,
                                 'paging': engine.paging,
                                 'language_support': engine.language_support,
                                 'supported_languages':
                                 engine.supported_languages.keys()
                                 if isinstance(engine.supported_languages, dict)
                                 else engine.supported_languages,
                                 'safesearch': engine.safesearch,
                                 'time_range_support': engine.time_range_support,
                                 'timeout': engine.timeout}
                                for engine_name, engine in engines.items()],
                    'plugins': [{'name': plugin.name,
                                 'enabled': plugin.default_on}
                                for plugin in plugins],
                    'instance_name': settings['general']['instance_name'],
                    'locales': settings['locales'],
                    'default_locale': settings['ui']['default_locale'],
                    'autocomplete': settings['search']['autocomplete'],
                    'safe_search': settings['search']['safe_search'],
                    'default_theme': settings['ui']['default_theme'],
                    'version': VERSION_STRING,
                    'doi_resolvers': [r for r in settings['doi_resolvers']],
                    'default_doi_resolver': settings['default_doi_resolver'],
                    }) 
Example 75
Project: dci-control-server   Author: redhat-cip   File: jobs_events.py    Apache License 2.0 5 votes vote down vote up
def get_jobs_events_from_sequence(user, sequence):
    """Get all the jobs events from a given sequence number."""

    args = check_and_get_args(flask.request.args.to_dict())

    if user.is_not_super_admin():
        raise dci_exc.Unauthorized()

    query = sql.select([models.JOBS_EVENTS]). \
        select_from(models.JOBS_EVENTS.join(models.JOBS,
                    models.JOBS.c.id == models.JOBS_EVENTS.c.job_id)). \
        where(_TABLE.c.id >= sequence)
    sort_list = v1_utils.sort_query(args['sort'], _JOBS_EVENTS_COLUMNS,
                                    default='created_at')
    query = v1_utils.add_sort_to_query(query, sort_list)

    if args.get('limit', None):
        query = query.limit(args.get('limit'))
    if args.get('offset', None):
        query = query.offset(args.get('offset'))

    rows = flask.g.db_conn.execute(query).fetchall()

    query_nb_rows = sql.select([func.count(models.JOBS_EVENTS.c.id)])
    nb_rows = flask.g.db_conn.execute(query_nb_rows).scalar()

    return json.jsonify({'jobs_events': rows, '_meta': {'count': nb_rows}}) 
Example 76
Project: QuestradeAPI_PythonWrapper   Author: pcinat   File: handshake.py    Apache License 2.0 5 votes vote down vote up
def token():
    token = __get_session_token__()
    return jsonify(token), 200 
Example 77
Project: QuestradeAPI_PythonWrapper   Author: pcinat   File: handshake.py    Apache License 2.0 5 votes vote down vote up
def token_api(url):
    token = __get_session_token__()
    return jsonify(token[url]), 200 
Example 78
Project: lumberjack   Author: robertwatkins   File: server.py    GNU General Public License v3.0 4 votes vote down vote up
def post(self):
        # This does not currently allow sending only some fields. All fields must be specified.
        try:
            new_agent_id = max(self.get().get('agents')) + 1
        except:
            new_agent_id = 1
        print(request.json)
        if not request.json:
            abort(400)

        try:
            if 'agent_name' in request.json and type(request.json['agent_name']) != unicode:
                abort(400)
            if 'agencurt_type' in request.json and type(request.json['agent_type']) != unicode:
                abort(400)
            if 'log_path' in request.json and type(request.json['log_path']) != unicode:
                abort(400)
            if 'notification_channel' in request.json and type(request.json['notification_channel']) != unicode:
                abort(400)
            if 'running_status' in request.json and type(request.json['running_status']) != unicode:
                abort(400)
            if 'skill_type' in request.json and type(request.json['skill_type']) != unicode:
                abort(400)
            if 'training_status' in request.json and type(request.json['training_status']) != unicode:
                abort(400)

            new_agent_name = request.json.get('agent')[0].get('agent_name')
            new_agent_type = request.json.get('agent')[0].get('agent_type')
            new_log_path = request.json.get('agent')[0].get('log_path')
            new_notification_channel = request.json.get('agent')[0].get('notification_channel')
            new_running_status = request.json.get('agent')[0].get('running_status')
            new_skill_type = request.json.get('agent')[0].get('skill_type')
            new_training_status = request.json.get('agent')[0].get('training_status')

            insert_query = ("insert into main.agents (agent_name, agent_type, log_path ,notification_channel, running_status, skill_type, training_status, agent_id ) "
            "values ('" + new_agent_name + "', '" +new_agent_type + "', '" +new_log_path + "', '" +new_notification_channel + "', '" + new_running_status + "', '" + new_skill_type + "', '" + new_training_status + "', '" + str(new_agent_id) + "');")

            print(insert_query)
            conn = db_connect.connect()
            query = conn.execute(insert_query)
            result_json = jsonify({'result': 'success'})
        except TypeError:
            print(traceback.format_exc())
            result_json = jsonify({'result': 'failure'})

        return result_json 
Example 79
Project: lumberjack   Author: robertwatkins   File: server.py    GNU General Public License v3.0 4 votes vote down vote up
def put(self, agent_id):
        # This does not currently allow sending only some fields. All fields must be specified.
        if not request.json:
            abort(400)

        try:
            if 'agent_name' in request.json and type(request.json['agent_name']) != unicode:
                print("invalid agent_name")
                abort(400)
            if 'agent_type' in request.json and type(request.json['agent_type']) != unicode:
                print("invalid agent_type")
                abort(400)
            if 'log_path' in request.json and type(request.json['log_path']) != unicode:
                print("invalid log path")
                abort(400)
            if 'notification_channel' in request.json and type(request.json['notification_channel']) != unicode:
                print("invalid notification channel")
                abort(400)
            if 'running_status' in request.json and type(request.json['running_status']) != unicode:
                print("invalid running_status")
                abort(400)
            if 'skill_type' in request.json and type(request.json['skill_type']) != unicode:
                print("invalid skill type")
                abort(400)
            if 'training_status' in request.json and type(request.json['training_status']) != unicode:
                print("invalid training status")
                abort(400)

            new_agent_name = request.json.get('agent')[0].get('agent_name')
            new_agent_type = request.json.get('agent')[0].get('agent_type')
            new_log_path = request.json.get('agent')[0].get('log_path')
            new_notification_channel = request.json.get('agent')[0].get('notification_channel')
            new_running_status = request.json.get('agent')[0].get('running_status')
            new_skill_type = request.json.get('agent')[0].get('skill_type')
            new_training_status = request.json.get('agent')[0].get('training_status')

            update_query = ("update main.agents set agent_name = '"+ new_agent_name + "', " +
                            "agent_type = '"+new_agent_type + "', " +
                            "log_path  = '"+new_log_path + "', " +
                            "notification_channel = '" +new_notification_channel + "', " +
                            "running_status = '"+ new_running_status + "', " +
                            "skill_type = '"+ new_skill_type + "', " +
                            "training_status = '"+ new_training_status + "' " +
                            " where agent_id = '" + agent_id + "';")

            print(update_query)
            conn = db_connect.connect()
            query = conn.execute(update_query)
            result_json = jsonify({'result': 'success'})
        except TypeError:
            print(traceback.format_exc())
            result_json = jsonify({'result': 'failure'})

        return result_json 
Example 80
Project: sourceapi   Author: kradalby   File: v1.py    MIT License 4 votes vote down vote up
def root(function=None):
    response = {
        'data': {}
    }

    if not request.json:
        record_query(request, NOT_VALID_JSON)
        return json.jsonify(NOT_VALID_JSON)

    if 'data' not in request.json.keys():
        record_query(request, MISSING_DATA)
        return json.jsonify(MISSING_DATA)

    try:
        ip, port = request.json['data'].split(':')
    except:
        record_query(request, NOT_VALID_JSON)
        return json.jsonify(NOT_VALID_JSON)

    try:
        s = SourceQuery(ip, int(port))
        servername = '{}:{}'.format(ip, port)

        if function == 'all':
            response['data'][servername] = s.info()
            response['data'][servername]['players'] = s.player()
        elif function == 'serverinfo':
            response['data'][servername] = s.info()
        elif function == 'playerinfo':
            response['data'][servername] = s.player()
        elif function == 'ping':
            response['data'][servername] = s.ping()
        elif function == 'rules':
            s.timeout = 10
            response['data'][servername] = s.rules()
        else:
            record_query(request, ENDPOINT_NOT_FOUND)
            return json.jsonify(ENDPOINT_NOT_FOUND)

        response['status'] = 'success'
        record_query(request, None)
        return json.jsonify(response)
    except Exception:
        record_query(request, NO_RESPONSE)
        return json.jsonify(NO_RESPONSE)