输入为空时获取所有数据 API

Get all data API when inputs are empty

我创建了我的第一个 API,我可以在其中从 Bigquery 中的 table 获取数据。 我可以根据下面的 2 个输入获取我需要的所有数据,但我也试图在输入为空时获取整个 table,这是我做不到的。 感谢您的帮助

@app.route("/tracking", methods=['GET'])
def tracking_data():

    haulier_id_tracking = request.args.get('haulier_id_tracking')
    month_tracking = request.args.get('month_tracking')



    query_job = bq_client.query("""
            WITH t AS (
                SELECT *
                FROM mart.monthly_vehicle_stats
                WHERE dt_fr_month = '{month_tracking}-01' AND (haulier_id_tracking = '{haulier_id_tracking}')
            
            
            SELECT TO_JSON_STRING(STRUCT(ARRAY_AGG(STRUCT(dt_fr_month, haulier_id_tracking, vehicle_id , nb_days_tracked, 
            data_access, date_first_camp, invoiced)) AS data)) json
            FROM t
        """.format(month_tracking = month_tracking, haulier_id_tracking = haulier_id_tracking))

    for row in query_job:

        return json.loads(row["json"])

当输入为空时,你可以remove the where clause像这样:

@app.route("/tracking", methods=['GET'])
def tracking_data():

    haulier_id_tracking = request.args.get('haulier_id_tracking')
    month_tracking = request.args.get('month_tracking')

    where_clause = ''
    if haulier_id_tracking != '' and month_tracking != '':
        where_clause = f"WHERE dt_fr_month = '{month_tracking}-01' AND (haulier_id_tracking = '{haulier_id_tracking}'"



    query_job = bq_client.query(f"""
            WITH t AS (
                SELECT * FROM mart.monthly_vehicle_stats {where_clause})


            SELECT TO_JSON_STRING(STRUCT(ARRAY_AGG(STRUCT(dt_fr_month, haulier_id_tracking, vehicle_id , nb_days_tracked,
            data_access, date_first_camp, invoiced)) AS data)) json
            FROM t
        """)

    for row in query_job:
        return json.loads(row["json"])