✅ 내용
- Docker compose로 Django와 PostgreSQL설치
- postgreSQL 유저/테이블 이름:
minha
/ikaria
- API gateway
- endpoint:
/users
POST
: body에 사용자 이름을 넣어서 보내면 postgreSQL에 사용자 이름, 접속날짜, ip 주소 저장. 만약 이미 있는 사용자면 접속 날짜 업데이트
- Postman API 명세서
✅ Django
✔ model
from ipaddress import ip_address
from django.db import models
class User(models.Model):
name = models.CharField(max_length=100)
created_at = models.DateTimeField(auto_now_add = True)
updated_at = models.DateTimeField(auto_now = True)
ip_address = models.GenericIPAddressField(null=True)
class Meta:
db_table = 'users'
✔ view
import json
from django.http import JsonResponse
from django.views import View
from users.models import User
class UserView(View):
def post(self, request):
try:
data = json.loads(request.body)
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
name = data['name']
if x_forwarded_for:
ip = x_forwarded_for.split(',')[-1].strip()
else:
ip = request.META.get('REMOTE_ADDR')
if not User.objects.filter(name=name).exists():
User.objects.create(name = name, ip_address=ip)
else:
[i.save() for i in User.objects.filter(name=name)]
result = [{
'name' : user.name,
'created_at' : user.created_at.strftime('%Y-%m-%d %H:%M:%S'),
'updated_at' : user.updated_at.strftime('%Y-%m-%d %H:%M:%S'),
'ip' : user.ip_address
}for user in User.objects.all()]
return JsonResponse({'result' : result}, status = 200)
except:
return JsonResponse({'message' :'ERROR'}, status = 400)
✅ PostgreSQL