Implement JWT On Django Rest

Pada tutorial sebelumnya kita sudah mempelajari tentang

selanjutnya kali ini kita akan mengimplementasikan JWT pada Django Rest Framework

install jwt pada django :
pip install djangorestframework-jwt
tambahkan pada setting.py script di bawah ini untuk membuat screet key dan token expired
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
 }

 

buat function untuk encode dan decode JWT
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"}))
good luck ….!

Interface Cursor Already Closed on Nginx

Python Django

Saat kamu menggunakan raw query pada django dengan database postgres dan kamu menemukan pesan error “Interface Cursor Already Closed”. kamu perlu membuat Try … Exception, pesan error tersebut di karenakan akses koneksi ke database terputus dan pid uwsgi tidak mampu mereload koneksi ke database postgres. solusi simplenya lihat contoh di bawah ini

from django.db import connections
from django.db.utils import InterfaceError
cursor = connections['default'].cursor()
 
def dictfetchall(cursor):
    "Return all rows from a cursor as a dict"
    columns = [col[0] for col in cursor.description]
    return [
        dict(zip(columns, row))
        for row in cursor.fetchall()
        ]
try:
    cursor.execute("""select * from ean_expedia_properties""")
    all_list = dictfetchall(cursor)    
except InterfaceError:
    cr = connections['default'].cursor()
    cr.execute("""select * from ean_expedia_properties""")
    all_list = dictfetchall(cr)
 
print(all_list)

 

good luck !

Dictionary Raw SQL Queries Django

Python Django

Bagaimana cara membuat dictionary pada raw SQL query django ?

pertama import library django connection

from django.db import connections
cursor = connections['default'].cursor()

 

kedua buat function untuk merubah index menjadi dictionary

def dictfetchall(cursor):
    "Return all rows from a cursor as a dict"
    columns = [col[0] for col in cursor.description]
    return [
        dict(zip(columns, row))
        for row in cursor.fetchall()
        ]

 

ketiga buat function untuk memanggil data dari database

def p_mapping_list(request):
    try:
        cursor.execute("""SELECT id, parent_id FROM test LIMIT 2""")
        all_list = dictfetchall(cursor)
        for p in all_list: 
            print(p.parent_id)
    except:
        cursor.close()
        connections['default'].cursor()

 

link dokumentasihttps://docs.djangoproject.com/en/1.11/topics/db/sql/

good luck …!

 

Auto Complete Django

Auto Complete Django

Bagaimana membuat form auto complete pada django ?

Buat sebuah form

<div>
    Hotel Name: <input type="text" id="ean_hotel" name="hotel_name" />
   ID_Ean : <input type="text" id="id_ean" name="id_ean" />
</div>

 

Buat scrip auto complete dengan jquery

<script type="text/javascript">
$(document).ready(function(){
    var ac_config = {
        source:'http://localhost:8002/properties/p-auto',
        headers: {'X-CSRFToken': '{{ csrf_token }}'},
    select: function(event, ui) {
        $('#id_ean').val(ui.item.property_id);
        event.preventDefault();
        $("#ean_hotel").val(ui.item.properties_name); },
        minLength:1
    };
    $("#ean_hotel").autocomplete(ac_config);
});
</script>

 

buat function untuk mengolah data json 

def get_auto_properties(request):
    propertyGet = request.GET.get('term')
    getProperties = Propertiesmodel.objects.filter(name__contains=propertyGet)
 
    lst = []
    for x in getProperties:
        d = {}
        d['ean_hotel_id'] = x.ean_hotel_id
        d['property_id'] = x.property_id
        d['properties_name'] = x.name
        lst.append(d)
 
    response = json.dumps(lst, default=myconverter)
    return HttpResponse(response)
 
def myconverter(o):
    if isinstance(o, datetime):
        return o.__str__()

 

good luck …!