Skip to content

Commit

Permalink
updated fastapi
Browse files Browse the repository at this point in the history
  • Loading branch information
poojithakonduparti authored Mar 3, 2023
1 parent f5527f4 commit dc7b4c1
Show file tree
Hide file tree
Showing 6 changed files with 201 additions and 7 deletions.
10 changes: 9 additions & 1 deletion fastapi-app/requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,15 @@ certifi==2022.12.7
cffi==1.15.1
charset-normalizer==3.0.1
click==8.1.3
colorama==0.4.6
commonmark==0.9.1
cryptography==39.0.1
dnspython==2.3.0
ecdsa==0.18.0
email-validator==1.3.1
exceptiongroup==1.1.0
fastapi==0.92.0
functions==0.7.0
greenlet==2.0.2
gunicorn==20.1.0
h11==0.14.0
Expand All @@ -35,6 +38,7 @@ py==1.11.0
pyasn1==0.4.8
pycparser==2.21
pydantic==1.10.5
Pygments==2.14.0
pytest==7.2.1
pytest-html==3.2.0
pytest-metadata==2.0.4
Expand All @@ -46,15 +50,19 @@ pytz==2022.7.1
PyYAML==6.0
requests==2.28.2
rfc3986==1.5.0
rich==12.6.0
rsa==4.9
s3transfer==0.6.0
schemas==0.7.1
shellingham==1.5.0.post1
six==1.16.0
sniffio==1.3.0
SQLAlchemy==2.0.4
sqlite-s3-query==0.0.74
starlette==0.25.0
tomli==2.0.1
typing-extensions==4.5.0
typer==0.7.0
typing_extensions==4.5.0
ujson==5.7.0
urllib3==1.26.14
uvicorn==0.20.0
Expand Down
18 changes: 17 additions & 1 deletion fastapi-app/schema.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,27 @@
from typing import Optional
from pydantic import BaseModel
from unicodedata import name
from click import confirmation_option, password_option
from enum import Enum

class User(BaseModel): #class to create or access user
name: str
username : str
password: str
plan : str #added plan assignment 3
user_type : str

class UpdateUserPassword(BaseModel):
password : str

class Config():
orm_mode = True

class ShowUser(BaseModel): #class to show only the name of the user as a response
name: str

class Config():
orm_mode = True #allows app to take ORM object and translate into responses
orm_mode = True #allows app to take ORM object and translate into responses

class Login(BaseModel): #class for login
username: str
Expand All @@ -22,3 +33,8 @@ class Token(BaseModel): #token class with access token and token type

class TokenData(BaseModel):
username: Optional[str] = None

class Plan(str, Enum): #class to show plans as options in CLI
free = 'free'
gold = 'gold'
platinum = 'platinum'
Binary file modified fastapi-app/sql_scraped_database.db
Binary file not shown.
170 changes: 170 additions & 0 deletions fastapi-app/typer_main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
import typer
import requests
import json
from schema import Plan
from wsgiref import headers


#API_URL = "http://127.0.0.1:8080"
API_URL = "http://34.73.90.193:8002"

app = typer.Typer()
users_app = typer.Typer()
app.add_typer(users_app, name="users")
session =requests.session() #creating session
headers = session.headers #declaring headers as global variable

@users_app.command("create")
def create_user(name: str = typer.Option(..., prompt= "Enter your name"), username: str = typer.Option(..., prompt= "Enter your username"), password : str = typer.Option(...,prompt = "Please enter your password",confirmation_prompt= True), plan : Plan = typer.Option(..., prompt = "Please choose a plan"), user_type : str = typer.Option(["user, admin"], prompt="Are you a user or admin?") ):
'''
Create an account by entering name, username, password and choose a plan
'''
payload = {'name': name, 'username': username, 'password': password, 'plan': plan, 'user_type' : user_type}
response = requests.request("POST", f"{API_URL}/user/create", json=payload) #referencing fastapi to create a user in the database
print(response)
print(f"Creating user: {username} in plan: {plan}")

@users_app.command("login")
def login(username : str = typer.Option(...,prompt="Enter Username"), password: str = typer.Option(..., prompt="Enter Password")):
'''
Login using username and password to be granted an access token in order to perform authorized tasks
'''
global headers
payload = {'username' : username, 'password' : password}
response = requests.request("POST",f"{API_URL}/login",data=payload)
json_data = json.loads(response.text)
#print(json_data['access_token'])
if response.status_code ==200:
access_token = json_data['access_token']
#headers = {'User-Agent': 'python-requests/2.26.0', 'Accept-Encoding': 'gzip, deflate, br', 'Accept': '*/*', 'Connection': 'keep-alive'}
#print('Before adding Authorization:', headers)
headers['Authorization'] = f"Bearer {access_token}" #always throws error here!
#print('After adding Authorization:', headers)
session.headers.update({'Authorization': 'Bearer ' + access_token})
print(session.headers)
#print("working")
else:
print("Incorrect username or password.")

@users_app.command("changepassword")
def change_password(username: str = typer.Option(...,prompt = "Enter username"),new_password: str = typer.Option(...,prompt="Enter new password", confirmation_prompt=True) ):
'''
Change password by entering your username and new password
'''
payload = {'password' : new_password}
response = requests.request("PATCH", f"{API_URL}/user/update?username={username}", json=payload, headers=headers) #referencing fastapi to change a user's password in the database
if response.status_code == 200:
print("Password updated successfully!")
else:
print(response)

@users_app.command("download")
def download_by_filename(username : str = typer.Option(...,prompt="Enter Username to login"), password: str = typer.Option(..., prompt="Enter Password"), dataset : str = typer.Option(...,prompt="Choose one- GOES18 or NEXRAD")):
'''
Download files from goes18 or nexrad by entering the filename
'''

payload = {'username' : username, 'password' : password}
login_resp = requests.request("POST",f"{API_URL}/login",data=payload)
if(login_resp.status_code==200):
json_data = json.loads(login_resp.text)
json_data['access_token']
access_token = json_data['access_token']
global headers
headers['Authorization'] = f"Bearer {access_token}"
if dataset == "GOES18":
file_name=input("Enter file name: ")
response = requests.request("POST", f"{API_URL}/fetchfile/goes18?file_name={file_name}", headers=headers) #api request to get file from nexrad
if response.status_code == 200:
json_data = json.loads(response.text)
final_url = json_data #store reponse data
print("Found URL of the file available on GOES18 bucket!") #display success message
print("URL to file: ", final_url)
return
else:
print("Incorrect file name given, please change!")
return
elif dataset == "NEXRAD":
file_name=input("Enter file name: ")
response = requests.request("POST", f"{API_URL}/fetchfile/nexrad?file_name={file_name}", headers=headers) #api request to get file from nexrad
if response.status_code == 200:
json_data = json.loads(response.text)
final_url = json_data #store reponse data
print("Found URL of the file available on NEXRAD bucket!") #display success message
print("URL to file: ", final_url)
return
else:
print("Incorrect file name given, please change!")
return
else:
print("Please enter one of the 2 options above")
return
else:
print("Incorrect username or password.")
return

payload = {file_name : file_name}
if dataset == "goes18":
response = requests.request("GET", f"{API_URL}/fetchfile/goes18",json=payload) #api request to get file from goes18
elif dataset == "nexrad":
response = requests.request("POST", f"{API_URL}/fetchfile/nexrad?file_name={file_name}", headers=header) #api request to get file from nexrad
print(response)
print("Download link!")

@users_app.command("fetch")
def list_files(username : str = typer.Option(...,prompt="Enter Username to login"), password: str = typer.Option(..., prompt="Enter Password"), dataset : str = typer.Option(...,prompt="Choose one- GOES18 or NEXRAD")):

'''
List all files in a bucket.
The format for choosing for GOES18 is : GOES18 Product Year Day Hour
The format for choosing for NEXRAD is : NEXRAD Year Month Day Ground Station
'''

payload = {'username' : username, 'password' : password}
login_resp = requests.request("POST",f"{API_URL}/login",data=payload)
if(login_resp.status_code==200):
json_data = json.loads(login_resp.text)
json_data['access_token']
access_token = json_data['access_token']
global headers
headers['Authorization'] = f"Bearer {access_token}"
if dataset == "GOES18":
year=input("Enter year: ")
day=input("Enter day: ")
hour=input("Enter hour: ")
print("Product is ABI-L1b-RadC by default")
product = "ABI-L1b-RadC"
response = requests.request("GET",f"{API_URL}/s3/goes18?year={year}&day={day}&hour={hour}&product={product}", headers=headers)
if response.status_code == 200:
json_data = json.loads(response.text)
files_in_selected_hour = json_data #store response data
print("List of files loading...")
print(files_in_selected_hour)
return
else:
print("Incorrect input given, please change the inputs!")
return
elif dataset == "NEXRAD":
year=input("Enter year: ")
month=input("Enter month: ")
day=input("Enter day: ")
ground_station=input("Enter ground station: ")
response = requests.request("GET",f"{API_URL}/s3/nexrad?year={year}&month={month}&day={day}&ground_station={ground_station}", headers=headers)
if response.status_code == 200:
json_data = json.loads(response.text)
files_in_selected_hour = json_data #store response data
print("List of files loading...")
print(files_in_selected_hour)
return
else:
print("Incorrect input given, please change the inputs!")
return
else:
print("Please enter one of the 2 options above")
return
else:
print("Incorrect username or password.")
return

if __name__ == "__main__":
app()
Binary file modified fastapi-app/user_data.db
Binary file not shown.
10 changes: 5 additions & 5 deletions fastapi-app/userdb.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@
from sqlalchemy.orm import declarative_base
from sqlalchemy.orm import sessionmaker
import os

dir_path = os.path.dirname(os.path.realpath(__file__))
f = open(os.path.join(dir_path, 'user_data.db'), 'w')
f.close()
#commenting these lines out because it creates and erases db contents everytime file is run
#dir_path = os.path.dirname(os.path.realpath(__file__))
#f = open(os.path.join(dir_path, 'user_data.db'), 'w')
#f.close()


user_db_url = 'sqlite:///./user_data.db' #defining database url
Expand All @@ -30,4 +30,4 @@ def get_db():
try:
yield db #return session object using yield
finally:
db.close
db.close

0 comments on commit dc7b4c1

Please sign in to comment.