-
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathmain.py
More file actions
60 lines (46 loc) · 1.47 KB
/
main.py
File metadata and controls
60 lines (46 loc) · 1.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
from fastapi import FastAPI, Request, Response
from fastapi.responses import JSONResponse
from pydantic import BaseModel
from datetime import datetime
# import logging
# import json_logging
import httpx
import sys
import traceback
from exceptions import UnicornException
from settings import Settings
from log import init_log
from cors import init_cors
from instrumentator import init_instrumentator
from config import Config
from models import CountryEntity
import geoip2.database
import geoip2
reader = geoip2.database.Reader('./mmdb/GeoLite2-Country.mmdb')
app = FastAPI()
settings = Settings()
try:
conf = Config(settings.CONFIG_PATH)
init_log(app, conf.section("log")["path"])
except:
traceback.print_exc(file=sys.stderr)
pass
init_cors(app)
init_instrumentator(app)
client = httpx.AsyncClient()
@app.exception_handler(UnicornException)
async def unicorn_exception_handler(request: Request, exc: UnicornException):
return JSONResponse(
status_code=exc.status,
content={"code": exc.code, "message": exc.message},
)
@app.get("/api/v1/geoip/{ip}", response_model=CountryEntity)
async def read_item(ip: str):
try:
resp = reader.country(ip)
return {"ip": ip, "country": resp.country.iso_code}
except geoip2.errors.AddressNotFoundError as e:
return {"ip": ip, "country": ""}
except Exception as e:
traceback.print_exc(file=sys.stderr)
raise UnicornException(status=400, code=-20000, message=str(e))