วันเสาร์ที่ 24 มกราคม พ.ศ. 2558

Test 03 - csv data sort in cgi


Test 03 csv data sort in cgi

ในคราวนี้ผมจะทดสอบโดยการ ให้ cgi เปิดไฟล์ csv ออกมาแล้วสามารถที่จะจัดเรียง
ข้อมูลในนั้นและแสดงออกมาได้
ขั้นแรกเลย จัดเตรียม server ให้พร้อมที่จะ run cgi
 ต่อมาเข้าไปที่ 0.0.0.0:8000/#dir/#file โดยในคราวนี้ผมได้ตั้งชื่อไฟล์ว่า datasort.cgi
 หน้าตาของโปรแกรมเป็นแบบนี้ ในขั้นแรกจะให้เลือกไฟล์ csv ที่อยู่ใน directory ที่จัดเตรียมไว้
เพื่อที่จะนำมาใช้แสดงผล ในที่นี้เป็น /home/#user/bss/csv-data/ โดย user คือชื่อ username
ให้เรากดเลือกไฟล์ใดไฟล์หนึ่งเพื่อนที่จะนำมาแสดงผล
 โปรแกรมก็จะแสดงผลข้อมูลในไฟล์ออกมา โดยในขั้นแรกจะยังไม่มีการจัดเรียงอะไร สามารถที่จะเปลี่ยนไฟล์ได้โดยไปที่ change file แล้วเลือกไฟล์ที่ต้องการ
 เมื่อเลือกไฟล์ที่ต้องการได้แล้วสามารถที่จะสั่งให้มันจัดเรียง ตาม id มาก - น้อย หรือตรงกันข้ามได้โดย
ไปที่ Sort by
ผลของการจัดเรียงเป็นดังนี้


code ::


#!/usr/bin/python
#--coding: utf-8 -*-
print "Content-type: text/html\n ; charset=utf-8"
import os, cgi
query = cgi.FieldStorage()
selectedfile, command = "", ""
for i in query.keys():
    exec(i + " = " + query[i].value)

def sortby(obj, type):
    data = {}
    for table in range(len(obj)-1):
        if(obj[table][1] != ""):
            data[len(data)] = int(obj[table][1].replace("-", "").replace(" ", ""))
        else: data[len(data)] = 0   
    i = j = 0
    while i < len(data):
        j = i
        while j < len(data):
            if type == "up":
                if data[j] < data[i]:   
                    dd = data[i]
                    data[i] = data[j]
                    data[j] = dd
                    dummy = obj[i]
                    obj[i] = obj[j]
                    obj[j] = dummy
            elif type == "down":
                if data[j] > data[i]:   
                    dd = data[i]
                    data[i] = data[j]
                    data[j] = dd
                    dummy = obj[i]
                    obj[i] = obj[j]
                    obj[j] = dummy
            j += 1
        i += 1
    return obj
       

print """
<script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
<script>
function jumptofile(file){
    window.location.href = location.protocol + '//' + location.host + location.pathname+"?selectedfile=\\\""+file+"\\\"&command=\\\"\\\"";
}

function jumptoparam(command){
   
    window.location.href = location.protocol + '//' + location.host + location.pathname+"?selectedfile=\\\""""+selectedfile+"""\\\"&command=\\\""+command+"\\\"";
}

function check(part){
    $(part).toggle();
}
</script>
"""

library = "/home/galible/bss/csv-data"
trav = os.walk(library);
datarows, datatables, title = {}, {}, {}
if selectedfile == "":
    print "&nbsp;&nbsp;&nbsp;<h1><font color=\"red\">choose the file</font></h1>"
    for fol in trav:
        for file in fol[2]:
            print "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<font size=\"5\">>>> </font><a onclick=\"javascript:jumptofile(name)\" name=\""+str(fol[0])+"/"+str(file)+"\"><font size=\"5\" color=\"#FFAA55\">"+str(fol[0])+"/"+str(file)+"</font><font size=\"5\"> <<<</font></a><br>";
else:
    print "<h1><font color=\"#0055FF\">detail for csv file : </font><font color=\"#FF5500\">"+selectedfile+"</font></h1>"   
    file = open(selectedfile, 'r')
    datatables = file.readlines()
    for row in datatables:
        if title == {}:
            title = row.split(",")
        else:
            datarows[len(datarows)] = row.split(",")
       
    print "change file : <select onchange=\"jumptofile(value)\">"
    for fol in trav:
        for file in fol[2]:
            print "<option value=\""+str(fol[0])+"/"+str(file)+"\" "+((str(file) == str(selectedfile.split("/")[-1])) and "selected" or "")+">"+str(file)+"</option>"
    print "</select><br>"
    if command == "":
        print "Sort by : <select onchange=\"jumptoparam(value)\"><option value=\"\" selected>no sort</option><option value=\"sortidup\">sort id up to down</option><option value=\"sortiddown\">sort id down to up</option></select><br>"
    if command == "sortidup":
        print "Sort by : <select onchange=\"jumptoparam(value)\"><option value=\"\">no sort</option><option value=\"sortidup\" selected>sort id up to down</option><option value=\"sortiddown\">sort id down to up</option></select><br>"
        datarows = sortby(datarows, "up")
    if command == "sortiddown":
        print "Sort by : <select onchange=\"jumptoparam(value)\"><option value=\"\">no sort</option><option value=\"sortidup\">sort id up to down</option><option value=\"sortiddown\" selected>sort id down to up</option></select><br>"
        datarows = sortby(datarows, "down")
   
    print "<table border=\"4\">"
    print "<tr>"
    for header in title:
        print "<td>" + header + "</td>"
    print "</tr>"
    for table in range(len(datarows)):
        print "<tr>"
        for row in datarows[table]:
            print "<td>" + row + "</td>"
        print "</tr>"
    print "</table>"

Test 02 - directory list in cgi


test 02 directory list by cgi

จากคราวที่แล้วที่ได้ทดสอบ ให้ python เขียน html ดู คราวนี้จึงได้ทดสอบการใช้
cgi ในการเขียนหน้าเว็บ โดย python
ขั้นแรก จัดเตรียม เซิฟเวอร์ให้พร้อมที่จะรัน cgi

ทดสอบรันโค้ดที่ได้เขียนมา
 โดยเข้าไปที่ 0.0.0.0:8000/#dir/#file โดย #dir คือ directory ที่อยู่ภายใน server และ #file คือชื่อของ file






--code--

#!/usr/bin/python
print "Content-type: text/html\n\n"
import cgi, cgitb, os

datain = cgi.FieldStorage()
directory, srcq = "", ""

def spl(text):
    text = text.replace("/", "");
    text = text.replace(".", "");
    text = text.replace("~", "__sp__");
    return text

def chknxtnode(text1, text2):
    root = ""
    leaf = ""
    if len(text1) > len(text2):
        root = text2
        leaf = text1
    else:   
        root = text1
        leaf = text2
    i, result = 0, 1
    while i < len(root):
        if root[i] != leaf[i]:
            result = 0
        i += 1
    return result

def space(num):
    for i in range(num):
        print "&nbsp;"

def namefol(part):
    part = part.split("/")
    return part[len(part)-1]
   

def nbfol(part):
    print " <input type=\"button\" value=\"show\" name=\""+spl(part)+"\" id=\""+spl(part)+"=show\" onclick=\"javascript:showtools(name)\"> <"+spl(part)+" style=\"display:none\"><input type=\"button\" name=\""+part+"\" value=\"rename\" onclick=\"javascript:dirrename(name)\"><input type=\"button\" name=\""+part+"\" value=\"new file\" onclick=\"javascript:dirnewfile(name)\"></"+spl(part)+">"

def nbfile(part):
    print " <input type=\"button\" value=\"show\" name=\""+spl(part)+"\" id=\""+spl(part)+"=show\" onclick=\"javascript:showtools(name)\"> <"+spl(part)+" style=\"display:none\"><input type=\"button\" name=\""+part+"\" value=\"delete\" onclick=\"javascript:filedelete(name)\"><input type=\"button\" name=\""+part+"\" value=\"rename\" onclick=\"javascript:filerename(name)\"></"+spl(part)+">"

for i in datain.keys():
    exec(i + " = " + datain[i].value)

print """
<script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
<script>
function jumpto(){
    var query = document.getElementById("txtb1").value;
    var srcq = document.getElementById("txtb2").value;
    var old = \"""" + directory + """\"
    if(query == "-"){
        window.location.href = "dirls.py?directory=\\\""+old+"\\\"&srcq=\\\""+srcq+"\\\"";
    }else{
        window.location.href = "dirls.py?directory=\\\""+query+"\\\"&srcq=\\\""+srcq+"\\\"";
    }
}

function showtools(part){
    var enp = $(part);
    var data = document.getElementById(part+"=show");
    if(data.value == "show"){
        data.value = "hide";
        enp.show();
    }else{
        data.value = "show";
        enp.hide();
    }
}

function check(part){
    $(part).toggle();
}

function dirrename(part){
    while(true){
        datas = part.split("/")
        var folname = datas[datas.length - 1];
        var dirname = "";
        for(var i = 0; i < datas.length - 1; i++){
            dirname += datas[i];
        }
        var newname = prompt("Rename this folder to", folname);
        if(newname == null){
            break;
        }
        if($(dirname+newname).length == 0){
            xmlhttp = new XMLHttpRequest();
            xmlhttp.open("GET", "command.py?type=\\\"rename\\\"&dir=\\\""+part[0]+"\\\"&newname=\\\""+newname+"\\\"");
            xmlhttp.send();
            break;
        }else{
            alert("sorry guys but this name is exists in directory");
        }
    }
}

function dirnewfile(part){

}

function filedelete(part){

}

function filerename(part){

}
</script>
"""

print "<html><head></head><body><b>Directory : <input type=\"textbox\" name=\"txtbdir\" id=\"txtb1\"> \"-\" for still use old directory<br>Search for : </b><input type=\"textbox\" name=\"txtsrc\" id=\"txtb2\"> <input type=\"button\" value=\"accept\" name=\"butselect\" onclick=\"javascript:jumpto()\"><br><br>"

try:   
    if (directory != "") and (srcq == ""):
        print "<h1>Search in " + directory + "</h1>"
        try:
            data = os.walk(directory);
            updir = {}
            updir[0] = str(directory)
            for part in data:
                while 1:
                    if chknxtnode(updir[len(updir) - 1], part[0]):
                        updir[len(updir)] = part[0]
                        break
                    else:
                        dummy = {}
                        for i in range(len(updir) - 1):
                            dummy[i] = updir[i]
                        updir = dummy
                space(3*(len(updir)-2))
                print "<b><a href=\""+part[0]+"\">"+part[0]+"</a></b> "
                nbfol(part[0])
                print "<br>"
                for file in part[2]:
                    space(3*(len(updir)-1))
                    print "<a href=\""+part[0]+file+"\">"+file+"</a> size : "+ str(os.stat(str(part[0])+"/"+str(file)).st_size) + " b "
                    nbfile(str(part[0])+str(file))
                    print "<br>"
        except:    print "directory not exists !!";
    elif directory != "":
        print "<h1>Search for " + srcq + " in " + directory + "</h1>"
        try:
            data = os.walk(directory);
            for part in data:
                if srcq in namefol(part[0]):
                    print part[0]
                    nbfol(part[0])
                    print "<br>"
                for file in part[2]:
                    if srcq in file:
                        space(5);
                        print part[0] + " --> <a href=\""+str(part[0])+"/"+str(file)+"\">"+file+"</a>"
                        nbfile(str(part[0])+"/"+str(file))
                        print "<br>"
        except:    print "directory not exists !!";
    else: gotoexcept
except:    print "<h2>Please enter some directory and push select...</h2>"

ผลการทดสอบของ code

ใส่ directory ที่ต้องการค้นหาลงไป
หลังจากกด accept แล้วจะแสดงผลการค้นหาขึ้นมาทดสอบค้นหาคำ โดยการพิมพ์ key word ที่ต้องการค้นหาลงไปในช่อง search for หลังจากนั้นกด accept จะปรากฎ file ที่มีชื่อตรงกับคำที่ใส่ลงไป

วันพุธที่ 14 มกราคม พ.ศ. 2558

Test 01 - python html directory


Test01 python-html-directory !!

การทดสอบที่ 1 ใช้ไพทอนไปเขียนไฟล์ใน HTML เพื่อที่จะแสดง directory ที่อยู่ในเครื่อง
ผลลัพธ์เป็นดังนี้
สร้างไฟล์ pdir.py ไว้โดยเขียนโค้ดไพธอนและสั่งรันโค้ดของมัน
จะขั้นให้ใส่ directory root ที่จะเป็นจุดเริ่มต้นของการค้นหา
ในภาพให้เป็น /home

 ได้ผลลัพธ์ดังนี้ โดยมันจะไปสร้างไฟล์ไว้ที่ /home/[USER] อยู่แล้ว โดยกำหนดให้โค้ด
บันทึกไฟล์เป็นชื่อ part.html
 และหลังจากที่กดที่ button แล้วจะมี directory ย่อยออกมา
 หลังจากนั้นทดสอบเปลี่ยน directory root

ผลที่ได้ออกมาก็เปลี่ยนเช่นกัน
โดย code ของ python เป็นดังนี้
Code -->


import os
def spl(text):
    text = text.replace("/", "");
    text = text.replace(".", "");
    return text

def chknxtnode(text1, text2):

    root = ""
    leaf = ""
    if len(text1) > len(text2):
        root = text2
        leaf = text1
    else:   
        root = text1
        leaf = text2
    i, result = 0, 1
    while i < len(root):
        if root[i] != leaf[i]:
            result = 0
        i += 1
    return result
directory = raw_input("input the directory : ")
datastr = "<script src=\"/home/galible/jquery.js\"></script>\n<script>\nfunction check(part){\n    $(part).toggle();\n}\n</script>\n<html></br><font color=\"#22CCFF\"><b><h1>Directory of "+directory+"</b></h1>"
datadir = os.walk(directory)
updir = {}
updir[0] = str(directory)
closepart = {}
for part in datadir:
    while not updir == {}:
        if chknxtnode(updir[len(updir)-1], part[0]):
            k = 0
            while k < len(updir)-1:
                for l in [1, 2, 3, 4, 5]:
                    datastr += "&nbsp;"
                k += 1
            datastr += "<input type=\"button\" name=\""+spl(part[0])+"\" value=\""+part[0]+"\" id=\""+spl(part[0])+"=button\" onclick=\"javascript:check(name)\"></br>\n"
            if updir[len(updir)-1] == part[0]:
                datastr += "<"+spl(updir[len(updir)-1])+">\n"
            else: datastr += "<"+spl(part[0])+">\n"
            updir[len(updir)] = part[0];
            break
        else:   
            datastr += "</"+spl(updir[len(updir)-1])+">\n"
            j = 0
            dummy = {}
            while j < len(updir)-1:
                dummy[j] = updir[j]
                j += 1
            updir = dummy
    for name in part[2]:
        k = 0
        while k < len(updir)-1:
            for l in [1, 2, 3, 4, 5]:
                datastr += "&nbsp;"
            k += 1
        datastr += name+"</br>\n"
    datastr += "<script>$(\""+spl(part[0])+"\").toggle()</script></br>"
datastr += "</html>"
file = open("part.html", 'w')
file.writelines(datastr)