파이썬 Geolocation
Server Side/Python2026. 7. 9. 22:54
import time
import hmac
import hashlib
import base64
import requests
def make_signature(secret_key, method, base_string, timestamp, access_key):
message = f"{method} {base_string}\n{timestamp}\n{access_key}"
signature = base64.b64encode(
hmac.new(
secret_key.encode("utf-8"),
message.encode("utf-8"),
hashlib.sha256
).digest()
).decode("utf-8")
return signature
def get_geolocation(ip):
host_name_url = "https://geolocation.apigw.ntruss.com"
request_url = "/geolocation/v2/geoLocation"
access_key = "여기에 Access Key"
secret_key = "여기에 Secret Key"
timestamp = str(int(time.time() * 1000))
base_string = f"{request_url}?ip={ip}&ext=t&responseFormatType=json"
signature = make_signature(
secret_key,
"GET",
base_string,
timestamp,
access_key
)
url = host_name_url + base_string
headers = {
"X-NCP-APIGW-TIMESTAMP": timestamp,
"X-NCP-IAM-ACCESS-KEY": access_key,
"X-NCP-APIGW-SIGNATURE-V2": signature
}
try:
response = requests.get(url, headers=headers)
response.raise_for_status()
data = response.json()
if "geoLocation" in data:
lat = data["geoLocation"]["lat"]
lng = data["geoLocation"]["long"]
else:
lat = 37.535053
lng = 127.147263
except Exception as e:
print("API Error:", e)
lat = 37.535053
lng = 127.147263
return {
"latitude": lat,
"longitude": lng
}
# 테스트
if __name__ == "__main__":
ip = "8.8.8.8"
result = get_geolocation(ip)
print(result)
Flask 에서 사용 할 경우
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route("/geolocation", methods=["POST"])
def geolocation():
ip = request.remote_addr
result = get_geolocation(ip)
return jsonify(result)
if __name__ == "__main__":
app.run(debug=True)
필요한 라이브러리
pip install requests
'Server Side > Python' 카테고리의 다른 글
| 파이썬 스웨거 문서 (0) | 2026.07.05 |
|---|---|
| 파이썬 fast-api 문서 (0) | 2026.07.05 |
