Django Rest Framework merupakan framework untuk membuat web RESTful API. Django Rest Framework sudah banyak digunakan oleh perusahan-perusahan besar seperti Mozilla, Heroku, Eventbrite, dan lain — lain. Penggunaan Django Rest Framework terbilang mudah, untuk suatu model kita tidak perlu mendefinisikan method GET, POST, UPDATE, dll, Django Rest Framework lah yang mengatur semua method request.
Pada tutorial sebelumnya kita sudah mempelajari tentang
pip install djangorestframework-jwt
SECRET_KEY = "12345"
EXPIRY_TIME = datetime.timedelta(seconds=20)
JWT_AUTH = {
'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=20), # Token expires * seconds after being issued
'JWT_ALLOW_REFRESH': True,
'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(seconds=120), # Token can be refreshed up to * seconds after being issued
}
def get_token(request):
username =request.GET.get('username')
password = request.GET.get('password')
if username and password is not None:
payload = {
'username': username,
'password':password,
'exp':datetime.utcnow() + settings.EXPIRY_TIME
}
token = jwt.encode(payload, settings.SECRET_KEY, algorithm='HS256')
token =str(token).replace("b'","")
token = str(token).replace("'", "")
token= {'token':token}
return HttpResponse(
json.dumps(token)
)
else:
return HttpResponse(
json.dumps({'Error': "Invalid credentials"}),
status=400
)
def get_verivy_token(request):
token =request.GET.get('token')
try:
payload = jwt.decode(token, settings.SECRET_KEY, algorithm='HS256')
return HttpResponse(
json.dumps(payload),
status=200
)except jwt.ExpiredSignature:
return HttpResponse(json.dumps({'Error': "Token is invalid"}))
except:
return HttpResponse(json.dumps({'Error': "Token DoesNotExist"}))
baca artikel lainya :