Spaces:
Sleeping
Sleeping
chen commited on
Update app.py
Browse files14 unmodified lines151617181920216 unmodified lines282930313233348 unmodified lines4344454647484950515253545556575859606162636465666768697071727374757677787980811 unmodified line838485868788899091929394959614 unmodified lines)# Initialize the IRIS FDSN client# This is placed in a global scope to be reused across requeststry:client = Client("IRIS")logging.info("Successfully initialized IRIS FDSN client.")6 unmodified lines"""A simple 'Hello World' endpoint."""return {"Hello": "World!", "message": "Go to /earthquakes to fetch data, or /docs for the API documentation."}@app.get("/earthquakes")async def get_earthquake_catalog():8 unmodified lines)try:# Define the query parametersstarttime = UTCDateTime("2015-01-05")endtime = UTCDateTime("2016-03-05")min_magnitude = 5.0logging.info(f"Fetching events from {starttime} to {endtime} with min magnitude {min_magnitude}.")# Fetch the earthquake catalog from the IRIS web servicecatalog = client.get_events(starttime=starttime,endtime=endtime,minmagnitude=min_magnitude,)logging.info(f"Found {len(catalog)} events.")# Process the catalog into a more friendly JSON formatearthquake_list = []for event in catalog:# Ensure the event has a preferred origin and magnitude to avoid errorsif not event.preferred_origin() or not event.preferred_magnitude():continueorigin = event.preferred_origin()magnitude = event.preferred_magnitude()# Extract place descriptionplace = "N/A"if event.descriptions:place = event.descriptions[0].textearthquake_list.append({"time": origin.time.isoformat(),"latitude": origin.latitude,"longitude": origin.longitude,1 unmodified line"magnitude": magnitude.mag,"magnitude_type": magnitude.magnitude_type,"place": place,})return JSONResponse(content={"earthquakes": earthquake_list})except Exception as e:logging.error(f"An error occurred while fetching data from IRIS FDSN: {e}")raise HTTPException(status_code=500, # Internal Server Errordetail=f"An internal error occurred while fetching data from the external service: {e}",)14 unmodified lines1516171819206 unmodified lines272829303132338 unmodified lines4243444546474849505152535455565758596061626364656667686970717273747576771 unmodified line7980818283848586878889909192939495969714 unmodified lines)# Initialize the IRIS FDSN clienttry:client = Client("IRIS")logging.info("Successfully initialized IRIS FDSN client.")6 unmodified lines"""A simple 'Hello World' endpoint."""return {"Hello": "World!", "message": "Go to /earthquakes to fetch data, or /docs for the API documentation. Dayi"}@app.get("/earthquakes")async def get_earthquake_catalog():8 unmodified lines)try:starttime = UTCDateTime("2015-01-05")endtime = UTCDateTime("2016-03-05")min_magnitude = 5.0logging.info(f"Fetching events from {starttime} to {endtime} with min magnitude {min_magnitude}.")catalog = client.get_events(starttime=starttime,endtime=endtime,minmagnitude=min_magnitude,)logging.info(f"Found {len(catalog)} events. Now processing.")earthquake_list = []# --- Key Change Start ---# Loop through each event and process it individually to prevent one bad event from crashing the app.for event in catalog:try:# Ensure the event has a preferred origin and magnitudeif not event.preferred_origin() or not event.preferred_magnitude():continue # Skip to the next event if essential data is missingorigin = event.preferred_origin()magnitude = event.preferred_magnitude()# Safely extract the place descriptionplace = "N/A"if event.descriptions: # Check if the descriptions list exists and is not emptyplace = event.descriptions[0].textearthquake_list.append({"time": origin.time.isoformat(),"latitude": origin.latitude,"longitude": origin.longitude,1 unmodified line"magnitude": magnitude.mag,"magnitude_type": magnitude.magnitude_type,"place": place,})except Exception as e:# If a single event fails, log it and continue with the others.logging.warning(f"Skipping one event due to a processing error: {e}")continue# --- Key Change End ---logging.info(f"Successfully processed {len(earthquake_list)} events.")return JSONResponse(content={"earthquakes": earthquake_list})except Exception as e:logging.error(f"A major error occurred during the request: {e}")raise HTTPException(status_code=500, # Internal Server Errordetail=f"An internal error occurred: {e}",)
app.py+27-26