<commit_before>from datetime import datetime
from dmutils.audit import AuditTypes

from flask import jsonify, abort, request, current_app

from .. import main
from ... import db
from ...models import ArchivedService, Service, Supplier, Framework, AuditEvent

from sqlalchemy import asc
from sqlalchemy.exc import IntegrityError
from sqlalchemy.sql.expression import false
from ...validation import detect_framework_or_400, is_valid_service_id_or_400
from ...utils import url_for, pagination_links, \
    drop_foreign_fields, display_list
from ...service_utils import validate_and_return_service_request, \
    update_and_validate_service, index_service, \
    delete_service_from_index, validate_and_return_updater_request
from sqlalchemy.types import String


@main.route('/')
def index():
    """Entry point for the API, show the resources that are available."""
    return jsonify(links={
        "audits.list": url_for('.list_audits', _external=True),
        "services.list": url_for('.list_services', _external=True),
        "suppliers.list": url_for('.list_suppliers', _external=True)
    }
    ), 200


@main.route('/services', methods=['GET'])
def list_services():
    try:
        page = int(request.args.get('page', 1))
    except ValueError:
        abort(400, "Invalid page argument")

    supplier_id = request.args.get('supplier_id')

    services = Service.query.filter(
        Service.framework.has(Framework.expired == false())
    ).order_by(
        asc(Service.framework_id),
        asc(Service.data['lot'].cast(String).label('data_lot')),
        asc(Service.data['serviceName'].cast(String).label('data_servicename'))
    )

    if request.args.get('status'):
        services = Service.query.filter(
            Service.status.in_(request.values.getlist('status'))
        )

    if supplier_id is not None:
        try:
            supplier_id = int(supplier_id)
        except ValueError:
            abort(400, "Invalid supplier_id: %s" % supplier_id)

        supplier = Supplier.query.filter(Supplier.supplier_id == supplier_id) \
            .all()
        if not supplier:
            abort(404, "supplier_id '%d' not found" % supplier_id)

        services = services.filter(Service.supplier_id == supplier_id)

    services = services.paginate(
        page=page,
        per_page=current_app.config['DM_API_SERVICES_PAGE_SIZE'],
    )

    return jsonify(
        services=[service.serialize() for service in services.items],
        links=pagination_links(
            services,
            '.list_services',
            request.args
        )
    )


@main.route('/archived-services', methods=['GET'])
def list_archived_services_by_service_id():
    """
    Retrieves a list of services from the archived_services table
    for the supplied service_id
    :query_param service_id:
    :return: List[service]
    """

    is_valid_service_id_or_400(request.args.get("service-id", "no service id"))
    service_id = request.args.get("service-id", "no service id")

    try:
        page = int(request.args.get('page', 1))
    except ValueError:
        abort(400, "Invalid page argument")

    services = ArchivedService.query.filter(Service.service_id == service_id)

    services = services.paginate(
        page=page,
        per_page=current_app.config['DM_API_SERVICES_PAGE_SIZE'],
    )

    if request.args and not services.items:
        abort(404)
    return jsonify(
        services=[service.serialize() for service in services.items],
        links=pagination_links(
            services,
            '.list_services',
            request.args
        )
    )


@main.route('/services/<string:service_id>', methods=['POST'])
def update_service(service_id):
    """
        Update a service. Looks service up in DB, and updates the JSON listing.
    """

    is_valid_service_id_or_400(service_id)

    service = Service.query.filter(
        Service.service_id == service_id
    ).first_or_404()

    service_to_archive = ArchivedService.from_service(service)
    update_details = validate_and_return_updater_request()
    update = validate_and_return_service_request(service_id)

    db.session.add(
        update_and_validate_service(
            service,
            update,
            update_details
        )
    )



    try:
        db.session.add(service_to_archive)

        audit = AuditEvent(
            audit_type=AuditTypes.update_service,
            user=update_details['updated_by'],<commit_msg>Fixed pep8 complaints (too many new lines)<commit_after>from datetime import datetime
from dmutils.audit import AuditTypes

from flask import jsonify, abort, request, current_app

from .. import main
from ... import db
from ...models import ArchivedService, Service, Supplier, Framework, AuditEvent

from sqlalchemy import asc
from sqlalchemy.exc import IntegrityError
from sqlalchemy.sql.expression import false
from ...validation import detect_framework_or_400, is_valid_service_id_or_400
from ...utils import url_for, pagination_links, \
    drop_foreign_fields, display_list
from ...service_utils import validate_and_return_service_request, \
    update_and_validate_service, index_service, \
    delete_service_from_index, validate_and_return_updater_request
from sqlalchemy.types import String


@main.route('/')
def index():
    """Entry point for the API, show the resources that are available."""
    return jsonify(links={
        "audits.list": url_for('.list_audits', _external=True),
        "services.list": url_for('.list_services', _external=True),
        "suppliers.list": url_for('.list_suppliers', _external=True)
    }
    ), 200


@main.route('/services', methods=['GET'])
def list_services():
    try:
        page = int(request.args.get('page', 1))
    except ValueError:
        abort(400, "Invalid page argument")

    supplier_id = request.args.get('supplier_id')

    services = Service.query.filter(
        Service.framework.has(Framework.expired == false())
    ).order_by(
        asc(Service.framework_id),
        asc(Service.data['lot'].cast(String).label('data_lot')),
        asc(Service.data['serviceName'].cast(String).label('data_servicename'))
    )

    if request.args.get('status'):
        services = Service.query.filter(
            Service.status.in_(request.values.getlist('status'))
        )

    if supplier_id is not None:
        try:
            supplier_id = int(supplier_id)
        except ValueError:
            abort(400, "Invalid supplier_id: %s" % supplier_id)

        supplier = Supplier.query.filter(Supplier.supplier_id == supplier_id) \
            .all()
        if not supplier:
            abort(404, "supplier_id '%d' not found" % supplier_id)

        services = services.filter(Service.supplier_id == supplier_id)

    services = services.paginate(
        page=page,
        per_page=current_app.config['DM_API_SERVICES_PAGE_SIZE'],
    )

    return jsonify(
        services=[service.serialize() for service in services.items],
        links=pagination_links(
            services,
            '.list_services',
            request.args
        )
    )


@main.route('/archived-services', methods=['GET'])
def list_archived_services_by_service_id():
    """
    Retrieves a list of services from the archived_services table
    for the supplied service_id
    :query_param service_id:
    :return: List[service]
    """

    is_valid_service_id_or_400(request.args.get("service-id", "no service id"))
    service_id = request.args.get("service-id", "no service id")

    try:
        page = int(request.args.get('page', 1))
    except ValueError:
        abort(400, "Invalid page argument")

    services = ArchivedService.query.filter(Service.service_id == service_id)

    services = services.paginate(
        page=page,
        per_page=current_app.config['DM_API_SERVICES_PAGE_SIZE'],
    )

    if request.args and not services.items:
        abort(404)
    return jsonify(
        services=[service.serialize() for service in services.items],
        links=pagination_links(
            services,
            '.list_services',
            request.args
        )
    )


@main.route('/services/<string:service_id>', methods=['POST'])
def update_service(service_id):
    """
        Update a service. Looks service up in DB, and updates the JSON listing.
    """

    is_valid_service_id_or_400(service_id)

    service = Service.query.filter(
        Service.service_id == service_id
    ).first_or_404()

    service_to_archive = ArchivedService.from_service(service)
    update_details = validate_and_return_updater_request()
    update = validate_and_return_service_request(service_id)

    db.session.add(
        update_and_validate_service(
            service,
            update,
            update_details
        )
    )
    try:
        db.session.add(service_to_archive)

        audit = AuditEvent(
            audit_type=AuditTypes.update_service,
            user=update_details['updated_by'],
{'fraction_non_alphanumeric': 0.10766138038865311, 'fraction_numerical': 0.007929417020326112, 'mean_word_length': 3.0120967741935485, 'pattern_counts': {'":': 6, '<': 5, '<?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': '4594643', 'n_tokens_mistral': 2700, 'n_tokens_neox': 2615, 'n_words': 545}