Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 테라폼
- Azure
- Azure 자격증
- 오리지널스 솔티드 에그
- docker
- K8S
- 리눅스 동아리
- poetry
- 교내활동
- 카카오클라우드
- Kubernetes
- 애저
- az-900
- 도커
- dockerfile
- 쿠버네티스
- kakaocloud
- 수제버거
- 웹 서버
- 벅벅
- 화랑대
- 더블쿼터파운더 치즈
- 한성대입구역
- 가상환경
- 리눅스
- 버거킹 오리지널스 솔티드 에그
- Terraform
- 더블쿼터파운더 치즈 세트
- 오리지널스 솔티드 에그 싱글
- 웹 배포
Archives
- Today
- Total
클라우드 공부 일지
FastAPI SMS 전송 및 인증 확인 with coolsms 본문
requirements.py
annotated-types==0.7.0
anyio==4.4.0
certifi==2024.7.4
charset-normalizer==3.3.2
click==8.1.7
coolsms==0.4
coolsms_python_sdk==2.0.3
fastapi==0.112.0
h11==0.14.0
idna==3.7
pydantic==2.8.2
pydantic_core==2.20.1
python-dotenv==1.0.1
requests==2.32.3
sniffio==1.3.1
starlette==0.37.2
typing_extensions==4.12.2
urllib3==2.2.2
uvicorn==0.30.5
작성한 후 아래 명령어를 터미널에 입력하면 필요한 패키지들을 자동으로 설치해 준다.
pip install -r requirements.txt
main.py
import random
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from sdk.api.message import Message
from sdk.exceptions import CoolsmsException
from dotenv import load_dotenv
import os
# .env 파일의 환경 변수를 로드합니다.
load_dotenv()
# 환경 변수에서 API 키와 비밀번호를 불러옵니다.
API_KEY = os.getenv("API_KEY")
API_SECRET = os.getenv("API_SECRET")
SENDER_NUMBER = os.getenv("SENDER_NUMBER")
app = FastAPI()
verification_codes = {}
class PhoneNumberRequest(BaseModel):
phone_number: str
class VerifyCodeRequest(BaseModel):
phone_number: str
verification_code: str
def generate_verification_code(length=6):
return "".join(random.choices("0123456789", k=length))
@app.post("/send_sms/")
def send_sms(request: PhoneNumberRequest):
verification_code = generate_verification_code()
verification_codes[request.phone_number] = verification_code
params = {
"type": "sms",
"to": request.phone_number,
"from": SENDER_NUMBER,
"text": f"인증번호는 {verification_code}입니다.",
}
cool = Message(API_KEY, API_SECRET)
try:
response = cool.send(params)
if response["success_count"] > 0:
return {"message": "SMS sent successfully"}
else:
raise HTTPException(status_code=400, detail="Failed to send SMS")
except CoolsmsException as e:
raise HTTPException(status_code=500, detail=f"Internal Server Error: {e.msg}")
@app.post("/verify_sms/")
def verify_sms(request: VerifyCodeRequest):
if verification_codes.get(request.phone_number) == request.verification_code:
return {"message": "Verification successful"}
else:
raise HTTPException(status_code=400, detail="Invalid verification code")
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
.env
API_KEY = "coolsms에서 받은 api 키"
API_SECRET = "coolsms에서 받은 api 시크릿 키"
SENDER_NUMBER = "핸드폰 번호"
프로젝트 디렉토리 구조
project_directory/
│
├── main.py
├── .env
└── requirements.txt
SMS 전송 Curl문 예시
# SMS 전송 요청
curl -X 'POST' \
'http://127.0.0.1:8000/send_code/' \
-H 'Content-Type: application/json' \
-d '{
"phone_number": "01012345678"
}'
인증 코드 검증 Curl문 예시
# 인증 코드 검증 요청
curl -X 'POST' \
'http://127.0.0.1:8000/verify_code/' \
-H 'Content-Type: application/json' \
-d '{
"phone_number": "01012345678",
"verification_code": "123456"
}'
실행 시 결과 값
'Python' 카테고리의 다른 글
FastAPI SMS 전송 및 인증 확인 + 로그인 구현 with coolsms (0) | 2024.08.04 |
---|---|
FastAPI 환경 구축 with VSCode (0) | 2024.07.27 |