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 …!

Sample Xpath in Python

sample xpath in python

XPath (XML Path Language) adalah bahasa kueri untuk memilih bagian – bagian (nodes) dari sebuah dokumen XML. XPath juga dapat digunakan untuk menghitung nilai (contoh : string, angka atau boolean) dari isi dari sebuah dokumen XML. XPath distandarisasi oleh World Wide Web Consortium (W3C)

berikut ini contoh penggunaan xpath pada python

buat file xml terlebih dahulu misal kita namakan cancel_response.xml

<?xml version=”1.0″ encoding=”ISO-8859-1″?>
	<SOAP-ENV:Envelope
	xmlns:SOAP-ENV=”http://schemas.xmlsoap.org/soap/envelope/”
	xmlns:xsd=”http://www.w3.org/2001/XMLSchema”
	xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
	xmlns:SOAP-ENC=”http://schemas.xmlsoap.org/soap/encoding/”
	xmlns:tns=”urn:webservice”>
		<SOAP-ENV:Body>
			<ns1:WsCancelPNRResponse xmlns:ns1=”urn:sj_service”>
				<return xsi:type=”tns:respWsCancelPNR”>
					<Username xsi:type=”xsd:string”>xy</Username>
					<BookingCode xsi:type=”xsd:string”>QTGPDF</BookingCode>
					<ErrorCode xsi:type=”xsd:string”>CANCEL0005</ErrorCode>
					<ErrorMessage xsi:type=”xsd:string”>Invalid PNR status.</ErrorMessage>
				</return>
			</ns1:WsCancelPNRResponse>	
		</SOAP-ENV:Body>
	</SOAP-ENV:Envelope>

 

buat file untuk parse XPath misal parse.py

 

import requests
import json
from lxml import etree
from lxml.builder import ElementMaker
from lxml.objectify import fromstring
from io import StringIO, BytesIO
from collections import OrderedDict
 
def process_response():
 
    response = open('cancel_response.xml').read()
    response_namespaces={
        'e' : 'http://schemas.xmlsoap.org/soap/envelope/',
        'ns1':'urn:sj_service'
    }
 
    tree = etree.fromstring(response.encode('utf-8'))
 
    x_response = tree.xpath('//e:Body/ns1:WsCancelPNRResponse/return',namespaces=response_namespaces)
 
    message = x_response[0].xpath('ErrorMessage/text()')[0]
    booking_code = x_response[0].xpath('BookingCode/text()')[0]
 
    response_message = OrderedDict()
    response_message['booking_code'] = booking_code
    response_message['message'] = message
    json_response = json.dumps(response_message)
 
    print(json_response)

 

Good Luck … !