예제 #1
0
def test_toItem():
    session = Session(session_start, visitor_id, avg_time, total_time)
    assert session.toItem() == {
        'PK': {
            'S': f'VISITOR#{ visitor_id }'
        },
        'SK': {
            'S': f'SESSION#{ session_start }'
        },
        'GSI2PK': {
            'S': f'SESSION#{ visitor_id }#{ session_start }'
        },
        'GSI2SK': {
            'S': '#SESSION'
        },
        'Type': {
            'S': 'session'
        },
        'AverageTime': {
            'N': str(avg_time)
        },
        'TotalTime': {
            'N': str(total_time)
        }
    }
예제 #2
0
def test_itemToSession():
    session = Session(datetime.datetime(2020, 1, 1, 0, 0), '0.0.0.0', 0.1, 0.1)
    newSession = itemToSession(session.toItem())
    assert newSession.sessionStart == session.sessionStart
    assert newSession.ip == session.ip
    assert newSession.avgTime == session.avgTime
    assert newSession.totalTime == session.totalTime
예제 #3
0
def test_itemToSession():
    session = Session(session_start, visitor_id, avg_time, total_time)
    newSession = itemToSession(session.toItem())
    assert newSession.sessionStart == session.sessionStart
    assert newSession.id == session.id
    assert newSession.avgTime == session.avgTime
    assert newSession.totalTime == session.totalTime
예제 #4
0
def test_toItem():
    session = Session(datetime.datetime(2020, 1, 1, 0, 0), '0.0.0.0', 0.1, 0.1)
    assert session.toItem() == {
        'PK': {
            'S': 'VISITOR#0.0.0.0'
        },
        'SK': {
            'S': 'SESSION#2020-01-01T00:00:00.000Z'
        },
        'GSI2PK': {
            'S': 'SESSION#0.0.0.0#2020-01-01T00:00:00.000Z'
        },
        'GSI2SK': {
            'S': '#SESSION'
        },
        'Type': {
            'S': 'session'
        },
        'AverageTime': {
            'N': '0.1'
        },
        'TotalTime': {
            'N': '0.1'
        }
    }
예제 #5
0
    def updateSession(self, session, visits, print_error=True):
        '''Updates a session with new visits and attributes.

    Parameters
    ----------
    session : Session
      The session to change the average time on page and the total time on the
      website.
    visits : list[ Visit ]
      All of the visits that belong to the session.
    '''
        if not isinstance(session, Session):
            raise ValueError('Must pass a Session object')
        if not isinstance(visits, list):
            raise ValueError('Must pass a list of Visit objects')
        if not all([isinstance(visit, Visit) for visit in visits]):
            raise ValueError('List of visits must be of Visit type')
        # Get all of the seconds per page visit that exist.
        pageTimes = [
            visit.timeOnPage for visit in visits
            if isinstance(visit.timeOnPage, float)
        ]
        # Calculate the average time the visitor spent on the pages. When there are
        # no page times, there is no average time.
        if len(pageTimes) == 1:
            averageTime = pageTimes[0]
        elif len(pageTimes) > 1:
            averageTime = np.mean(pageTimes)
        else:
            averageTime = None
        # Calculate the total time spent in this session. When there is only one
        # visit, there is no total time.
        if len(visits) == 1:
            totalTime = None
        else:
            totalTime = (visits[-1].date - visits[0].date).total_seconds()
        session = Session(visits[0].date, visits[0].ip, averageTime, totalTime)
        try:
            self.client.put_item(TableName=self.tableName,
                                 Item=session.toItem(),
                                 ConditionExpression='attribute_exists(PK)')
            self.addVisits(visits)
            return {'session': session, 'visits': visits}
        except ClientError as e:
            if print_error:
                print(f'ERROR updateSession: { e }')
            if e.response['Error'][
                    'Code'] == 'ConditionalCheckFailedException':
                return {'error': f'Session not in table { session }'}
            return {'error': 'Could not update session in table'}