Web dev example : JSON & jQuery Mobile & Bottle

Bottle is a fast, simple and lightweight WSGI micro web-framework for Python. jQuery Mobile base on jQuery for mobile device. jQuery vs. jQuery Mobile vs. jQuery UI Install bottle: $ sudo apt-get install python-setuptools $ easy_install bottle Demo server deployment file structure: BottlejQuery ├── bottleJQuery.py └── index.html run command: $ ./bottleJQuery.py connect to server: http://localhost:8080/bottle Building simple web server use bottle bottleJQuery.py #!/usr/bin/env python from bottle import route, static_file, debug, run, get, redirect from bottle import post, request import os, inspect, json #enable bottle debug debug(True) # WebApp route path routePath = '/bottle' # get directory of WebApp (bottleJQuery.py's dir) rootPath = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) @route(routePath) def rootHome(): return redirect(routePath+'/index.html') @route(routePath + '/<filename:re:.*\.html>') def html_file(filename): return static_file(filename, root=rootPath) @get(routePath + '/jsontest') def testJsonGET(): print "GET Header : \n %s" % dict(request.headers) #for debug header return {"id":2,"name":"Jone"} @post(routePath + '/jsontest') def testJsonPost(): print "POST Header : \n %s" % dict(request.headers) #for debug header data = request.json print "data : %s" % data if data == None: return json.dumps({'Status':"Failed!"}) else: return json.dumps({'Status':"Success!"}) run(host='localhost', port=8080, reloader=True) Test GET request: $ curl -i -X GET http://localhost:8080/bottle/jsontest HTTP/1.0 200 OK Date: Wed, 07 Aug 2013 16:03:53 GMT Server: WSGIServer/0.1 Python/2.7.3 Content-Length: 25 Content-Type: application/json {"id": 2, "name": "Jone"} bottle debug message: ...

August 7, 2013 · 4 min · oopsmonk

Sending HTML Mail Using SMTP With Authorization

Here is a text/plain MIME type parts in official exmaple code. I remove it from my sample code, because it’s not show up in mail at Office Outlook 2010. #!/usr/bin/env python """ File name: sendMail.py Python send HTML mail using SMTP with authorization Usage : ./sendMail.py to@gmail.com Subtitle [ FilePath | txt ] """ import smtplib import sys,traceback from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from time import gmtime, strftime #log file location log_path = "./mail-log"; #log timestamp format logger_tstamp = "%Y-%m-%d %H:%M:%S" #SMPT server smtp_server = "smtp.gmail.com" #gmail 465 or 578 smtp_port = 587 #mail from user = "from@gmail.com" pwd = "password" # log method class Logger: file = 1 err = 2 class ContentType: file = 1 txt = 2 #select log method debug_log = Logger.err #select content type content_type = ContentType.txt def debug(msg): if debug_log == Logger.file: with open(log_path, 'a') as log_file: log_file.write(strftime(logger_tstamp, gmtime()) + msg) log_file.close() elif debug_log == Logger.err: sys.stderr.write(strftime(logger_tstamp, gmtime()) + msg) else: print(strftime(logger_tstamp, gmtime()) + msg) #check argument number arg_count = len(sys.argv) if arg_count !=4: debug("[Error]: invalid argument\n") sys.exit(1) try: mail_to = sys.argv[1] subject = sys.argv[2] if content_type == ContentType.file: content_path = sys.argv[3] with open(content_path, 'r') as f_content: content = f_content.read() f_content.close() else: content = sys.argv[3] serv = smtplib.SMTP(smtp_server, smtp_port) # serv.ehlo() serv.starttls() # serv.ehlo() serv.login(user, pwd); msg = MIMEMultipart('alternative') msg['Subject'] = subject msg['From'] = user msg['To'] = mail_to part1 = MIMEText(content, 'html') msg.attach(part1) serv.sendmail(user, mail_to, msg.as_string()) serv.quit() debug("[Debug] subject : " + subject + "\n") except: debug("[Error]: send mail error\n") debug("[Error]:\n" + traceback.format_exc()) sys.exit(2); Reference: email: Examples smtplib How to send email in Python via SMTPLIB ...

July 31, 2013 · 2 min · oopsmonk

Redirect and Save iptables on Ubuntu 12.04

Redirect port 8080 to 80 sudo iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8080 Check iptables setting sudo iptables -t nat -L Save configure to iptables.rules sudo iptables-save > /etc/iptables.rules Save Solution #1 Configre /etc/network/interfaces iface eth0 inet dhcp pre-up iptables-restore < /etc/iptables.rules Save Solution #2 Configure /etc/network/if-pre-up.d/iptablesload #!/bin/sh iptables-restore < /etc/iptables.rules exit 0 Configure /etc/network/if-post-down.d/iptablessave #!/bin/sh iptables-save -c > /etc/iptables.rules if [ -f /etc/iptables.downrules ]; then iptables-restore < /etc/iptables.downrules fi exit 0 Change permissions ...

July 5, 2013 · 1 min · oopsmonk

Connect Oracle 10g Database use JDBC

install jayDeBeApi & jpype $ sudo apt-get install python-setuptools $ sudo easy_install JayDeBeApi $ sudo easy_install jpype Download Oracle JDBC Drivers ojdbc6.jar to local. import jpype import jaydebeapi jHome = jpype.getDefaultJVMPath() print jHome jpype.startJVM(jHome, '-Djava.class.path=/path/to/ojdbc6.jar') conn = jaydebeapi.connect('oracle.jdbc.driver.OracleDriver', 'jdbc:oracle:thin:user/password@DB_HOST_IP:1521:DB_NAME') curs = conn.cursor() curs.execute("select * from ACCOUNT") acc = curs.fetchall() curs.close() conn.close() jpype.shutdownJVM() print acc Reference: https://pypi.python.org/pypi/JayDeBeApi http://wiki.python.org/moin/Oracle

June 24, 2013 · 1 min · oopsmonk

Install JDK1.4.2(32bit) on Ubuntu 12.04 LTS(64bit)

Here is an error occurred if installed directly: install.sfx.XXX: not found Solution: install g++-mltilib and JDK $ sudo apt-get install g++-multilib $ chmod +x j2sdk-1_4_2_19-linux-i586.bin $ ./j2sdk-1_4_2_19-linux-i586.bin ..... Do you agree to the above license terms? [yes or no] yes Unpacking... Checksumming... 0 0 Extracting... UnZipSFX 5.40 of 28 November 1998, by Info-ZIP (Zip-Bugs@lists.wku.edu). creating: j2sdk1.4.2_19/ creating: j2sdk1.4.2_19/jre/ creating: j2sdk1.4.2_19/jre/bin/ inflating: j2sdk1.4.2_19/jre/bin/java inflating: j2sdk1.4.2_19/jre/bin/keytool inflating: j2sdk1.4.2_19/jre/bin/policytool .... Creating j2sdk1.4.2_19/lib/tools.jar Creating j2sdk1.4.2_19/jre/lib/rt.jar Creating j2sdk1.4.2_19/jre/lib/jsse.jar Creating j2sdk1.4.2_19/jre/lib/charsets.jar Creating j2sdk1.4.2_19/jre/lib/ext/localedata.jar Creating j2sdk1.4.2_19/jre/lib/plugin.jar Creating j2sdk1.4.2_19/jre/javaws/javaws.jar Done. $ sudo mkdir -p /usr/lib/jvm $ sudo mv j2sdk1.4.2_19 /usr/lib/jvm/java-1.4.2_19 Java environment configuration. $ wget http://webupd8.googlecode.com/files/update-java-0.5b $ chmod +x update-java-0.5b $ sudo ./update-java-0.5b Select java-1.4.2_19 Check java version $ java -version java version "1.4.2_19" Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.2_19-b04) Java HotSpot(TM) Client VM (build 1.4.2_19-b04, mixed mode)

June 20, 2013 · 1 min · oopsmonk

Remove the same files in two folders

有時在整理照片或文件時, 需要比對2個資料匣, 把重覆的檔案拿掉. Dwonload Source Here function usage(){ echo "Find the same file in two folders and remove it." echo "usage : ./comp-rm.sh target-dir source-dir" echo "remove the same files in target-dir." } if [ $# -ne 2 ]; then usage exit 1 fi target_dir=$1 source_dir=$2 f_list1=$(find "$target_dir" -type f) f_list2=$(find "$source_dir" -type f) for i in $f_list1; do echo $f_list2 | grep $(basename $i) >/dev/null && hit_str+=$i";" done if [ -z $hit_str ]; then echo "list is empty.." exit 0 fi export IFS=";" count=0 for hit_file in $hit_str; do echo "$hit_file" let count++ done echo "Do you want to remove these files ($count)?" read -p "Press 'Ctrl+C' stop, 'Enter' key to continue..." for hit_file in $hit_str; do echo "removing... $hit_file" rm -f $hit_file done exit 0

June 19, 2013 · 1 min · oopsmonk

Raspberry Pi Setup

Install Raspbian “wheezy” image Download image from Raspberry Pi offical website Mount HOME to HDD Copy HOME data to disk $ sudo mkdir /media/new_home $ sudo mount /dev/sda1 /media/new_home $ sudo rsync -aXS /home/. /media/new_home/. $ sudo umount /media/new_home fstab #get disk UUID $ sudo blkid /dev/mmcblk0p1: SEC_TYPE="msdos" LABEL="boot" UUID="936C-7122" TYPE="vfat" /dev/mmcblk0p2: UUID="c1198422-7a7c-4863-8a8f-45a1db26b4f2" TYPE="ext4" /dev/sda1: UUID="2cd990b5-6c27-4933-95d0-fd00b000fe77" TYPE="ext4" #modify fstab $ echo "UUID=2cd880b5-6c27-4933-95d0-fd00b000fe77 /home ext4 defaults 0 2" | sudo tee --append /etc/fstab #mount HOMW without reboot. $ sudo mount -a Create a sudo user #create user with HOME directory $ sudo useradd -m oopsmonk #add user to sudo group $ sudo adduser oopsmonk sudo #set password $ sudo passwd oopsmonk Install necessary packages $ sudo aptitude full-upgrade -y $ sudo aptitude install tmux vim git python-setuptools -y $ sudo easy_install pip SAMBA server $ sudo aptitude install samba $ sudo cp /etc/samba/smb.conf /etc/samba/smb.conf.bak $ sudo vi /etc/samba/smb.conf enable sucurity user # security = user [rpi] comment = raspberry-pi path = /home/oopsmonk/ browseable = yes writable = yes read only = no #add smaba user and restart samba server $ sudo pdbedit -a -u oopsmonk $ sudo service samba restart Configre default editor $ echo "export EDITOR=vim" >> ~/.bashrc $ echo "export GIT_EDITOR=vim" >> ~/.bashrc $ echo "export TERM=screen-256color" >> ~/.bashrc $ echo "alias tmux='tmux -2'" >> ~/.bashrc $ source ~/.bashrc Boot from USB Disk Use dd or Win32DiskImager dump image to both SD card and USB Disk. ...

June 15, 2013 · 5 min · oopsmonk