Merge pull request #23 from bt3gl-labs/add-fastapi-location

Add Location API project on FastAPI deployed in Vercel
This commit is contained in:
bt3gl 2022-03-26 00:14:11 -07:00 committed by GitHub
commit ee6102339b
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
12 changed files with 134 additions and 0 deletions

View file

@ -1,6 +1,11 @@
# ✨🐍 [Scratch Space] Python: small projects and boilerplates
### APIs
* [FastAPI Location API deployed in Vercel](github.com/bt3gl-labs/Scratch-Space-Python/tree/master/fastapi-location-api)
### Boilerplates
* [CLI with Click](https://github.com/bt3gl-labs/Scratch-Space-Python/tree/master/boilerplates-click)

4
fastapi-location-app/.gitignore vendored Normal file
View file

@ -0,0 +1,4 @@
__pycache__
.vercel
venv
.env

View file

@ -0,0 +1,5 @@
requirements-dev.txt
venv
main.py
README.md
.gitignore

View file

@ -0,0 +1,34 @@
# Location API 🗺
Location API deployed in Vercel and built with FastAPI.
## Endpoint /location
Input data:
```
{"city": "berlin"}
```
Response:
```
{"lat":52.5186925,"lon":13.3996024,"tzone":1}
```
### Installing
```
virtualenv -p python3.9 venv
source venv/bin/activate
pipenv install
```
### Running
```
python3 main.py
```

View file

View file

@ -0,0 +1,14 @@
from .routes import router as LocationRouter
from fastapi import FastAPI
app = FastAPI()
@app.get("/", tags=["Root"])
async def read_root() -> dict:
return {
"message": "$CHOICES Timezone API ⏳✨. Try /docs to learn about this API"
}
app.include_router(LocationRouter, prefix="/tzone")

View file

@ -0,0 +1,35 @@
import pytz
import datetime
from geopy.geocoders import Nominatim
from timezonefinder import TimezoneFinder
def _find_timezone(lat, lon) -> int:
obj = TimezoneFinder()
tzone = obj.timezone_at(lng=lon, lat=lat)
timezone = datetime.datetime.now(pytz.timezone(tzone)).strftime('%z')
try:
timezone = int(timezone[:-2])
except:
print('Error formatting timezone {}'.format(timezone))
return timezone
def get_location(data) -> dict:
try:
city = data['city']
except:
print('Data is ill-formatted: {}'.format(data))
geolocator = Nominatim(user_agent="$choices")
location = geolocator.geocode(city)
data = {
'lat': location.latitude,
'lon': location.longitude,
'tzone': _find_timezone(location.latitude, location.longitude)
}
return data

View file

@ -0,0 +1,17 @@
from pydantic import BaseModel
from fastapi import APIRouter
from .methods import get_location
router = APIRouter()
class City(BaseModel):
city: str
@router.post("/")
def search_city(data: City) -> dict:
return get_location(data.dict())

View file

@ -0,0 +1,4 @@
import uvicorn
if __name__ == "__main__":
uvicorn.run("api.api:app", host="0.0.0.0", port=8000, reload=True)

View file

@ -0,0 +1 @@
uvicorn

View file

@ -0,0 +1,4 @@
timezonefinder==5.2.0
pytz==2022.1
pydantic
fastapi

View file

@ -0,0 +1,11 @@
{
"routes": [
{"src": "/(.*)", "dest": "api/api.py"}
],
"functions": {
"api/api.py": {
"memory": 3008,
"maxDuration": 30
}
}
}