Example #1
0
    def post(self):

        """
        # function post response http POST position with info
        """
        try:
            print('Begin to post')
            print(session)
            args = parser.parse_args()
            classid = session['classid']
            userid = session['userid']
            classstr = session['classstr']
            roleid = int(redis_store.get("roleid:"+userid))
            print(roleid)
            if ('classid' in session) and ('userid' in session):
                if (roleid == 1):
                    pptposition = args['pptposition']
                    pptinfo = args['pptinfo']
                    if (pptposition is not None):
                        sse.publish({"pptposition":pptposition},
                                    type="newposition"+classstr,
                                    channel="changed.ppt" )
                    if (pptinfo is not None):
                        sse.publish({"pptinfo":pptinfo},
                                    type="pptinfo"+classstr,
                                    channel="changed.ppt" )
                        redis_store.set('ppt:'+classid, pptinfo)
        except Exception as err:
            print("Fail to get info")
            print(err)
Example #2
0
def sleep():
    data = request.json or request.form
    minutes = int(data.get('minutes'))
    yeelight.set_sleep(minutes)
    print('Set sleep: {}'.format(minutes))
    sse.publish(get_status(), type='update')
    return 'OK'
Example #3
0
def light_set():
    data = request.json or request.form

    brightness = data.get('brightness')
    rgb = data.get('rgb')
    color = data.get('color')
    temp = data.get('temp')

    if brightness:
        print('Set brightness: {}'.format(brightness))
        yeelight.set_brightness(int(brightness))

    if rgb:
        print('Set rgb: {}'.format(rgb))
        yeelight.set_rgb(rgb)
    elif color:
        color = color.replace(' ', '')
        print('Set color {}'.format(color))
        try:
            rgb = webcolors.name_to_hex(color)[1:]
        except ValueError as e:
            return str(e)
        else:
            yeelight.set_rgb(rgb)
    elif temp:
        temp = int(temp)
        print('Set temp: {}'.format(temp))
        yeelight.set_temp(temp)

    sse.publish(get_status(), type='update')

    return 'OK' if any((brightness, rgb, temp)) else 'FAIL'
Example #4
0
def switch():
    if request.method == 'GET':
        return '1' if yeelight.switch == 1 else '0'

    if request.method == 'POST':
        data = request.json or request.form
        switch = data.get('switch')
    elif request.method in ('PUT', 'DELETE'):
        if request.method == 'PUT':
            switch = 'on'
        else:
            switch = 'off'

    command = {
        'on': yeelight.poweron,
        'off': yeelight.poweroff,
        '1': yeelight.poweron,
        '0': yeelight.poweroff,
    }
    if switch in command:
        command[switch]()
        print('Turn {} the light'.format(switch))
        sse.publish(get_status(), type='update')
        return 'OK'

    return 'Fail'
Example #5
0
def leave():
    details = request.get_json()
    id = details['id']
    username = r.hget(f'user:{id}', 'username')
    removed = r.srem('lobby', f'{id}:{username}')
    if removed:
        sse.publish({'id': id}, type='leave', channel='lobby')
    return jsonify(status='OK')
Example #6
0
def login1(username, password):
    user = SkypeUserModel.objects(username=username, password=password).first()
    if not user:
        sse.publish({"message": 'no user'}, type='loginn')
        return 'no user'
    else:
        sse.publish({"message": user.username + ' ' + user.password}, type='loginn')
        return user.username + ' ' + user.password 
Example #7
0
def command_stop(id):
    global process_dict
    "command_stop".p()
    if id in process_dict and process_dict[id].is_alive():
        process_dict[id].need_stop = True
        print("force stopped")
        sse.publish({"msg": "force stopped!"}, type='result')
    return "success"
Example #8
0
def processEachRDD(rdd):
    eval_counts = rdd.collect()
    len_eval_counts = len(eval_counts)

    if not len_eval_counts == 0:

        ups = []
        downs = []
        counter = 0
        for item in eval_counts:
            if counter % 2 == 0:
                ups.append(item)
            else:
                downs.append(item)
            counter += 1
        up_sum = sum(ups)
        down_sum = sum(downs)

        res_str = " ".join([str(up_sum), str(down_sum)])
        fo = open(filepath, "a", encoding='utf-8')
        fo.write(res_str)
        fo.write("\n")
        fo.flush()
        fo.close()

        fr = open(filepath, "r", encoding='utf-8')
        lines = fr.readlines()
        ups = []
        downs = []
        evals = []

        up_ratio = []
        totals = []

        for line in lines:
            if not line == "":
                up_tmp, down_tmp = line.split(" ")
                up_tmp = int(up_tmp)
                down_tmp = int(down_tmp)
                eval_tmp = up_tmp + down_tmp

                ups.append(up_tmp)
                downs.append(down_tmp)
                evals.append(eval_tmp)

                up_ratio.append(100 * sum(ups) / sum(evals))
                totals.append(sum(evals))

        print("totals: {}, ratio: {}".format(totals, up_ratio))

        with app.app_context():
            sse.publish(
                {
                    "totals": totals,
                    "up_ratio": up_ratio,
                    "max": totals[-1]
                },
                type='eval')
Example #9
0
def on_alert_posted(alerts):
    for alert in alerts:
        logger.debug(f"Alert {alert['id']} published.")
        sse.publish(alert, type='alert')
        if alert["operative_status"] == enums.OperativeStatus.CONFIRMED:
            try:
                execute_automatic_response(alert)
            except Exception as e:
                logger.error("Error executing automatic response plan: %s" % e)
Example #10
0
 def run(this):
     while True:
         time.sleep(5)
         updates = this.get_online_players()
         if len(updates) > 0:
             print updates
         with app.app_context():
             for update in updates:
                 sse.publish({"message": json.dumps(update)}, type='loginEvent')
Example #11
0
def put_data():
  last_scan = request.get_json()["data"]
  app.logger.debug("last scan: {}".format(last_scan))

  worker = service.put_scanned_data(last_scan)

  message = json.dumps({"message": worker})
  sse.publish(message, type='scans')
  return make_response("OK", 200)
Example #12
0
 def sse_response():
     while True:
         send_time = str(time.time())
         template = render_template('message.html',
                                    id=random.randint(1, 10000),
                                    time=send_time)
         sse.publish(template, type='message')
         time.sleep(0.5)
         print('streamed', send_time)
Example #13
0
def send_messages():
    channel = request.values.get('channel')
    message = request.values.get('message')

    # 关于channel的使用==> http://flask-sse.readthedocs.io/en/latest/advanced.html
    # 如channel是channel_bob,则只有channel_bob.html才能接收数据
    # sse推送消息
    sse.publish({"message": message}, type='social', channel=channel)
    return jsonify({'code': 200, 'errmsg': 'success', 'data': None})
Example #14
0
def publish_hello():
    print(request.data['message'])
    sse.publish(
        {
            "sender": request.data["sender"],
            "message": request.data['message']
        },
        type='message')
    return "Message sent!"
Example #15
0
 def callback(progress):
     with flask.app_context():
         sse.publish(
             {
                 'url': url,
                 'status': 'in_progress',
                 'progress': progress['data'].decode('utf-8')
             },
             channel=url)
Example #16
0
def pick_winner():
    winnerText = request.args.get('card')
    pid = request.args.get('pid')
    czar = redis.get('czar')
    cardText = ""

    responseData = {}

    session['pid'] = session.get('pid')
    if session['pid'] is None:
        if pid is None:
            responseData.update({'error' : "pid is very empty, something went wrong"})
            return jsonify(responseData)
        session['pid'] = pid

    if czar != session['pid']:
        responseData.update({'error' : "Can't pick a winner if you're not the card czar"})
        return jsonify(responseData)

    card = redis.lpop('in-play')

    # Empty the in-play card list and find a winner
    while card is not None:
        cardPid = card.split(":")[0]
        cardText = card.split(":")[1]

        if str(cardText) == str(winnerText):
            winnerName = redis.hget(cardPid, 'name')
            winnerPid = cardPid
            redis.hincrby(winnerPid, 'score', 1)
            responseData.update({'winnerName' : winnerName})

        card = redis.lpop('in-play')

    newCzar = False
    czarNext = False

    while newCzar == False:
        for player in redis.lrange('players', 0, -1):
            redis.hset(player, 'ready', 'no')
            if czarNext:
                czar = player
                redis.hset(player, 'ready', 'yes')
                redis.set('czar', player)

                newCzar = True
                break

            if player == czar:
                czarNext = True

    responseData.update({'newCzar' : czar})

    new_black_card()

    sse.publish({"winner" : winnerPid, "winnerName" : winnerName, "newCzar" : czar}, type='pick-winner')
    return jsonify(responseData)
Example #17
0
def update_current_beacons():
    data = request.get_data()
    store.set_current_beacons(data)

    next_beacon = store.get_nearest_beacon()
    content = store.get_beacon_info(next_beacon)
    sse.publish(content, type='display_update')

    return "Beacon data successfully stored"
Example #18
0
def send(channel_name, massage_type):
    print("Hello channel send!")
    # print "req:  ", request.data
    #sse.publish({,  "type"=massage_type, "channel"=channel_name})
    sse.publish({"message": request.data},
                type=massage_type,
                channel=channel_name)
    # sse.publish('''{"message": "Hello!"}, type='greeting'''')
    return ("send", massage_type, "to", channel_name)
Example #19
0
def syncTaskListInClient():
    print("*********** syncTaskListInClient *****************")
    payload = {}
    sse.publish(type='greeting',
                data={
                    'storeID': 'TASK',
                    'operation': 'LOAD',
                    'payload': payload
                })
Example #20
0
def send_offer():
    data = loads(request.data)
    sse.publish({
        'username': current_user.username,
        'offer': data.get('offer')
    },
                type='offer',
                channel=data.get('username'))
    return Response('ok', status=200)
Example #21
0
def pull_images():
    _docker_login()  # do not perform login every time
    images = _get_image_tags(app.config['DOCKER_USER'],
                             app.config['DOCKER_PASSWORD'],
                             app.config['DOCKER_API_SERVER'])
    for image in images:
        for line in docker.pull(*image.split(':'), stream=True):
            sse.publish("data:{}".format(line))
    return "All good!"
Example #22
0
 def write(self, *args):
     s = ""
     for arg in args:
         s += " " + str(arg)
     with app.app_context():
         try:
             sse.publish({"data": s}, channel=self.jobID)
         except AttributeError:
             sys.__stdout__.write(" * Orphaned Message: " + s)
Example #23
0
def joinGame(gameID):
    username = request.get_json(force=True)
    print(username)
    game = [i for i in Game.query.all() if i.id == int(gameID)][0]
    player = Player(username=username, score=0, isFacilitator=False, game=game)
    db.session.add(player)
    db.session.commit()
    sse.publish(json.dumps(username), type='newPlayer')
    return jsonify(game.category.name)
Example #24
0
def submit_card():
    cardIndex = request.args.get('card')
    pid = request.args.get('pid')
    czar = redis.get('czar')
    ready = 'yes'

    responseData = {}

    session['pid'] = session.get('pid')
    if session['pid'] is None:
        if pid is None:
            responseData.update({'error' : "pid is very empty, something went wrong"})
            return jsonify(responseData)
        session['pid'] = pid

    if czar == session['pid']:
        responseData.update({'error' : "Can't pick a card if you're the card czar"})
        return jsonify(responseData)

    redis.hset(session['pid'], 'ready', ready)

    cardText = session['hand'].get(cardIndex)
    redis.lpush('in-play', "{}:{}".format(session['pid'], cardText))

    session['hand'].update({cardIndex : str(redis.lpop('white'))})

    sse.publish({"pid":pid}, type='picked-card')

    responseData.update({'czar' : czar})
    responseData.update({'cardText' : cardText})
    responseData.update({'cardIndex' : cardIndex})
    responseData.update({'blackCard' : str(redis.get('black-card'))})

    if redis.llen('in-play') == redis.llen('players') - 1 and redis.llen('players') > 2:
        cardText = []
        cardsList = []

        # Shuffle and empty the in-play card list
        card = redis.lpop('in-play')
        while card is not None:
            cardsList.append(card)

            card = redis.lpop('in-play')

        random.shuffle(cardsList)

        # Build the new shuffled list and publish the card text to the clients
        for card in cardsList:
            cardText.append(card.split(":")[1])

            redis.lpush('in-play', card)

        # Publish all of the cards in play
        sse.publish({"cards" : cardText}, type='cards-in-play')

    return jsonify(responseData)
Example #25
0
def push_log(message, channel):
    if channel != 'analysis':
        sse.publish({"message": message}, type='social', channel=channel)
        print('%s 发送成功!' % message)
        analysis(message)
    elif channel == 'analysis':
        sse.publish({"message": message}, type='social', channel=channel)
        print('%s 发送成功!' % message)
    else:
        print('发送消息失败')
Example #26
0
def send_candidate():
    data = loads(request.data)
    sse.publish(
        {
            'candidate': data.get('candidate'),
            'username': current_user.username
        },
        type='candidate',
        channel=data.get('username'))
    return Response('ok', status=200)
Example #27
0
    def __init__(self, name, root, input_file):

        # sanity-check: do not instantiate if PE is malformed
        filecontent = input_file.read()
        try:
            _ = pefile.PE(data=filecontent)
        except pefile.PEFormatError:
            raise WorkerException("Is not a valid PE/EXE file! Cannot parse.")

        # if a valid executable, then start creating valid metadata for it
        self.name = name
        self.timestamp = str(datetime.datetime.utcnow())
        self.uuid = str(uuid.uuid4())

        # store file's checksum to check against for file uniquity
        hasher = hashlib.sha256()
        for block in iter(lambda: input_file.read(4096), b""):
            hasher.update(block)
        self.checksum = hasher.hexdigest()

        # instantiate new workspace directory
        self.workspace = BoaWorker.init_workspace(root, self.name)

        # include path to binary in workspace as well
        self.path = os.path.join(self.workspace, self.name)

        # move file pointer back to beginning, and save
        input_file.stream.seek(0)
        input_file.save(self.path)

        # parsed out information regarding the executable

        # python version
        self.pyver: int = 0

        # packer object used to generate final executable
        self.packer: t.Optional[unpack.BaseUnpacker] = None

        # stores parsed paths to bytecode files
        self.bytecode_paths: t.List[str] = []

        # decompiler object used to recover source code
        self.decompiler: t.Optional[decompile.BoaDecompiler] = None

        # stores recovered source files that are relevant for analyze
        self.relevant_src = []

        # parsed out security issues from bandit
        self.sec_issues = {}

        # stores any errors parsed out during execution
        self.error = None

        # push event to represent new task initializing
        sse.publish({"uuid": self.uuid}, type="events")
Example #28
0
def reset_puzzle_pieces_and_handle_errors(puzzle):
    cur = db.cursor()
    result = cur.execute(
        fetch_query_string("select_all_from_puzzle_for_id.sql"),
        {
            "id": puzzle
        },
    ).fetchall()
    if not result:
        cur.close()
        raise DataError("No puzzle found with that id.")

    (result, col_names) = rowify(result, cur.description)
    puzzle_data = result[0]
    cur.close()

    try:
        reset_puzzle_pieces(puzzle)
    # TODO: Fix handling of errors on puzzle reset pieces
    except Error as err:
        # Update puzzle status to RENDERING_FAILED
        r = requests.patch(
            "http://{HOSTAPI}:{PORTAPI}/internal/puzzle/{puzzle_id}/details/".
            format(
                HOSTAPI=current_app.config["HOSTAPI"],
                PORTAPI=current_app.config["PORTAPI"],
                puzzle_id=puzzle_data["puzzle_id"],
            ),
            json={"status": RENDERING_FAILED},
        )
        sse.publish(
            "status:{}".format(RENDERING_FAILED),
            channel="puzzle:{puzzle_id}".format(
                puzzle_id=puzzle_data["puzzle_id"]),
        )
        if r.status_code != 200:
            raise Exception("Puzzle details api error")

    # Update puzzle status to ACTIVE and sse publish
    r = requests.patch(
        "http://{HOSTAPI}:{PORTAPI}/internal/puzzle/{puzzle_id}/details/".
        format(
            HOSTAPI=current_app.config["HOSTAPI"],
            PORTAPI=current_app.config["PORTAPI"],
            puzzle_id=puzzle_data["puzzle_id"],
        ),
        json={"status": ACTIVE},
    )
    sse.publish(
        "status:{}".format(ACTIVE),
        channel="puzzle:{puzzle_id}".format(
            puzzle_id=puzzle_data["puzzle_id"]),
    )
    if r.status_code != 200:
        raise Exception("Puzzle details api error")
Example #29
0
def send_messages():
    #channel = request.values.get('channel')
    channel = 'log'
    #message = request.values.get('message')
    p = subprocess.Popen('tail -f ./test.log', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE,)    #起一个进程,执行shell命令
    while True:
        line = p.stdout.readline()   #实时获取行
        if line:                     #如果行存在的话
            message = str(line.strip())
            sse.publish({"message": message}, type='social', channel=channel)
    return jsonify({'code': 200, 'errmsg': 'success', 'data': None})
Example #30
0
    def post(self):
        """
        create chatRoom
        """
        print("this is CreateRoom")

        data = request.json
        session_id = data['session_id']
        calleeUsername = data['calleeUsername']

        print(data)

        username = redis_store.get_item(session_id)
        if not username:
            return ({'Status': 'Please Login'})

        username = username.decode('utf-8')

        #generate random Room ID
        chars = string.ascii_uppercase + string.digits
        roomID = ''.join(random.choice(chars) for _ in range(8))

        #generate callee ssesion id
        calleeUsername = str(calleeUsername)
        calleeSession_id = hashlib.sha256(calleeUsername.encode()).hexdigest()

        print(1)
        #save roomid in chat_store
        #value = {'caller':username, 'message':''}
        #chat_store.hmsetall(roomID, value)
        #chat_store.hmset(roomID, 'message', 'hy')

        #check callee is login and send chat request\

        print(calleeUsername)
        print(2)
        if (redis_store.get_item(calleeSession_id) != None):
            print(3)
            sse.publish(
                {
                    "state": "invite",
                    'roomID': roomID,
                    "callerUsername": username
                },
                type=calleeUsername + 'calleeEvent')
            return jsonify({
                'status': 200,
                'message': ' send your invitation to ' + calleeUsername,
                'roomID': roomID
            })

        #sse.publish({"message": "Hello!"}, type='greeting')

        return jsonify({'status': 400})
Example #31
0
def post_message():
    ret_data = {"value": request.args.get('messageValue')}
    post = Post()
    post.constain = ('%.200s' % ret_data['value'])
    post.author = current_user.username
    post.post_datetime = datetime.datetime.utcnow()
    db.session.add(post)
    db.session.commit()
    sse.publish({"message": "updatemessage"}, type='greeting')
    #posts = Post.query.order_by(Post.post_datetime.desc()).filter_by()
    return jsonify({'value': 'Succesed.'})
Example #32
0
def send(channel_name, massage_type):
    print "Hello channel send!"
    sse.publish({"message": request.data},
                type=massage_type,
                channel=channel_name)
    return "send", massage_type, "to", channel_name


# @app.route('/')
# def index():
#     return render_template("index.html")
# @app.route('/webrtc')
# def webrtc():
#     return render_template("sec.html")
#
# @app.route('/hello')
# def publish_hello():
#     sse.publish({"message": "Hello!"}, type='greeting')
#     return "Message sent!"

# @app.route('/xhr',  methods=['GET', 'POST'])
# def xhr():
#     data = request.form
#     room_id = request.form.get('chat_id')
#     tab_uuid = request.form.get('uuid')
#     if r.exists(room_id):
#         return json.dumps({'success': False}), 400, {'ContentType': 'application/json'}
#     r.set(room_id,tab_uuid)
#
#
#
#
#     return json.dumps({'success': True}), 200, {'ContentType': 'application/json'}

# @app.route('/joinxhr',  methods=['GET', 'POST'])
# def joinxhr():
#     data = request.form
#     room_id = request.form.get('chat_id')
#     if r.exists(room_id):
#         uuid= r.get(room_id)
#         # sse.publish({"message": "one peer are calling","room_id" : room_id}, type=uuid)
#         return json.dumps({'success': True}), 200, {'ContentType': 'application/json'}
#
#
#     # r.set(room_id,1)
#
#
#
#
#     return json.dumps({'success': False}), 400, {'ContentType': 'application/json'}
#
# @app.route('/join')
# def join():
#     return render_template("join.html")
Example #33
0
def sse_turn_off():
    global is_on

    turn_off()
    is_on = False

    # need to make sure this exists
    # also, make sure that redis is running on your pi
    with app.app_context():
        # sse, make sure to capture as success in js
        sse.publish({'success': 'True'}, type='success')
Example #34
0
def return_poll():
    data = request.get_json()
    options = data.get("options")
    code = data.get("code")
    sse.publish({
        "options": options,
        "code": code
    },
                type='answers',
                channel=code)
    return render_template("answering.html", roomCode=code)
Example #35
0
def light():
    if request.method == 'GET':
        return jsonify(get_status())
    elif request.method == 'PUT':
        yeelight.poweron()
        sse.publish(get_status(), type='update')
    elif request.method == 'DELETE':
        yeelight.poweroff()
        sse.publish(get_status(), type='update')

    return 'OK'
def server_side_event(scheduled=True, supplierID=None):
    """ Function to publish server side event """
    with app.app_context():
        channel = f"supplierID_{supplierID}"
        print(channel)
        sse.publish(next(get_data()), type='newOrder', channel=channel)
        if scheduled:
            print("Event Scheduled at ", datetime.datetime.now())
        else:
            print(f"Event triggered for channel=supplierID_{supplierID} at ",
                  datetime.datetime.now())
def fetch_updates():
    """
         该步骤实际上是向redis的sse频道(channel), 发布了一条消息, 而且是以SSE格式发送的
         即 data: "", 而type则是event-type(前端需要为该事件添加监听器, 以接受数据)
         publish ---> self.redis.publish(channel=channel)
    """
    sse.publish({
        'question': 'which programming is the best?',
        'value': 'Absolutely, PHP',
        'who': 'allen'
    }, type='new_answers')
    return json.dumps({"state": "ok"})
Example #38
0
    def post(self):
        """Create a new message.

        """

        text = get_valid_json(self.SCHEMA)['text']
        user_id = (db.session.query(models.User)
                   .filter(models.User.username == auth.username())
                   .first().id)
        new_message = models.Message(user_id, text)
        db.session.add(new_message)
        db.session.commit()
        new_message_from_db = self.get(new_message.id)
        sse.publish(new_message_from_db, type='message')
        return new_message_from_db
Example #39
0
    def post(self):

        """
        # function post response http POST txt to chatlist
        """
        try:
            print("ready to receive post message")
            args = parser.parse_args()
            if ('classid' in session) and ('userid' in session):
                classid = session['classid']
                userid = session['userid']
                classstr = session['classstr']
                question = args['txt']
                chatnum = str(int(redis_store.get("chatnum:"+classid))+1)
                username = redis_store.get("username:"******"roleid:"+userid)
                createtime = datetime.datetime.now()

                if roleid == '1':
                    rolename = "teacher"
                elif roleid == '2':
                    rolename = "student"
                createtimestr = createtime.strftime("%Y-%m-%d %H:%M:%S")
                newmessage = dict(chatnum=chatnum,
                                  username=username,
                                  createtime=createtimestr,
                                  rolename=rolename,
                                  question=question)
                print("Ready to save redis")
                redis_store.lpush("chatcontent:"+classid, chatnum)
                redis_store.lpush("chatcontent:"+classid, username)
                redis_store.lpush("chatcontent:"+classid, createtimestr)
                redis_store.lpush("chatcontent:"+classid, rolename)
                redis_store.lpush("chatcontent:"+classid, question)
                redis_store.set("chatnum:"+classid, chatnum)
                print(newmessage)
                sse.publish({"message":newmessage},
                            type=("newchatmessage"+classstr),
                            channel="changed.chatroom")
                # print("newchatmessage"+classstr)
                # print(len("newchatmessage"+classstr))
                return newmessage
            else:
                return "You have no right to do this"
        except Exception as err:
            print("Fail to add chat text")
            print(err)
Example #40
0
def command_run(id):
    global process_dict
    "command_run".p()
    sse.publish({"msg": "Hello!"}, type='result')
    log_path = "output.log"
    end_str = "###allend"

    if os.path.exists(log_path):
        os.remove(log_path)
    file_ = open(log_path, "w")
    try:
        def output(msg):
            file_.write(msg)
            file_.flush()
        result = [0]
        cur_process = Thread(target=exe.func_with_file, 
                    args=(10, result, output, end_str))
        process_dict[id] = cur_process
        cur_process.start()
        # cur_process.join()

        for line in exe.tail(log_path, 0):
            # line.p()
            if line == end_str:
                sse.publish({"msg": "close!"}, type='close')
                break
            else:
                sse.publish({"msg": line}, type='result')
    finally:
        file_.close()
    "in2333".p()
    return "success"
Example #41
0
def ding():
        print "received data from python!!"
        username = request.get_json()
        print username
        sse.publish({"message": username}, type='greeting')
        return "Message sent!"
Example #42
0
    def post(self):
        """
        # function post response http POST teastatus with info
        """
        try:
            print('Begin to post')
            print(session)
            args = parser.parse_args()
            classid = session['classid']
            userid = session['userid']
            classstr = session['classstr']
            username = redis_store.get('username:'******'classstr']
            userinfo["roleid"] = int(redis_store.get("roleid:"+userid))

            if ('classid' in session) and ('userid' in session):

                if roleid == 1:
                    teaname = args['teaname']
                    tealinkstatus = args['tealinkstatus']
                    print("print post info");
                    print(teaname);
                    print(tealinkstatus);

                    if tealinkstatus is not None:
                        print("Teacher status changes to {0}".format(str(tealinkstatus)))
                        redis_store.hset('tealinkstatus_dict:'+classid,
                                         teaname, tealinkstatus)

                        tealinkstatus_hash = redis_store.hgetall('tealinkstatus_dict:'+classid)
                        tealinkstatus_dict = {"0": [], "1": [], "2": [], "3": []}
                        for (k, v) in tealinkstatus_hash.items():
                            for ni in range(4):
                                if v == str(ni):
                                    tealinkstatus_dict[str(ni)].append(k)
                                    break

                        sse.publish({"tealinkstatus":tealinkstatus_dict},
                                    type="newtealinkstatus"+classstr,
                                    channel="changed.status")
                        print(tealinkstatus_dict)
                        print("newtealinkstatus"+classstr)


                    stuname = args['stuname']
                    stulinkstatus = args['stulinkstatus']

                    if stulinkstatus is not None:
                        print("Student status changes to {0}".format(str(stulinkstatus)))
                        redis_store.hset('stulinkstatus_dict:'+classid,
                                         stuname, stulinkstatus)

                        stulinkstatus_hash = redis_store.hgetall('stulinkstatus_dict:'+classid)
                        stulinkstatus_dict = {"0": [], "1": [], "2": [], "3": []}
                        for (k, v) in stulinkstatus_hash.items():
                            for ni in range(4):
                                if v == str(ni):
                                    stulinkstatus_dict[str(ni)].append(k)
                                    break

                        sse.publish({"stulinkstatus":stulinkstatus_dict},
                                    type="newstulinkstatus"+classstr,
                                    channel="changed.status")
                        print(stulinkstatus_dict)
                        print("newstulinkstatus"+classstr)

                    tea_list = redis_store.lrange('tea_list:'+classid, 0, -1)
                    stu_list = redis_store.lrange('stu_list:'+classid, 0, -1)

                    tealinkstatus_hash = redis_store.hgetall('tealinkstatus_dict:'+classid)
                    stulinkstatus_hash = redis_store.hgetall('stulinkstatus_dict:'+classid)

                    tealinkstatus_dict = {"0": [], "1": [], "2": [], "3": []}
                    stulinkstatus_dict = {"0": [], "1": [], "2": [], "3": []}

                    for (k, v) in tealinkstatus_hash.items():
                        for ni in range(4):
                            if v == str(ni):
                                tealinkstatus_dict[str(ni)].append(k)
                                break

                    for (k, v) in stulinkstatus_hash.items():
                        for ni in range(4):
                            if v == str(ni):
                                stulinkstatus_dict[str(ni)].append(k)
                                break

                    userinfo["teacher"] = tea_list
                    userinfo["student"] = stu_list
                    userinfo["tealinkstatuslist"] = tealinkstatus_dict
                    userinfo["stulinkstatuslist"] = stulinkstatus_dict

                    print("Success to update status in session")
                    return userinfo
                elif roleid == 2:
                    stuname = args['stuname']
                    stulinkstatus = args['stulinkstatus']
                    print("Student status changes to {0}".format(str(stulinkstatus)))
                    redis_store.hset('stulinkstatus_dict:'+classid,
                                     stuname, stulinkstatus)

                    stulinkstatus_hash = redis_store.hgetall('stulinkstatus_dict:'+classid)
                    stulinkstatus_dict = {"0": [], "1": [], "2": [], "3": []}
                    for (k, v) in stulinkstatus_hash.items():
                        for ni in range(4):
                            if v == str(ni):
                                stulinkstatus_dict[str(ni)].append(k)
                                break

                    sse.publish({"stulinkstatus":stulinkstatus_dict},
                                type="newstulinkstatus"+classstr,
                                channel="changed.status")
                    print(stulinkstatus_dict)
                    print("newstulinkstatus"+classstr)

                    tea_list = redis_store.lrange('tea_list:'+classid, 0, -1)
                    tealinkstatus_hash = redis_store.hgetall('tealinkstatus_dict:'+classid)
                    tealinkstatus_dict = {"0": [], "1": [], "2": [], "3": []}
                    for (k, v) in tealinkstatus_hash.items():
                        for ni in range(4):
                            if v == str(ni):
                                tealinkstatus_dict[str(ni)].append(k)
                                break

                    userinfo["teacher"] = tea_list
                    userinfo["tealinkstatuslist"] = tealinkstatus_dict

                    print("Success to update status in session")
                    return userinfo
                else:
                    return "role id is not existed"
            else:
                print("You have no right to do this")
                return "You have no right to do this"
        except Exception as err:
            print("Fail to update status")
            print(err)