Exemplo n.º 1
0
def chess_board_svc():
    if request.method == 'GET':
        return json.dumps({
            "board": game_server.game_board.board(),
            "width": game_server.game_board.board_width,
            "height": game_server.game_board.board_height
        })
    elif request.method == 'POST':
        msg = json.loads(request.get_data())
        player = msg["player"]
        x = msg["x"]
        y = msg["y"]
        if player in {ChessBoard.BLACK, ChessBoard.WHITE, ChessBoard.YELLOW}:
            ret_code = game_server.put_down_chess(x, y, player)
            if ret_code >= 0:
                succ = True
                msg = "下棋成功"
            elif ret_code == -1:
                succ = False
                msg = "该位置已有棋子,请更换位置"
            else:
                succ = False
                msg = "请等待其他用户下棋"
            return json.dumps({"succ": succ, "msg": msg})
        else:
            return json.dumps({"succ": False, "msg": "该用户不在棋局内"})
Exemplo n.º 2
0
def pay_cb_wx():
	data = httpc_util.xml_to_dict(request.get_data())
	
	if data["return_code"] == "SUCCESS":
		orderno = data["out_trade_no"]
		ll = orderno.split("_")
		channel = int(ll[0])
		pay_channel = ll[1]

		## 获取商户秘钥
		sql = 'select md5_key from admin_online_payment where id = %s' % pay_channel
		mch_key = LogQry(channel).qry(sql)[0][0]

		## 先判断签名
		src = "&".join(["%s=%s" % (i, data[i]) for i in sorted(data.keys()) if i != "sign"])
		src += "&key=%s" % mch_key
		sign = md5(src).upper()
		if data["result_code"] == "SUCCESS" and data["sign"] == sign: 
			## 签名校验通过 支付成功
			money = data["total_fee"]
			platform_orderno = data["transaction_id"]
			orderno = data["out_trade_no"]
			
			if do_pay_after(channel, orderno, platform_orderno, int(money), data["time_end"]):
				payload = {"return_code":"SUCCESS", "return_msg":"OK"}
				return httpc_util.dict_to_xml(payload)
			else:
				payload = {"return_code":"FAIL", "return_msg":"send err"}
				return httpc_util.dict_to_xml(payload)
		else:
			payload = {"return_code":"FAIL", "return_msg":"check sign err"}
			return httpc_util.dict_to_xml(payload)
Exemplo n.º 3
0
def token_endpoint():
    client_authn = request.headers.get("Authorization")

    if request.method == "GET":
        data = request.query_string
    elif request.method == "POST":
        data = request.get_data()

    response = current_app.op.provider.token_endpoint(data.decode("utf-8"), authn=client_authn)
    return response.message, response.status, response.headers
Exemplo n.º 4
0
 def dispatch_request(self, res_cls, handle_func_name, *args, **kwargs):
     method_name = request.method.lower()
     res = res_cls(current_app.logger, self)
     content = request.get_data(as_text=True)
     content_mime_type = request.mimetype
     result_mime_type, result_str = res.dispatch_call(handle_func_name, method_name, content,
                                                      content_mime_type, *args, **kwargs)
     response = make_response(result_str)
     response.mime_type = result_mime_type
     return response
Exemplo n.º 5
0
    def delete():
        print(f'=========== Review DELETE() !!! ===========\n')
        try:
            params = json.loads(request.get_data(), encoding='utf-8')

            # ???
            ReviewDao.delete(params['review_no'])
            print('\n=== deleted ===')
            return {'message': 'SUCCESS'}, 200

        except Exception as e:
            return {'message': 'NOT FOUND DATA'}, 404
Exemplo n.º 6
0
def predict():
    data = ''
    if request.method == 'POST':
        if request.get_data() is not None:
            data = request.get_data()
            data = json.loads(data)
        else:
            return app.response_class(response=json.dumps(
                {"status": "Invalid input"}),
                                      status=400,
                                      mimetype='application/json')
    else:
        return app.response_class(response=json.dumps(
            {"status": "Method not allowed"}),
                                  status=405,
                                  mimetype='application/json')

    # print(data)
    dat = ''
    while True:
        dat = ''.join(random.sample(chars, 16))
        if hashes.get(dat) is None:
            hashes[dat] = 1
            break
    # print(dat)
    inference.predict(data.get('text', 'sorry no data found'), f'audio/{dat}')

    @after_this_request
    def cleanup(res):
        try:
            for f in sorted(os.listdir('audio/')):
                if dat in f:
                    os.remove(f'audio/{f}')
            os.remove(f'audio/{dat}.wav')
            hashes.pop(dat)
        except Exception as e:
            pass
        return res

    return send_file(f'audio/{dat}.wav', as_attachment=True)
Exemplo n.º 7
0
def leave_game():
    msg = json.loads(request.get_data())
    color = msg['color']
    succ = True
    if color == "black":
        game_server.black_player = None
    elif color == "white":
        game_server.white_player = None
    elif color == "yellow":
        game_server.yellow_player = None
    else:
        succ = False
    return json.dumps({"succ": succ})
Exemplo n.º 8
0
def submit():
    if request.method == 'POST':
        # topic = request.get_json()["search"]
        #main.getdata(topic)
        a = request.get_data()
        data= json.loads(a)
        topic = data["topic"]
        result = main.getdata(topic)
        #print data
        return jsonify(result)  
        
        
    
    return render_template("index.html")
Exemplo n.º 9
0
def player_svc():
    if request.method == 'GET':
        return json.dumps({
            "black_ip":
            None if game_server.black_player is None else
            game_server.black_player.agent_ip,
            "white_ip":
            None if game_server.white_player is None else
            game_server.white_player.agent_ip,
            "yellow_ip":
            None if game_server.yellow_player is None else
            game_server.yellow_player.agent_ip
        })
    elif request.method == 'POST':
        msg = json.loads(request.get_data())
        player_ip = msg['ip']
        color = msg['color']
        succ = True

        # 不允许同一IP多次加入游戏
        already_into_ips = set()
        if game_server.black_player:
            already_into_ips.add(game_server.black_player.agent_ip)
        if game_server.white_player:
            already_into_ips.add(game_server.white_player.agent_ip)
        if game_server.yellow_player:
            already_into_ips.add(game_server.yellow_player.agent_ip)
        if player_ip in already_into_ips:
            succ = False
            msg = "您已经加入该棋局"
        elif color == "black" and game_server.black_player is None:
            game_server.black_player = Agent(sever_ip, player_ip, color)
            msg = '黑方成功加入棋局'
        elif color == "white" and game_server.white_player is None:
            game_server.white_player = Agent(sever_ip, player_ip, color)
            msg = '白方成功加入棋局'
        elif color == "yellow" and game_server.yellow_player is None:
            game_server.yellow_player = Agent(sever_ip, player_ip, color)
            msg = '黄方成功加入棋局'
        else:
            succ = False
            msg = '用户{0}加入棋局失败'.format(player_ip)
        return json.dumps({"succ": succ, "msg": msg})
Exemplo n.º 10
0
def client_registration():
    response = current_app.op.register_client(request.headers.get("Authorization"),
                                              request.get_data().decode("utf-8"))
    return response.message, response.status, response.headers
Exemplo n.º 11
0
def return_template(__template__):


    if request.method == 'DELETE':


         # get id of database entry  
        delete_id = request.get_data().decode()

        print(delete_id)

        # connect to db
        conn = sqlite3.connect(STATIC_PATH + "/database" + DB_NAME)
        c = conn.cursor()

        # get entry to delete
        c.execute("SELECT * FROM orders WHERE id = ?", (delete_id))
        db_entry = c.fetchone()

        # delete local qr code image
        os.remove(db_entry[3])

        c.execute("DELETE FROM orders WHERE id = ?", (delete_id))

        conn.commit()
        conn.close()

        return json.dumps({"status":True})

    elif request.method == 'PUT':

        # get id of database entry  
        status_id = request.get_data().decode()

        print(status_id)


        # connect to db
        conn = sqlite3.connect(STATIC_PATH + "/database/" + DB_NAME)
        c = conn.cursor()

        # get currently stored status from db
        c.execute("SELECT status FROM orders WHERE id = ?;", (status_id))
        db_status = c.fetchone()

        # toggle status
        if db_status[0]:
            c.execute("UPDATE orders SET status = 0 WHERE id = ?;", (status_id))
        else:
            c.execute("UPDATE orders SET status = 1 WHERE id = ?;", (status_id))

        conn.commit()
        conn.close()

        return json.dumps({"status":True})

    elif request.method == 'POST':
            
        # catch data of form
        description = request.form['new_entry_description']
        trackingLink = request.form['new_entry_trackingLink']

        # connect to db
        conn = sqlite3.connect(STATIC_PATH + "/database" + DB_NAME)
        c = conn.cursor()

        # insert data into database
        # note: qrcode is of type BLOB, which is a binary format
        c.execute("INSERT INTO orders (description, trackinglink, qrcode, status) VALUES (?, ?, ?, ?);", (description, trackingLink, QRGenModule.createQRCode(trackingLink, description, IMG_PATH), 0))
        conn.commit()
        conn.close()

        return redirect(url_for('orderlist'))


    else:

        # DATABASE DEBUG
        # db_clear_all_orders()
        # db_create_orders_table()

        conn = sqlite3.connect(STATIC_PATH + "/database" + DB_NAME)
        c = conn.cursor()
        
        c.execute("SELECT * FROM orders")
        data = c.fetchall()

        print(data)

        conn.commit()
        conn.close()

        return str(render_template(__template__, data=data))
def im():
    """ Incoming message handler: sent by ForwardClientProvider """
    req = jsonex_loads(request.get_data())
    message = g.provider.send(req['message'])
    return {'message': message}
def status():
    """ Incoming status handler: forwarded by ForwardServerProvider """
    req = jsonex_loads(request.get_data())
    status = g.provider._receive_status(req['status'])
    return {'status': status}
def im():
    """ Incoming message handler: forwarded by ForwardServerProvider """
    req = jsonex_loads(request.get_data())
    message = g.provider._receive_message(req['message'])
    return {'message': message}