示例#1
0
def log(item_id=None):
    from app.models.log import Log

    l = Log(user_id=g.user.id, action='{0}'.format(request.endpoint))
    if item_id:
        l.item_id = item_id
    l.create()
示例#2
0
    def test_get(self):
        """Test the get() method.
        """
        project = Project()
        project.save()

        entry = Log(project=project, item_value="true", log_item="logtest")
        entry.save()

        self.failUnless(logger.get(project, "logtest") ==
            Log.query.filter(Log.log_item == "logtest").all()[0].item_value)

        self.failUnless(logger.get(project, "fakerandomname") == "")
示例#3
0
def log(project, item, value, replace_value):
    """Add a new log entry to the log table.

    :param str item: The item to log (think of it as a title).
    :param str value: The value of the logged item.
    :param str replace_value: if set to logger.REPLACE, this entry will replace
        the previous entry with the same value. If set to logger.UPDATE, then
        this entry will add on to the previous entry's value with this entry's
        value in the form "old [new]".
    :return None: None.
    """

    try:
        entry = Log.query.\
            filter(Log.log_item == item).\
            filter(Log.project == project).one()
    except NoResultFound:
        entry = Log(project=project, log_item=item, item_value="")

    if REPLACE == replace_value:
        entry.item_value = value
        entry.save()

    elif UPDATE == replace_value:
        entry.item_value = entry.item_value + " [" + value + "] "
        entry.save()
示例#4
0
    def test_get(self):
        """Test the get() method.
        """
        project = Project()
        project.save()

        entry = Log(project=project, item_value="true", log_item="logtest")
        entry.save()

        self.failUnless(
            logger.get(project, "logtest") == Log.query.filter(
                Log.log_item == "logtest").all()[0].item_value)

        self.failUnless(logger.get(project, "fakerandomname") == "")
示例#5
0
文件: game.py 项目: xxr3376/Pair-Game
def create_response(cur_game, ack,actions = None):
    #print '-------------'
    #print ack
    score = 0
    if cur_game:
        #cur_game.state = cur_game.PLAYING
        print cur_game.state
        ack['userid'] = g.user.id
        score = cur_game.update_score(ack)
    if actions and (len(actions)==2 or ack['type'] == 'exit'):
        item = Log.create(
                cur_game.id,
                cur_game.get_attr('current_round'),
                cur_game.get_attr('submit_count'),
                score,
                actions)
        if ack['type'] in ['exit','done']:
            cur_game.finish()
    ret = {
        "status": states_map[ack['type']],
        "score": score,
    }
    if ack['type'] in ['done','exit']:
        Score.log_score(cur_game.id,g.user.id,score,ack['type'])

    if ack['type'] in ['match', 'timeout', 'new','fail']:
        ret["round_length"]= cur_game.round_queue_length(),
        #print ack['next']
        cur_round = Rounds.query.get(ack['next'])
        ret['round'] = json.loads(cur_round.data)
        cur_game.set_attr('current_round',ack['next'])
    return jsonify(ret)
示例#6
0
def log(project, item, value, replace_value):
    """Add a new log entry to the log table.

    :param str item: The item to log (think of it as a title).
    :param str value: The value of the logged item.
    :param str replace_value: if set to logger.REPLACE, this entry will replace
        the previous entry with the same value. If set to logger.UPDATE, then
        this entry will add on to the previous entry's value with this entry's
        value in the form "old [new]".
    :return None: None.
    """

    try:
        entry = Log.query.\
            filter(Log.log_item == item).\
            filter(Log.project == project).one()
    except NoResultFound:
        entry = Log(project=project, log_item=item, item_value="")

    if REPLACE == replace_value:
        entry.item_value = value
        entry.save()

    elif UPDATE == replace_value:
        entry.item_value = entry.item_value + " [" + value + "] "
        entry.save()
示例#7
0
 def save_to_db(data):
     # data = format_unicode_data(data)
     log = Log(
         msg_type=data['msg_type'],
         code=data['code'],
         zh_msg=data['zh_msg'],
         en_msg=data['en_msg'],
         zh_tip=data['zh_tip'],
         en_tip=data['en_tip'],
         timeout=data['timeout'],
         timestamp=data['timestamp']
     )
     db.session.add(log)
     db.session.commit()
示例#8
0
    def post(self):
        json_data = request.get_json(force=True)
        bros_bro_id = json_data["bros_bro_id"]
        token = json_data["token"]
        logged_in_bro = Bro.verify_auth_token(token)
        bro_that_is_reported = Bro.query.filter_by(id=bros_bro_id).first()

        if not logged_in_bro:
            return {
                "result": False,
                "message": "Your credentials are not valid."
            }

        if not bro_that_is_reported:
            return {"result": False, "message": "Bro not found."}

        chat = BroBros.query.filter_by(bro_id=logged_in_bro.id,
                                       bros_bro_id=bros_bro_id).first()
        if chat is None:
            return {"result": False, "message": "Chat not found."}

        chat.bro_removed()
        chat.block_chat(True)

        # We take the last 40 messages from these bros to log.
        messages = Message.query.filter_by(sender_id=logged_in_bro.id, recipient_id=bros_bro_id). \
            union(Message.query.filter_by(sender_id=bros_bro_id, recipient_id=logged_in_bro.id)). \
            order_by(Message.timestamp.desc()).paginate(1, 40, False).items

        message_log = []
        for message in messages:
            message_log.append(json.dumps(message.serialize))

        log = Log(report_from=json.dumps(logged_in_bro.serialize),
                  report_to=json.dumps(bro_that_is_reported.serialize),
                  messages=message_log,
                  report_date=datetime.utcnow())

        db.session.add(chat)
        db.session.add(log)
        db.session.commit()

        return {"result": True, "chat": chat.serialize}
示例#9
0
    def post(self):
        json_data = request.get_json(force=True)
        broup_id = json_data["broup_id"]
        token = json_data["token"]
        logged_in_bro = Bro.verify_auth_token(token)

        if not logged_in_bro:
            return {
                "result": False,
                "message": "Your credentials are not valid."
            }

        broup_that_is_reported = Broup.query.filter_by(
            broup_id=broup_id, bro_id=logged_in_bro.id).first()
        broup_objects = Broup.query.filter_by(broup_id=broup_id)
        remove_bro = Bro.query.filter_by(id=logged_in_bro.id).first()
        if not broup_that_is_reported or not broup_objects or not remove_bro:
            return {"result": False, "message": "Broup not found."}

        # We take the last 100 messages from this broup to log.
        messages = BroupMessage.query.filter_by(broup_id=broup_id).\
            order_by(BroupMessage.timestamp.desc()).paginate(1, 100, False).items

        message_log = []
        for message in messages:
            message_log.append(json.dumps(message.serialize))

        log = Log(report_from=json.dumps(logged_in_bro.serialize),
                  report_to=json.dumps(broup_that_is_reported.serialize),
                  messages=message_log,
                  report_date=datetime.utcnow())

        db.session.add(log)

        if not broup_that_is_reported.has_left():
            remove_bromotion = remove_bro.get_bromotion()
            for broup in broup_objects:
                broup_name = remove_last_occur(broup.get_broup_name(),
                                               remove_bromotion)
                broup.set_broup_name(broup_name)
                broup.remove_bro(logged_in_bro.id)
                db.session.add(broup)

            # It's possible that the user who left was the only admin in the broup at the moment.
            # When there are no admins left we randomly assign a user to be admin.
            if len(broup_that_is_reported.get_admins()) == 0:
                # In this special event we will make everyone remaining an admin.
                for broup in broup_objects:
                    if not broup.has_left() and not broup.is_removed():
                        new_admin_id = broup.bro_id
                        for broup2 in broup_objects:
                            broup2.add_admin(new_admin_id)
                            db.session.add(broup2)
            # It's possible, that the user left the broup and that there are no more bros left.
            # In this case we will remove all the messages
            if len(broup_that_is_reported.get_participants()) == 0:
                messages = BroupMessage.query.filter_by(broup_id=broup_id)
                for message in messages:
                    db.session.delete(message)
            broup_that_is_reported.leave_broup()

        broup_that_is_reported.mute_broup(True)
        broup_that_is_reported.broup_removed()

        db.session.add(broup_that_is_reported)
        db.session.commit()

        return {"result": True, "chat": broup_that_is_reported.serialize}
def read_content(context: ApiContext, id) -> dict:
    article = context.query(Article).get(id)
    log = Log(user=context.user, article=article)
    context.session.add(log)
    return article.to_json()
示例#11
0
文件: game.py 项目: xxr3376/Pair-Game
def hand_in(token):
    cur_game = Game.get_by_token(token)
    if not cur_game or not cur_game.participate(g.user)\
            or cur_game.get_attr('state') != cur_game.PLAYING:
            #or cur_game.state != cur_game.PLAYING:
        if cur_game:
                    print cur_game.state
        abort(400)

    data = request.get_json()
    if not data:
        abort(400)

    if data['type'] == 'timeout':
        handin = { 
                "timeout": True,
                'time':conf('total_time'),
                'action':Log.create_action(g.user.id,'TIMEOUT')}
    else:
        handin = {
            "timeout": False,
            "time": data['time'],
            "choice": data['choice'],
            'action':Log.create_action(
                g.user.id,
                'NORMAL',
                data['choice'],
                data['time'])
        }
    cur_game.lock()
    actions = [handin['action']]
    mate = cur_game.pop_waiting()
    ack = None
    if mate:
        actions = [handin['action'],mate['action']]
        if handin['timeout'] or mate['timeout']:
            #cur_game.update_score("timeout")
            ack = cur_game.new_round()
            if ack.get("type") != 'done':
                ack['type'] = 'timeout'
        else:
            time = max(handin['time'], mate['time'])
            state = 'fail'
            if mate['choice'] == handin['choice']:
                state = 'match'
            #cur_game.update_score(state, time)
            ack = cur_game.new_round()
            ack['state'] = state
            if ack.get("type") != 'done':
                ack['type'] = state
            #else:
             #   ack = { "type": "unmatch" }
              #  count = cur_game.get_attr('submit_count')
               # count += 1
                #cur_game.set_attr('submit_count', count)
        cur_game.notice(ack)
        cur_game.unlock()
    else:
        try:
            wait_time = conf('timeout_time')
            wait_time += conf('total_time')-handin['time']
            ack = cur_game.declare_and_wait(handin,wait_time)
        except TimeoutError:
            ack = cur_game.timeout()
            ack['state'] = 'exit'
    ack['time'] = handin['time']
    return create_response(cur_game, ack,actions)
示例#12
0
from schema import Schema, Use, Or
from unittest.mock import patch
from app.views.log import find
from app.models.log import Log
import unittest
import uuid


log = Log(
    user_id=1,
    product_id='product_id',
    company_id='company_id',
    phone_number=5511999999999,
    value=10.00
)

log_validate = Schema({
    'id': Use(str),
    'user_id': Use(int),
    'product_id': Use(str),
    'company_id': Use(str),
    'phone_number': Use(int),
    'value': Use(float),
    'created': Or(str, None)
})

logs_validate = Schema([{
    'id': Use(str),
    'user_id': Use(int),
    'product_id': Use(str),
    'company_id': Use(str),