def api_list_data(trip_name, date_string, place_name, sample_type): is_csv = False try: data_format = request.args.get("fmt") if data_format == "csv": is_csv = True except KeyError: pass data = psql_query("SELECT * FROM field_data WHERE dataset=%s AND date(tstamp)=(DATE %s) AND site=%s AND sensor=%s", (trip_name, date_string, place_name, sample_type)) if is_csv: cursor = db_conn.cursor() cursor.execute("SELECT * FROM field_data LIMIT 0") column_names = [desc[0] for desc in cursor.description] # In case the requested csv is huge, return it bit by bit def stream_csv(): yield ",".join(column_names) + "\n" for row in data: print(row) yield ",".join([str(item) if item is not None else "" for item in row]) + "\n" csv_response = Response(stream_csv(), mimetype="text/csv") # Set the file's download name csv_response.headers["Content-Disposition"] = 'inline; filename="data.csv"' return csv_response else: return jsonify(dataset=trip_name, date=date_string, place=place_name, sample_type=sample_type, data=data)
def psql_query(query, args=None, include_columns=False): cursor = db_conn.cursor() if args is not None: cursor.execute(query, args) else: cursor.execute(query) if include_columns: return ([desc[0] for desc in cursor.description], cursor.fetchall()) else: return cursor.fetchall()
def api_list_data(trip_name, date_string, place_name, sample_type): is_csv = False try: data_format = request.args.get("fmt") if data_format == "csv": is_csv = True except KeyError: pass data = psql_query( "SELECT * FROM field_data WHERE dataset=%s AND date(tstamp)=(DATE %s) AND site=%s AND sensor=%s", (trip_name, date_string, place_name, sample_type)) if is_csv: cursor = db_conn.cursor() cursor.execute("SELECT * FROM field_data LIMIT 0") column_names = [desc[0] for desc in cursor.description] # In case the requested csv is huge, return it bit by bit def stream_csv(): yield ",".join(column_names) + "\n" for row in data: print(row) yield ",".join( [str(item) if item is not None else "" for item in row]) + "\n" csv_response = Response(stream_csv(), mimetype="text/csv") # Set the file's download name csv_response.headers[ "Content-Disposition"] = 'inline; filename="data.csv"' return csv_response else: return jsonify(dataset=trip_name, date=date_string, place=place_name, sample_type=sample_type, data=data)