|
| 1 | +import json |
| 2 | +from fastapi import Response |
| 3 | +from datetime import datetime, timedelta, date |
| 4 | +from fastapi import APIRouter |
| 5 | +from ...commons.ocm import getData |
| 6 | +from ...commons.example_responses import ocp_200_response, response_422 |
| 7 | +from fastapi.param_functions import Query |
| 8 | + |
| 9 | +router = APIRouter() |
| 10 | + |
| 11 | + |
| 12 | +@router.get('/api/v1/ocm/jobs', |
| 13 | + summary="Returns a job list", |
| 14 | + description="Returns a list of jobs in the specified dates. \ |
| 15 | + If not dates are provided the API will default the values. \ |
| 16 | + `startDate`: will be set to the day of the request minus 5 days.\ |
| 17 | + `endDate`: will be set to the day of the request.", |
| 18 | + responses={ |
| 19 | + 200: ocp_200_response(), |
| 20 | + 422: response_422(), |
| 21 | + },) |
| 22 | +async def jobs(start_date: date = Query(None, description="Start date for searching jobs, format: 'YYYY-MM-DD'", examples=["2020-11-10"]), |
| 23 | + end_date: date = Query(None, description="End date for searching jobs, format: 'YYYY-MM-DD'", examples=["2020-11-15"]), |
| 24 | + pretty: bool = Query(False, description="Output contet in pretty format.")): |
| 25 | + if start_date is None: |
| 26 | + start_date = datetime.utcnow().date() |
| 27 | + start_date = start_date - timedelta(days=5) |
| 28 | + |
| 29 | + if end_date is None: |
| 30 | + end_date = datetime.utcnow().date() |
| 31 | + |
| 32 | + if start_date > end_date: |
| 33 | + return Response(content=json.dumps({'error': "invalid date format, start_date must be less than end_date"}), status_code=422) |
| 34 | + |
| 35 | + results = await getData(start_date, end_date, 'ocm.elasticsearch') |
| 36 | + |
| 37 | + if len(results) >= 1: |
| 38 | + response = { |
| 39 | + 'startDate': start_date.__str__(), |
| 40 | + 'endDate': end_date.__str__(), |
| 41 | + 'results': results.to_dict('records') |
| 42 | + } |
| 43 | + else: |
| 44 | + response = { |
| 45 | + 'startDate': start_date.__str__(), |
| 46 | + 'endDate': end_date.__str__(), |
| 47 | + 'results': [] |
| 48 | + } |
| 49 | + |
| 50 | + if pretty: |
| 51 | + json_str = json.dumps(response, indent=4) |
| 52 | + return Response(content=json_str, media_type='application/json') |
| 53 | + |
| 54 | + jsonstring = json.dumps(response) |
| 55 | + return jsonstring |
0 commit comments