<commit_before>from pyramid.view import view_config
from pyramid.httpexceptions import (
    HTTPNotFound,
    HTTPBadRequest,
    HTTPUnauthorized,
    HTTPForbidden,
)
from ..models import (
    DBSession,
    Task,
    TaskState,
    TaskLock,
    TaskComment,
    PriorityArea,
    Project,
    User,
    Message,
)
from geoalchemy2 import (
    shape,
)

from sqlalchemy.orm import (
    joinedload,
)

from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy.exc import OperationalError
from sqlalchemy.sql.expression import (
    not_,
    and_,
    func,
)

from pyramid.security import authenticated_userid

import datetime
import random

from ..models import EXPIRATION_DELTA, ST_SetSRID

import logging
log = logging.getLogger(__name__)


def __get_user(request, allow_none=False):
    user_id = authenticated_userid(request)

    if not user_id:
        if allow_none:
            return None
        raise HTTPUnauthorized()

    user = DBSession.query(User).get(user_id)

    if not allow_none and not user:  # pragma: no cover
        raise HTTPUnauthorized()

    return user


def __get_task(request, lock_for_update=False):
    check_task_expiration()
    task_id = request.matchdict['task']
    project_id = request.matchdict['project']
    filter = and_(Task.project_id == project_id, Task.id == task_id)
    query = DBSession.query(Task) \
                     .options(joinedload(Task.cur_lock)) \
                     .filter(filter)

    if lock_for_update:
        query = query.with_for_update(nowait=True, of=Task)

    try:
        task = query.one()
    except NoResultFound:
        task = None
    except OperationalError:  # pragma: no cover
        raise HTTPBadRequest("Cannot update task. Record lock for update.")

    if not task or \
       task.cur_state and task.cur_state.state == TaskState.state_removed:
        # FIXME return translated text via JSON
        raise HTTPNotFound("This task doesn't exist.")
    return task


def __ensure_task_locked(task, user):
    locked_task = get_locked_task(task.project_id, user)
    if locked_task != task:
        raise HTTPForbidden("You need to lock the task first.")


@view_config(route_name='task_xhr', renderer='task.mako')
def task_xhr(request):
    user = __get_user(request, allow_none=True)
    task = __get_task(request)

    locked_task = get_locked_task(task.project_id, user)

    task_id = request.matchdict['task']
    project_id = request.matchdict['project']

    filter = and_(TaskState.task_id == task_id,
                  TaskState.project_id == project_id)
    states = DBSession.query(TaskState).filter(filter) \
        .order_by(TaskState.date).all()
    # remove the first state (task creation with state==ready)
    states.pop(0)

    filter = and_(TaskLock.task_id == task_id,
                  TaskLock.project_id == project_id)
    locks = DBSession.query(TaskLock).filter(filter) \
        .order_by(TaskLock.date).all()
    # remove the first lock (task creation)
    locks.pop(0)

    filter = and_(TaskComment.task_id == task_id,
                  TaskComment.project_id == project_id)
    comments = DBSession.query(TaskComment).filter(filter) \
        .order_by(TaskComment.date).all()

    history = states + locks + comments

    history = sorted(history, key=lambda step: step.date, reverse=True)

    return dict(task=task,
                user=user,
                locked_task=locked_task,
                history=history)


@view_config(route_name='task_empty', renderer='task.empty.mako')
def task_empty(request):
    user = __get_user(request, allow_none=True)
    project_id = request.matchdict['project']
    locked_task = get_locked_task(project_id, user)
    assigned_tasks = get_assigned_tasks(project_id, user)

    return dict(locked_task=locked_task, project_id=project_id,
                assigned_tasks=assigned_tasks, user=user)
<commit_msg>Fixing cache issues in task views<commit_after>from pyramid.view import view_config
from pyramid.httpexceptions import (
    HTTPNotFound,
    HTTPBadRequest,
    HTTPUnauthorized,
    HTTPForbidden,
)
from ..models import (
    DBSession,
    Task,
    TaskState,
    TaskLock,
    TaskComment,
    PriorityArea,
    Project,
    User,
    Message,
)
from geoalchemy2 import (
    shape,
)

from sqlalchemy.orm import (
    joinedload,
)

from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy.exc import OperationalError
from sqlalchemy.sql.expression import (
    not_,
    and_,
    func,
)

from pyramid.security import authenticated_userid

import datetime
import random

from ..models import EXPIRATION_DELTA, ST_SetSRID

import logging
log = logging.getLogger(__name__)


def __get_user(request, allow_none=False):
    user_id = authenticated_userid(request)

    if not user_id:
        if allow_none:
            return None
        raise HTTPUnauthorized()

    user = DBSession.query(User).get(user_id)

    if not allow_none and not user:  # pragma: no cover
        raise HTTPUnauthorized()

    return user


def __get_task(request, lock_for_update=False):
    check_task_expiration()
    task_id = request.matchdict['task']
    project_id = request.matchdict['project']
    filter = and_(Task.project_id == project_id, Task.id == task_id)
    query = DBSession.query(Task) \
                     .options(joinedload(Task.cur_lock)) \
                     .filter(filter)

    if lock_for_update:
        query = query.with_for_update(nowait=True, of=Task)

    try:
        task = query.one()
    except NoResultFound:
        task = None
    except OperationalError:  # pragma: no cover
        raise HTTPBadRequest("Cannot update task. Record lock for update.")

    if not task or \
       task.cur_state and task.cur_state.state == TaskState.state_removed:
        # FIXME return translated text via JSON
        raise HTTPNotFound("This task doesn't exist.")
    return task


def __ensure_task_locked(task, user):
    locked_task = get_locked_task(task.project_id, user)
    if locked_task != task:
        raise HTTPForbidden("You need to lock the task first.")


@view_config(route_name='task_xhr', renderer='task.mako', http_cache=0)
def task_xhr(request):
    user = __get_user(request, allow_none=True)
    task = __get_task(request)

    locked_task = get_locked_task(task.project_id, user)

    task_id = request.matchdict['task']
    project_id = request.matchdict['project']

    filter = and_(TaskState.task_id == task_id,
                  TaskState.project_id == project_id)
    states = DBSession.query(TaskState).filter(filter) \
        .order_by(TaskState.date).all()
    # remove the first state (task creation with state==ready)
    states.pop(0)

    filter = and_(TaskLock.task_id == task_id,
                  TaskLock.project_id == project_id)
    locks = DBSession.query(TaskLock).filter(filter) \
        .order_by(TaskLock.date).all()
    # remove the first lock (task creation)
    locks.pop(0)

    filter = and_(TaskComment.task_id == task_id,
                  TaskComment.project_id == project_id)
    comments = DBSession.query(TaskComment).filter(filter) \
        .order_by(TaskComment.date).all()

    history = states + locks + comments

    history = sorted(history, key=lambda step: step.date, reverse=True)

    return dict(task=task,
                user=user,
                locked_task=locked_task,
                history=history)


@view_config(route_name='task_empty', renderer='task.empty.mako', http_cache=0)
def task_empty(request):
    user = __get_user(request, allow_none=True)
    project_id = request.matchdict['project']
    locked_task = get_locked_task(project_id, user)
    assigned_tasks = get_assigned_tasks(project_id, user)

    return dict(locked_task=locked_task, project_id=project_id,
                assigned_tasks=assigned_tasks, user=user)

{'fraction_non_alphanumeric': 0.09381390593047034, 'fraction_numerical': 0.0010224948875255625, 'mean_word_length': 3.109768907563025, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2314888', 'n_tokens_mistral': 2461, 'n_tokens_neox': 2390, 'n_words': 531}