2014年8月31日 星期日

python read json file

import json

f = open('addressbook.json')

for addressbook in json.load(f):
    print addressbook['name']
    print addressbook['phone']




References :
http://stackoverflow.com/questions/2835559/parsing-values-from-a-json-file-in-python

2014年8月30日 星期六

configure: error: Unknown MySQL directory - unable to find mysql.h

# apt-get install libmysqlclient-dev

configure: error: Unable to find working zlib library

# apt-get install zlib1g-dev

使用 GitHub OpenID 登入網站

1. 建立一個新的 application,可得到 Client ID、Client Secret
https://github.com/settings/applications

2. 在 Authorization callback URL 填入授權成功後要返回的網址


github = OAuth2Service(name='github',
                         authorize_url='https://github.com/login/oauth/authorize',
                         access_token_url='https://github.com/login/oauth/access_token',
                         client_id=CLIENT_ID,
                         client_secret=CLIENT_SECRET,
                         base_url='https://api.github.com/',
                         )

使用 Facebook OpenID 登入網站

1. 建立一個 Facebook APP, 可得到 Client ID、Client Secret
https://developers.facebook.com/apps/

2. Settings -> Advanced -> Valid OAuth redirect URIs 填入授權成功後的返回網址


facebook = OAuth2Service(name='facebook',
                         authorize_url='https://graph.facebook.com/oauth/authorize',
                         access_token_url='https://graph.facebook.com/oauth/access_token',
                         client_id=config.get('FACEBOOK', 'client_id'),
                         client_secret=config.get('FACEBOOK', 'client_secret'),
                         base_url='https://graph.facebook.com/',
                         )

https://github.com/a0726h77/opensourcefeeds.tw/blob/master/wsgi/app/controllers/facebook.py

2014年8月29日 星期五

使用 Google OpenID 登入網站

Google Developers Console
https://console.developers.google.com/


google = OAuth2Service(name='google',
                         authorize_url='https://accounts.google.com/o/oauth2/auth',
                         access_token_url='https://accounts.google.com/o/oauth2/token',
                         client_id=CLIENT_ID,
                         client_secret=CLIENT_SECRET,
                         base_url='https://www.googleapis.com/oauth2/v1/',
                         )

https://github.com/a0726h77/opensourcefeeds.tw/blob/master/wsgi/app/controllers/google.py




References :
Using OAuth 2.0 for Login (OpenID Connect) - Google Accounts Authentication and Authorization — Google Developers
not engage in honest work: 使用Google帳號登入自己的網站

Decoder failed to handle access_token with data as returned by provider

service.get_auth_session(data=data, decoder=json.loads)




References :
Google oauth2 authentication throws an exception in rauth · Issue #110 · litl/rauth

2014年8月23日 星期六

Supervisord log rotation settings

// logfile-maxbytes 爲單個檔案的記錄大小,超過的會 rotate 成備份檔,設爲 0 的話則所有 log 保存在同一個檔案
logfile-maxbytes = 20MB
// logfile-backups 爲 log 檔案的個數,設爲 0 的話則只保留一個,其他則予以刪除
logfile-backups = 5
// stdout 與 stderr 也可獨立設定
stdout_logfile_maxbytes
stdout_logfile_backups
stderr_logfile_maxbytes
stderr_logfile_backups




References :
php - Supervisord log file rotation settings - Stack Overflow

2014年8月21日 星期四

Python SNMP trap receiver 範例

PySNMP Examples: Native/low-level API to SNMPv1/v2c operartions

snmptrapd 接收 trap 設定

# apt-get install snmptrapd 
# vi /etc/default/snmptrapd
TRAPDRUN=yes

# 預設 log 儲存在 syslog,若要更改要指定 -Lf
TRAPDOPTS='-Lsd -p /run/snmptrapd.pid -Lf /var/log/snmptrapd.log'

# vi /etc/snmp/snmptrapd.conf
format1 "%a %N %T"                                                                                        
authCommunity log public
authCommunity execute public
traphandle default /usr/bin/php /tmp/snmptrap.php
disableAuthorization yes


發送 trap 測試
$ snmptrap -v 1 -c public 127.0.0.1 '' 127.0.0.1 6 1 '1111'




References :

2014年8月19日 星期二

OpenShift user home folder

OpenShift 的 ~/ 是不允許寫入的,使用者個人的設檔當等資料可以放在 $OPENSHIFT_DATA_DIR
$ cd $OPENSHIFT_DATA_DIR





References :
Permission denied | OpenShift by Red Hat

2014年8月18日 星期一

application not registered on db instance and no application bound to current context

直接使用 db.create_all() 會出錯,改成以下
 
with app.app_context():
    db.create_all()

問題說明:
Flask and SQLAlchemy: init_app · Piotr Banaszkiewicz




References :
python - When scattering Flask Models, RuntimeError: 'application not registered on db' was raised - Stack Overflow

在本機連線到 OpenShift 上的 MySQL

// 啓用 port forward (會將 openshift 上的 port 對應到本地)
$rhc port-forward -a applicationName

// 使用 show app 可以看到資料庫連線的帳號密碼
$ rhc show-app --app applicationName

// 使用 TCP 連線到資料庫
$ mysql -u USERNAME -p -h 127.0.0.1 




References :
Getting Started with Port Forwarding on OpenShift | Openshift Blog

OpenShift SQLAlchemy Database URI

PostgreSQL :
import os
SQLALCHEMY_DATABASE_URI = os.environ['OPENSHIFT_POSTGRESQL_DB_URL']

MySQL :
import os
SQLALCHEMY_DATABASE_URI = os.environ['OPENSHIFT_MYSQL_DB_URL']




References :
flask程序部署在openshift上的一些注意事项 - ranvane的个人空间 - 开源中国社区

OpenShift 檢視 web log

500 Internal Server Error

Local :
$ rhc show-app --app YOUR_APP_NAME | grep SSH
$ ssh SSH_URL

Server :
$ cd app-root/logs/
$ cat python.log

2014年8月16日 星期六

Python 使用 Requests 與 BeautifulSoup 截取並分析網頁內容

範例參考:
A Simple Web Bot with Requests and BeautifulSoup – Stefan Scherfke

函式庫文件:
Requests: HTTP for Humans — Requests 2.3.0 documentation
Beautiful Soup Documentation — Beautiful Soup 4.2.0 documentation

Flask 輸出 RSS

Flask function 參考
http://flask.pocoo.org/snippets/10/

AtomFeed 參數參考
https://github.com/mitsuhiko/werkzeug/blob/master/werkzeug/contrib/atom.py

BeautifulSoup find children node

soup.find('li').findAll('a')




Refernces :
python - How to find children of nodes using Beautiful Soup - Stack Overflow 

BeautifulSoup get a link

for link in soup.findAll('a'):
    print link['href']




References :
python/beautifulsoup to find all with specific anchor text - Stack Overflow

2014年8月11日 星期一

Error: .ini file does not include supervisorctl section

Error: .ini file does not include supervisorctl section
For help, use /usr/bin/supervisorctl -h

# supervisorctl -c <(echo "[supervisorctl]") status




References :
plope - supervisorctl should be able to operate without a .conf file

docker mapping port to a running container

# docker ps

# docker inspect container_name | grep IPAddress

# iptables -t nat -A DOCKER -p tcp --dport 8002 -j DNAT --to-destination 172.17.0.19:8000




References :
Exposing a port on a live Docker container - Google Groups

UWSGI start error: /usr/share/uwsgi/init/do_command: line 7: /dev/fd/62: No such file or directory

# ln -s /proc/self/fd /dev/fd




References :
Snip2Code - UWSGI start error: /usr/share/uwsgi/init/do_command: line 7: /dev/fd/62: No such file or directory

uwsgi: no app loaded. going in full dynamic mode

Ubuntu 12.04 LTS provides 1.0.3. Removing that and using pip to install 2.0.4 resolved my issues.
# pip install uWSGI




References :
flask - uwsgi: no app loaded. going in full dynamic mode - Stack Overflow

Makefile 變數指定


// 若指定值使用其他變數,此變數會連帶更動
VARIABLE = value

// 若指定值使用其他變數,此變數不會連帶更動

VARIABLE := value  

// 若變數未設定值時才給值
VARIABLE ?= value 
 
// 增加字串到原有變數
VARIABLE += value




References :
gnu make - Makefile variable assignment - Stack Overflow

2014年8月6日 星期三

2014年8月5日 星期二

Python 中斷超過執行時間的程式

使用 subprocess 控制子行程時間
# Start foo as a process
p = multiprocessing.Process(target=foo, name="Foo", args=(10,))
p.start()

# Wait 10 seconds for foo
time.sleep(10)

# Terminate foo
p.terminate()

# Cleanup
p.join()
 
 
 
 
References :
python - Stop code after time period - Stack Overflow

jQuery Draggable / Droppable

Draggable :

$( ".selector" ).draggable();


使用選項的說明可參考此作者:
雪兒隨筆記: [jQuery]UI/API/1.8/Draggable



說明一下 helper 這個選項:


helper
傳入形態 : String("original", "clone") 或 Function()
預設值:"original"

指定拖曳元素的樣式,original 爲原本的元素;clone 爲復制一個與原本樣式相同的元素;function 回傳爲一個 DOM 元素,可制定拖拉後產生新的樣式的元素




Droppable :
$( ".selector" ).droppable();

使用選項可參考此作者:
雪兒隨筆記: [jQuery]UI/API/1.8/Droppable


列出常用的事件:
activate/ deactivate:在接受的物件拖動時觸發事件,例如可變更可放置區的背景顏色
drop:拖曳物件在此元素內放開後觸發事件
out:物件從此拖曳區移走後觸發事件
over:物件拖曳至此區上時觸發事件




References :
Draggable Widget | jQuery UI API Documentation
Droppable Widget | jQuery UI API Documentation

MySQL 建立分區

  • 建立分區時可在分區加上 DATA DIRECTORY 和 INDEX DIRECTORY 選項,將資料存在不同的硬碟分區中
  • 刪除分區時,分區內的資料也會被刪除
  • hash 和 key 類型的分區不能 REORGANIZE

分區限制:
  1. 分區欄位必須加入主鍵或唯一鍵
  2. 分區需返回 int 類型的值作爲條件判斷
  3. 一個表最多 1024 個分區

分區類型:
  • range
  • list
  • hash
  • key


// 新增分區
mysql> ALTER TABLE tbl PARTITION BY KEY(col1) PARTITIONS 5;
mysql> ALTER TABLE tbl partition by range(`day`) (
partition p_2012 values less than (20130000),
partition p_2013 values less than (20140000)
);


// 刪除分區 (刪除分區時,分區內的資料也會被刪除)
mysql> ALERT TABLE tbl DROP PARTITION p0;

//分區資料操作
mysql> ALTER TABLE tbl REBUILD PARTITION p0, p1;
mysql> ALTER TABLE tbl ANALYZE PARTITION p0, p1;
mysql> ALTER TABLE tbl OPTIMIZE PARTITION p0, p1;
mysql> ALTER TABLE tbl REPAIR PARTITION p0, p1;mysql> ALTER TABLE tbl CHECK PARTITION p0, p1;




References :
MySQL :: MySQL 5.5 Reference Manual :: 19.2 Partitioning Types
MySQL Partition | Jonathan Hui
mysql partition 分区功能使用详解-mysql教程-数据库-壹聚教程网

2014年8月4日 星期一

show MySQL table partition


// show partitions in database
SELECT TABLE_NAME, PARTITION_NAME FROM INFORMATION_SCHEMA.PARTITIONS WHERE TABLE_SCHEMA = 'db_name' ;

// show partition type
SHOW CREATE TABLE tbl_name;

// show table partition size

SELECT PARTITION_ORDINAL_POSITION, TABLE_ROWS, PARTITION_METHOD
FROM information_schema.PARTITIONS
WHERE TABLE_SCHEMA = 'db_name' AND TABLE_NAME = 'tbl_name';




References :
database - How to see table partition size in MySQL ( is it even possible? ) - Stack Overflow
mysql - Can i view tables which are under Partition in my sql - Stack Overflow