<commit_before>from aiohttp import web
from aiohttp.web_urldispatcher import UrlDispatcher

from .session import CheckCalibrationSession
from .models import CalibrationSessionStatus

ALLOWED_SESSIONS = ['check']


def _format_status(
        session: 'CheckCalibrationSession',
        router: UrlDispatcher) -> 'CalibrationSessionStatus':
    pips = session.pipettes
    # pydantic restricts dictionary keys that can be evaluated. Since
    # the session pipettes dictionary has a UUID as a key, we must first
    # convert the UUID to a hex string.
    instruments = {token.hex: data for token, data in pips.items() if token}
    current = session.state_machine.current_state.name
    next = session.state_machine.next_state
    if next:
        path = router.get(next.name, '')
        if path:
            url = path.url_for()
        else:
            url = path
        links = {'links': {next.name: url}}
    else:
        links = {'links': {}}
    status = CalibrationSessionStatus(
        instruments=instruments,
        currentStep=current,
        nextSteps=links)
    return status


async def get_session(request):
    """
    GET /calibration/check/session

    If a session exists, this endpoint will return the current status.

    Otherwise, this endpoint will return a 404 with links to the post request.
    """
    session_type = request.match_info['type']
    session_storage = request.app['com.opentrons.session_manager']
    current_session = session_storage.sessions.get(session_type)
    if current_session:
        response = _format_status(current_session, request.app.router)
        return web.json_response(text=response.json(), status=200)
    else:
        response = {
            "message": f"No {session_type} session exists. Please create one.",
            "links": {"createSession": f"/calibration/{session_type}/session"}}
        return web.json_response(response, status=404)


async def create_session(request):
    """
    POST /calibration/check/session

    If a session exists, this endpoint will return the current status.

    The status message is in the shape of:
    :py:class:`.models.CalibrationSessionStatus`
    """
    session_type = request.match_info['type']
    if session_type not in ALLOWED_SESSIONS:
        message = f'Session of type {session_type} is not supported'
        return web.json_response(message, status=403)

    session_storage = request.app['com.opentrons.session_manager']
    current_session = session_storage.sessions.get(session_type)
    if not current_session:
        hardware = request.app['com.opentrons.hardware']
        await hardware.cache_instruments()
        new_session = CheckCalibrationSession(hardware)
        session_storage.sessions[session_type] = new_session

        response = _format_status(new_session, request.app.router)
        return web.json_response(text=response.json(), status=201)
    else:
        response = {
            "message": f"A {session_type} session exists."
                       "Please delete to proceed.",
            "links": {"deleteSession": f"/calibration/{session_type}/session"}}
        return web.json_response(response, status=409)


async def delete_session(request):
    """
    DELETE /calibration/check/session

    Endpoint to delete a session if it exists.
    """
    session_type = request.match_info['type']
    session_storage = request.app['com.opentrons.session_manager']
    current_session = session_storage.sessions.get(session_type)
    if not current_session:
        response = {'message': f'A {session_type} session does not exist.'}
        return web.json_response(response, status=404)
    else:
        await current_session.hardware.home()
        del session_storage.sessions[session_type]
        return web.json_response(status=200)<commit_msg>refactor(api): Add success message to delete endpoint (#5299)<commit_after>from aiohttp import web
from aiohttp.web_urldispatcher import UrlDispatcher

from .session import CheckCalibrationSession
from .models import CalibrationSessionStatus

ALLOWED_SESSIONS = ['check']


def _format_status(
        session: 'CheckCalibrationSession',
        router: UrlDispatcher) -> 'CalibrationSessionStatus':
    pips = session.pipettes
    # pydantic restricts dictionary keys that can be evaluated. Since
    # the session pipettes dictionary has a UUID as a key, we must first
    # convert the UUID to a hex string.
    instruments = {token.hex: data for token, data in pips.items() if token}
    current = session.state_machine.current_state.name
    next = session.state_machine.next_state
    if next:
        path = router.get(next.name, '')
        if path:
            url = path.url_for()
        else:
            url = path
        links = {'links': {next.name: url}}
    else:
        links = {'links': {}}
    status = CalibrationSessionStatus(
        instruments=instruments,
        currentStep=current,
        nextSteps=links)
    return status


async def get_session(request):
    """
    GET /calibration/check/session

    If a session exists, this endpoint will return the current status.

    Otherwise, this endpoint will return a 404 with links to the post request.
    """
    session_type = request.match_info['type']
    session_storage = request.app['com.opentrons.session_manager']
    current_session = session_storage.sessions.get(session_type)
    if current_session:
        response = _format_status(current_session, request.app.router)
        return web.json_response(text=response.json(), status=200)
    else:
        response = {
            "message": f"No {session_type} session exists. Please create one.",
            "links": {"createSession": f"/calibration/{session_type}/session"}}
        return web.json_response(response, status=404)


async def create_session(request):
    """
    POST /calibration/check/session

    If a session exists, this endpoint will return the current status.

    The status message is in the shape of:
    :py:class:`.models.CalibrationSessionStatus`
    """
    session_type = request.match_info['type']
    if session_type not in ALLOWED_SESSIONS:
        message = f"Session of type {session_type} is not supported."
        return web.json_response(message, status=403)

    session_storage = request.app['com.opentrons.session_manager']
    current_session = session_storage.sessions.get(session_type)
    if not current_session:
        hardware = request.app['com.opentrons.hardware']
        await hardware.cache_instruments()
        new_session = CheckCalibrationSession(hardware)
        session_storage.sessions[session_type] = new_session

        response = _format_status(new_session, request.app.router)
        return web.json_response(text=response.json(), status=201)
    else:
        response = {
            "message": f"A {session_type} session exists."
                       "Please delete to proceed.",
            "links": {"deleteSession": f"/calibration/{session_type}/session"}}
        return web.json_response(response, status=409)


async def delete_session(request):
    """
    DELETE /calibration/check/session

    Endpoint to delete a session if it exists.
    """
    session_type = request.match_info['type']
    session_storage = request.app['com.opentrons.session_manager']
    current_session = session_storage.sessions.get(session_type)
    if not current_session:
        response = {"message": f"A {session_type} session does not exist."}
        return web.json_response(response, status=404)
    else:
        await current_session.hardware.home()
        del session_storage.sessions[session_type]
        response = {'message': f"Successfully deleted {session_type} session."}
        return web.json_response(response, status=200)
{'fraction_non_alphanumeric': 0.09458242182473298, 'fraction_numerical': 0.006691545489640973, 'mean_word_length': 3.2010810810810812, 'pattern_counts': {'":': 13, '<': 3, '<?xml version=': 0, '>': 5, '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': '1885424', 'n_tokens_mistral': 2204, 'n_tokens_neox': 2134, 'n_words': 563}