Tuesday 30 June 2015

Enable parsing of python code in Web browser with Lighttp server in Ubuntu Mate


python

For a couple of days I am trying to run python script in Web browser. For that I need to enable cgi for web browser, so that it enable to parse .py script. I am using lighttpd (light weight http daemon on my Ubuntu mate). After I installed lighttpd with sudo apt-get install lighttpd, I opened /var/etc/lighttpd/lighttpd.conf.




At the begining of the file it has this lines where "mod_cgi" is being commented.
So I uncommented the  "mod_cgi"

server.modules = (
    "mod_access",
    "mod_alias",
    "mod_compress",
     "mod_redirect",
        "mod_rewrite",
        "mod_cgi"
)
 

if you don't like to uncomment "mod_cgi" there is another option to enable cgi module. Go to terminal and type "lighty-enable-mod cgi".

But I recommend the first option.

After you uncomment the line go to the bottom of the file and add this line.

$HTTP["url"] =~ "^/cgi-bin/" {
        cgi.assign = ( ".py" => "/usr/bin/python" ).


 Close the file and create a directory named cgi-bin on /var/www/.
You can also create it in /var/www/html, but you have to change the path in lighttpd.conf :

server.document-root        = "/var/www/html", 
which is by default server.document-root        = "/var/www/"

After you make this changes restart lighttp daemon. Make sure you put all your python script in the folder cgi-bin in /var/www/html.


 

#python #pythonscript #pythonprogramming #webserver

Socket based chat application using UDP.

python




In last post on socket based application TCP protocol is used. This section describes how to create a socket for message exchange using User Datagram Protocol a simple connectionless transmission model with a minimum of protocol mechanism. The main advantage of using UDP is that no connection instance is required to build up for client as it requires in case of TCP. Socket itself received data from client with recvfrom function which returns data and address of the client. Server only waits for the client message and no connection request is required, it only receives and sends data without even identifying client individually.

udpServer.py


import socket  # Socket library 

def Main():    # main function

   host = "127.0.0.1"                           # host loop back address to test in 

                                                           # adapter-less machine.
   port = 5001                                    # port for server




  # socket object.
  s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
  s.bind((host,port))                            # binding to host ip and port
 
  print "Server Started.."
  while True:                                      # infinite loop, server always waits for data
    data, addr = s.recvfrom(1024)    # Receiving data from client.
    print "message from: " + str(addr)   
    print "from connected user: " + str(data)
    data = str(data).upper()              # Converting data to upper case
    print "sending: " + str(data)        

    s.sendto(data,addr)                     # sending data back to client
  s.close();                                        # Socket closed when loop terminates.

if __name__ == '__main__':             # Main module invoked.
  Main()


udpClient.py

import socket  # Socket library 

def Main():    # main function

   host = "127.0.0.1"  # host loop back address to test in adapter-less machine.

   port = 5001            # port for server


   server = ('127.0.0.1',5000)


# socket object.
   s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) 
   s.bind((host,port))

   message = raw_input('->')                               
# Waits for user input      
   while message != 'q':
      s.sendto(message,server)                              # User input data send to server
      data, addr = s.recvfrom(1024)                     # data received from server
      print "Received from server: " + str(data);
      message = raw_input('->')                           # Waits for user input
   s.close()

if __name__ == '__main__':                 
# Main module invoked.  
  Main()

#python #pythoprogramming #pythoscript #socketprograming

Monday 29 June 2015

Socket based chat application with Python




Python socket library is powerful and can be for socket based data transfer for both TCP and UDP protocol. This tutorial with TCP. I have created two modules. One tcpServer.py and other is tcpClient.py. 

1. tcpServer.py
  
     This module simply bind the socket object to the server ipaddress to a particular port.
     Then it's listen for incoming connection from the client. It does nothing until it receives any 
     request. Once it receive request it accepts and enter into data exchange (chat). The server does 
     nothing but receives data send by the client and send back the same to client converting it to 
     uppercase. If the client terminates the server again go back to the state where it again listen for 
     some new connection request. Server can be stopped by pressing Ctrl+C. The program is included 
     inside Main() function to make it executable only. Cannot be used as library in any other module.

tcpServer.py code

import socket  # Socket library 

def Main():    # main function

 host = "127.0.0.1"  # host loop back address to test in adapter-less machine.
 port = 5000            # port for server

 s = socket.socket()  # socket object.
 s.bind((host,port))  # binding to server ip and port mentioned.


 while True:  # infinite loop ends on Ctrl+C by user.

    print "Server is waiting for connection...."  # waiting message displayed 

    s.listen(1)    # listening for incoming connection request.

    c, addr = s.accept()    #  Connection request accepted and connection object and client ip address 
                                       # returned

    print "Connection accepted from: " + str(addr) # message printed for connection success

    while True:  # infinite loop to exchange message with client

           data = c.recv(1024)            # receiving if any data send by client
           if not data:                          # checking if data exists, this condition is only false when 
                   break                         # client program terminates. 
                   

           print "Data recieved from user: " + str(data)
           print "Sending data to client"
          data = str(data).upper()              # received data converted to  uppercase.
          c.send(data)                               # received data send to client

       c.close()                                       # connection closed.

if __name__ == '__main__':              # Main is not called automatically but with this statement.
 Main()



2. tcpClient.py.

   TCP client takes host ip and host port  to connect (server binds and client connects). It asks input 
   from user (message) and it is send to the server until user enters quit in input. 


import socket

def Main():

 host = "127.0.0.1"
 port = 5000

 s = socket.socket()
 s.connect((host,port))                                          # Connects to server host and port.

 message = raw_input("==>")                             # Input from user.

 while message!= "quit":                                    # Loop until user enters quit

      s.send(message)                                           # Entered message send to server.
      data = s.recv(1024)                                      # Received data from server as response.
      print "Message from server: " + str(data)    # print the received message
      message = raw_input("==>")                      # Waits for the next user input

 s.close()                                                            # socket closed.

if __name__ == '__main__':                                                     
 Main()

------------------------------------------------------------------------------------------------------------------------------------

#python #pythoprogramming #pythoscript #socketprogramming

Friday 26 June 2015

Export oracle data to Microsoft Excel from Oracle forms.


 
A few days back I have been requested 
by one of my youtube viewer to make 
an oracle forms tutorial that will 
exports oracle database data to excel 
file with a single button click. 
Alas.. I am not talking about exporting 
data to CSV, but instead exporting 
directly to excel file. This has a 
few advantages. You can place your 
data in your desired format. Format 
your cell, with colors, style, and 
other excel features. So just go 
through this code given below, 
you can also copy paste the code, all you need to change is the column heading 
and sql string as per your requirement. It have nothing but one forms in-build 
package ole2.
 

declare
 application ole2.obj_type;
 workbooks ole2.obj_type;
 workbook ole2.obj_type;
 worksheets ole2.obj_type;
 worksheet ole2.obj_type;
 cell ole2.obj_type;
 arglist ole2.list_type;
 row_num number;
 col_num number;
 fontObj ole2.obj_type;
 cursor rec is select emp_code,emp_name,to_char(date_of_birth,'dd/mm/rrrr') date_of_birth from employee_master where date_of_birth is not null;
 procedure SetCellValue(rowid number,colid number,cellValue varchar) is
 begin
  arglist := ole2.create_arglist;
  ole2.add_arg(arglist,rowid);
  ole2.add_arg(arglist,colid);
  cell:= ole2.get_obj_property(worksheet,'Cells',arglist);
  fontObj := ole2.get_obj_property(cell,'Font');
  ole2.destroy_arglist(arglist);
  ole2.set_property(cell,'value',cellValue);
  ole2.set_property(fontObj,'Size',16);
  ole2.set_property(fontObj,'BOLD',1);
  ole2.set_property(fontObj,'ColorIndex',7);
  ole2.release_obj(cell);
 end SetCellValue;
 procedure app_init is
  begin
   application := ole2.create_obj('Excel.Application');
   ole2.set_property(application,'Visible',true);
   workbooks := ole2.get_obj_property(application,'workbooks');
   workbook := ole2.invoke_obj(workbooks,'add');
   worksheets := ole2.get_obj_property(application,'worksheets');
   worksheet := ole2.invoke_obj(worksheets,'add');
   ole2.set_property(worksheet,'Name','Emp Sheet');
 end app_init;
 
 procedure save_excel(path varchar,filename varchar) is
  begin
    OLE2.Release_Obj(worksheet);
    OLE2.Release_Obj(worksheets);
    -- Save the Excel file created
    If path is not null then
       Arglist := OLE2.Create_Arglist;
       OLE2.Add_Arg(Arglist,path||'\'||file_name||'.xls');
       OLE2.Invoke(workbook, 'SaveAs', Arglist);
       OLE2.Destroy_Arglist(Arglist);
    end if;
 end save_excel;

 begin
  app_init;
    row_num:=1;
    col_num:=1;
    SetCellValue(row_num,col_num,'Emp Code');
    col_num:=col_num + 1;
    SetCellValue(row_num,col_num,'Emp Name');
    col_num:=col_num + 1;
    SetCellValue(row_num,col_num,'Date of Birth');
    for i in rec loop
     row_num:=row_num + 1;
     col_num:=1;
     SetCellValue(row_num,col_num,i.emp_code);    
     col_num:=2;
     SetCellValue(row_num,col_num,i.emp_name);    
     col_num:=3;
     SetCellValue(row_num,col_num,i.date_of_birth);    
    end loop;    
   save_excel('d:\excel_export','emp_data');       
    OLE2.Release_Obj(workbook);
    OLE2.Release_Obj(workbooks);
    OLE2.Release_Obj(application); 
end;