Commit 9ae5b679 authored by vipul.v's avatar vipul.v

first

parents
# Default ignored files
/shelf/
/workspace.xml
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="PyPep8NamingInspection" enabled="true" level="WEAK WARNING" enabled_by_default="true">
<option name="ignoredErrors">
<list>
<option value="N801" />
<option value="N803" />
</list>
</option>
</inspection_tool>
</profile>
</component>
\ No newline at end of file
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.11 (weather_report_task_3)" project-jdk-type="Python SDK" />
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/weather_report_task_3.iml" filepath="$PROJECT_DIR$/.idea/weather_report_task_3.iml" />
</modules>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<excludeFolder url="file://$MODULE_DIR$/venv" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
\ No newline at end of file
[SERVICE]
port=8000
host=0.0.0.0
\ No newline at end of file
import uvicorn
from fastapi import FastAPI
from dotenv import load_dotenv
import script
load_dotenv()
from script.config.app_config import Service
from script.service.weather import router
app = FastAPI(title="Weather Report")
app.include_router(router)
if __name__ == "__main__":
uvicorn.run("main:app", host=script.config.app_config.Service.host, port=script.config.app_config.Service.port)
from configparser import SafeConfigParser
config = SafeConfigParser()
config.read('conf/application.conf')
class Service:
port = int(config.getint("SERVICE", "port"))
host = config.get("SERVICE", "host")
class APIEndpoints:
minimum = "/minimum"
maximum = "/maximum"
average = "/average"
daily = "/daily"
weekly = "/weekly"
monthly = "/monthly"
report_base = "/report_base"
wind_speed = "Wind Speed (km/h)"
class NameDoesNotExist(Exception):
pass
\ No newline at end of file
import smtplib
from email.mime.multipart import MIMEMultipart
class SendEmail:
@staticmethod
def send_file(sender_email, receiver, sender_password):
try:
with smtplib.SMTP('smtp.gmail.com', 587) as smtp:
msg = MIMEMultipart()
msg['From'] = sender_email
msg['To'] = receiver
msg['Subject'] = "weather report"
smtp.starttls()
with open("Weather Report_daily.xlsx", "rb") as file:
file_data = file.read()
file_name = file.name
msg.add_attachment(file_data, maintype="weather", subtype="xlsx", filename=file_name)
smtp.login(sender_email, sender_password)
smtp.send_message(msg)
except ValueError:
raise ValueError
except Exception as e:
print(e, "Excel Error Detected")
\ No newline at end of file
import pandas as pd
import openpyxl
class WeatherDataReport:
@staticmethod
def daily_report(df, date):
try:
df[['Date', 'Time']] = df['Formatted Date'].str.split(' ', n=1, expand=True)
filtered_df = df[df['Date'] == date]
data_response = WeatherDataReport.get_data(filtered_df)
new_response = {"date": date, "report": data_response}
condition = "daily"
WeatherDataReport.get_excel(data_response, condition)
return new_response
except ValueError:
raise ValueError
except Exception as e:
print(e, "Error Detected")
@staticmethod
def weekly_report(df, start_date, end_date):
try:
df[["date", "time"]] = df["Formatted Date"].str.split(" ", n=1, expand=True)
df["date"] = pd.to_datetime(df["date"])
start_date = pd.to_datetime(start_date)
end_date = pd.to_datetime(end_date)
filtered_df = df.loc[(df["date"] >= start_date) & (df["date"] <= end_date)]
data_response = WeatherDataReport.get_data(filtered_df)
new_response = {"start date": start_date, "end date": end_date, "data": data_response}
condition = "weekly"
WeatherDataReport.get_excel(data_response, condition)
return new_response
except ValueError:
raise ValueError
except Exception as e:
print(e, "Error Detected")
@staticmethod
def monthly_report(df, year, month):
try:
df[["date", "time"]] = df["Formatted Date"].str.split(" ", n=1, expand=True)
df["date"] = pd.to_datetime(df["date"])
df["date"] = pd.to_datetime(df["date"])
filtered_df = df.loc[(df["date"].dt.year == year) & (df["date"].dt.month == month)]
filtered_df = filtered_df.drop(columns=["time"])
data_response = WeatherDataReport.get_data(filtered_df)
new_response = {"year": year, "month": month, "data": data_response}
condition = "monthly"
WeatherDataReport.get_excel(data_response, condition)
return new_response
except ValueError:
raise ValueError
except Exception as e:
print(e, "Error Detected")
@staticmethod
def get_data(filtered_df):
avg_temp = round(filtered_df['Temperature (C)'].mean(axis=0), 2)
min_temp = round(filtered_df['Temperature (C)'].min(axis=0), 2)
max_temp = round(filtered_df['Temperature (C)'].max(axis=0), 2)
# Apparent Temperature
avg_at = round(filtered_df['Apparent Temperature (C)'].mean(axis=0), 2)
min_at = round(filtered_df['Apparent Temperature (C)'].min(axis=0), 2)
max_at = round(filtered_df['Apparent Temperature (C)'].max(axis=0), 2)
# Humidity
avg_hum = round(filtered_df['Humidity'].mean(axis=0), 2)
min_hum = round(filtered_df['Humidity'].min(axis=0), 2)
max_hum = round(filtered_df['Humidity'].max(axis=0), 2)
# Wind Speed
avg_ws = round(filtered_df['Wind Speed (km/h)'].mean(axis=0), 2)
min_ws = round(filtered_df['Wind Speed (km/h)'].min(axis=0), 2)
max_ws = round(filtered_df['Wind Speed (km/h)'].max(axis=0), 2)
# Wind Bearing
avg_wb = round(filtered_df['Wind Bearing (degrees)'].mean(axis=0), 2)
min_wb = round(filtered_df['Wind Bearing (degrees)'].min(axis=0), 2)
max_wb = round(filtered_df['Wind Bearing (degrees)'].max(axis=0), 2)
# Visibility
avg_vis = round(filtered_df['Visibility (km)'].mean(axis=0), 2)
min_vis = round(filtered_df['Visibility (km)'].min(axis=0), 2)
max_vis = round(filtered_df['Visibility (km)'].max(axis=0), 2)
# Pressure
avg_pre = round(filtered_df['Pressure (millibars)'].mean(axis=0), 2)
min_pre = round(filtered_df['Pressure (millibars)'].min(axis=0), 2)
max_pre = round(filtered_df['Pressure (millibars)'].max(axis=0), 2)
value_return = {
"Average": {"Temperature": avg_temp, "Apparent Temperature": avg_at, "Humidity": avg_hum,
"Wind Speed": avg_ws, "Wind Bearing": avg_wb, "Visibility": avg_vis,
"Pressure": avg_pre},
"Minimum": {"Temperature": min_temp, "Apparent Temperature": min_at, "Humidity": min_hum,
"Wind Speed": min_ws, "Wind Bearing": min_wb, "Visibility": min_vis,
"Pressure": min_pre},
"Maximum": {"Temperature": max_temp, "Apparent Temperature": max_at, "Humidity": max_hum,
"Wind Speed": max_ws, "Wind Bearing": max_wb, "Visibility": max_vis,
"Pressure": max_pre}}
return value_return
@staticmethod
def get_excel(data_response, condition):
try:
df = pd.DataFrame(data_response)
df.to_excel(f"Weather Report_{condition}.xlsx", index=True)
return "Dictionary converted into excel..."
except ValueError:
raise ValueError
except Exception as e:
print(e, "Excel Error Detected")
from typing import Any, Optional
from pydantic import BaseModel
class DefaultResponse(BaseModel):
status: str = "failed"
message: str
data: Optional[Any]
\ No newline at end of file
from typing import Optional, Any
from pydantic import BaseModel
# define a model for Item
class WeatherReport(BaseModel):
minimum: Optional[int]
maximum: Optional[int]
average: Optional[int]
\ No newline at end of file
from fastapi import FastAPI, File, UploadFile, APIRouter
import pandas as pd
from io import StringIO
import logging
from script.constants import APIEndpoints
from script.core.handler.send_email import SendEmail
from script.core.handler.weather import WeatherDataReport
from script.core.schema.response import DefaultResponse
router = APIRouter(prefix=APIEndpoints.report_base)
data = None
@router.post("/upload")
def upload_file(file: UploadFile = File(...)):
contents = file.file.read()
s = str(contents, 'utf-8')
raw_data = StringIO(s)
global data
data = pd.read_csv(raw_data)
raw_data.close()
file.file.close()
return {"filename": file.filename}
@router.get("/daily")
def daily_data(date: str):
try:
global data
op = WeatherDataReport.daily_report(data, date)
return DefaultResponse(message="Successfully found", status="success", data=op)
except ValueError:
return DefaultResponse(message="Due to Value Error")
except Exception as e:
logging.exception(e)
return DefaultResponse(message="Finding failed due to server error")
@router.get("/weekly")
def weekly_data(start_date: str, end_date: str):
try:
global data
op = WeatherDataReport.weekly_report(data, start_date, end_date)
return DefaultResponse(message="Successfully found", status="success", data=op)
except ValueError:
return DefaultResponse(message="Due to Value Error")
except Exception as e:
logging.exception(e)
return DefaultResponse(message="Finding failed due to server error")
@router.get("/monthly")
def monthly_data(year: int, month: int):
try:
global data
op = WeatherDataReport.monthly_report(data, year, month)
return DefaultResponse(message="Successfully found", status="success", data=op)
except ValueError:
return DefaultResponse(message="Due to Value Error")
except Exception as e:
logging.exception(e)
return DefaultResponse(message="Finding failed due to server error")
@router.get("/email")
def get_email(sender: str, receiver: str, password: str):
try:
SendEmail.send_file(sender, receiver, password)
return DefaultResponse(message="Successfully found", status="success")
except ValueError:
return DefaultResponse(message="Due to Value Error")
except Exception as e:
logging.exception(e)
return DefaultResponse(message="Finding failed due to server error")
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment