2014年7月30日 星期三

Flask return csv from sql

from flask import Response, send_file
    try:
        from cStringIO import StringIO                                                         
    except ImportError:
        from StringIO import StringIO

    output = StringIO()

    # 查詢
    results = Users.query.all()

    # 寫入 csv file
    for user in results:
    output.write("%s,%s,%s\n" % (user.id, user.name, user.email))

    # 輸出
    filename = address.csv

    response = Response(output.getvalue(), mimetype='text/csv')
    response.headers['Content-Disposition'] = 'attachment; filename=' + filename

    output.seek(0)
    return send_file(output, as_attachment=True, attachment_filename=filename)




References :
flask note - 我的Java生活 - ITeye技术网站
Returning MySQL query data in a csv file with Flask

GPG Key 簽署流程


撤銷 GPG key

妥善保護您密匙固然最重要,但您也要為萬一不幸的事作預備。一般的做法是您要事前先產生一個撤銷憑證 (Revoke Certificate) ,當您的 GnuPG 密匙不幸被盜去或遺失了後,您就可以用這撤銷憑證 去宣告原先的 GnuPG 鑰匙無效。 



# 產生撤銷憑證
$ gpg --output ~/myrevoke.asc --gen-revoke your_user_id

# 撤銷 GPG key
$ gpg --import ~/myrevoke.asc

$ gpg --keyserver pgp.mit.edu --send-keys your_user_id 




References :
產生 GnuPG 撤銷憑證 (Revoke Certificate) - FlossDoc
Revoking a GPG Key Pair | Carthik Sharma

GPG key 過期處理

$ gpg --list-keys
pub 4096R/ABCD1234 2013-09-26 [expired: 2013-12-31]

$ gpg --edit-key ABCD1234

gpg> list

pub 4096R/ABCD1234 created: 2013-09-26 expired: 2013-12-31 usage: SC
trust: unknown validity: expired
sub 4096R/EFGH5678 created: 2013-09-26 expired: never usage: E

gpg> key 0    # 只選擇 primary key,取消選擇 sub key

gpg> expire
Changing expiration time for the primary key.
Please specify how long the key should be valid.
0 = key does not expire
= key expires in n days
w = key expires in n weeks
m = key expires in n months
y = key expires in n years
Key is valid for? (0) 2014-12-31    # 可輸入到期日期
Key expires at Wed Dec 31 00:00:00 2014 CST
Is this correct? (y/N) y

gpg> save

$ gpg --keyserver keys.gnupg.net --send-keys ABCD1234




References :
How to change the expiration date of a GPG key | G-Loaded Journal

2014年7月25日 星期五

Sqlalchemy delete in subquery

InvalidRequestError: Could not evaluate current criteria in Python. Specify 'fetch' or False for the synchronize_session parameter.


sl = DBSession.query(Puesto.id).filter(Puesto.locales_id == id).subquery() DBSession.query(Servicio).filter(Servicio.puestos_id.in_(sl)) \ .delete(synchronize_session='fetch')




References :
python - Sqlalchemy delete subquery - Stack Overflow

2014年7月16日 星期三

ldap.OPERATIONS_ERROR: {'info': '000004DC: LdapErr: DSID-0C090724, comment: In order to perform this operation a successful bind must be completed on the connection., data 0, v23f0', 'desc': 'Operations error'}

ldap.OPERATIONS_ERROR: {'info': '000004DC: LdapErr: DSID-0C090724, comment: In order to perform this operation a successful bind must be completed on the connection., data 0, v23f0', 'desc': 'Operations error'}

 
import ldap
connect = ldap.open('127.0.0.1')
connect.set_option(ldap.OPT_REFERRALS, 0)connect.bind_s(USERNAME, PASSWORD)
result = connect.search_s(BASE_DN, ldap.SCOPE_SUBTREE, SEARCH_FILTER)
print result


References :
active directory - Python-ldap not able to bind successfully - Stack Overflow

2014年7月14日 星期一

Python string substitution using dictionaries

import re

sub_dict = {
    '%AAA%': 'Hello',
    '%BBB%': 'world'
}

pattern = '|'.join(sub_dict.keys())
repl_func = lambda matchobj: sub_dict[matchobj.group(0)]


text = "%AAA%, the %BBB% !"

text = re.sub(pattern, repl_func, text)




References :
Re: [問題] Python全文取代 - 看板 Python - 批踢踢實業坊

Convert integer to string in Jinja

{{ 12345678|string }}
{{ 1111|int }}
  
{% if 1111 == '1111' %}
    1111
{% else %}
    2222
{% endif %}




References :
python - Convert integer to string Jinja - Stack Overflow

2014年7月11日 星期五

jQuery textarea .val() 保留換行符號

var preserved = $('textarea').val().replace(/\n\r?/g, '%0D%0A');




References :
jQuery - Preserve textarea line breaks for AJAX call

簡訊(SMS) API 編碼

若是用 AT command 發送的

空格 (SPACE) 要代換成 +
換行 (\n)要代換成 %0a


一般使用 http 發送的 API,會自動代換空格及換行字元,唯中文需使用 urlencode

* 中華電信的 API 是使用 Big5 編碼
SMSTEXT = urllib.quote(SMSTEXT.encode('big5'))

* 簡訊發送字數長度限制:單一則訊息純英文數字為160字,中英文及數字混合為70字,字數計算包含空格



References :
請教中華電信發送簡訊的問題- 藍色小舖 BlueShop

2014年7月10日 星期四

查詢 Gearman 狀態

$ gearadmin --status

Column Explanation :
  1. Function Name
  2. Number in queue
  3. Number of jobs running
  4. Number of capable workers
 
 
 
 
 
References :
php - Gearman gearadmin command line tool status output meaning - Stack Overflow 

2014年7月9日 星期三

SQL GROUP BY records and then get last record from each group

id| name  | attendence
1 | Naveed| 1
2 | Naveed| 1
3 | Adil  | 1
4 | Adil  | 1 


SELECT MAX("id"), "name" FROM "test" WHERE "attendence" = 1 GROUP BY "name"

select * from (SELECT * from test order by id desc) as t WHERE "attendence" = 1 GROUP BY "name"




References :
php - SQL: GROUP BY records and then get last record from each group? - Stack Overflow

2014年7月8日 星期二

使用 git 產生diff 與接受 patch

產生差異檔
$ git diff  > patch
$ git diff  --cached > patch
$ git diff  branchname --cached > patch

套用補丁
$ git apply --check patch
$ git apply patch


延伸閱讀:git format-patch

Flask url_for in javascript

1. 使用 flask request 變數得到系統資訊
 
script type=text/javascript 
$SCRIPT_ROOT = {{ request.script_root|tojson|safe }}; 
/script
 
script type=text/javascript 
$.ajax({
    url: $SCRIPT_ROOT + "/api/uid",   
....
/script

 2. 使用 flask_util_js
dantezhu/flask_util_js




References :
AJAX with jQuery — Flask 0.11-dev documentation

sed in shell script

sed: -e expression #1, char 14: unknown option to `s'


line="Include /2"
rep=""
sed -e "s/${line}/${rep}/g" /root/new_scripts/a.conf
sed -e "s|${line}|${rep}|g" /root/new_scripts/a.conf 
 
 
 
 
 
References :
bash - replace a string in file using shell script - Stack Overflow

2014年7月6日 星期日

Python install ldap module

Modules/errors.h:8: fatal error: lber.h: No such file or directory
# apt-get install libldap2-dev


# pip install python-ldap





References :
module - Python: can't install python-ldap - Stack Overflow

2014年7月3日 星期四

Python string to operator

import operator

ops = {
    "+": operator.add,
    "-": operator.sub,
    ">=": operator.ge,
    "<=": operator.le
}

print ops[">="](2, 1)
print ops["<="](2, 1)




References :
Python:: Turn string into operator - Stack Overflow

2014年7月1日 星期二

DDWRT update ip to freedns.afraid.org

1. 取得 token
登入後進入此頁 https://freedns.afraid.org/dynamic/,可看到管理的 records,在要更新的 record 的 Direct URL 連結按右鍵,復制連結位址,連結路徑 ? 後面的編碼即爲 token

https://freedns.afraid.org/dynamic/update.php?YOUR_TOKEN


2. 設定 DDWRT
進入  DDNS 設定頁 http://192.168.1.1:8080/DDNS.asp

DDNS Service : freedns.afraid.org
User Name : 登入 freedns.afraid.org 的帳號
Password : 登入 freedns.afraid.org 的密碼
Host Name : example.mooo.com,AbCdEfGhIJKlMnOpQrStUvWxYz=
                      ,




References :

ddclient for freedns.afraid.org

ddclient 版本需 3.8.1 以上 (支援協定:freedns)




$ wget -O ddclient-3.8.2.tar.bz2 http://downloads.sourceforge.net/project/ddclient/ddclient/ddclient-3.8.2/ddclient-3.8.2.tar.bz2?r=http%3A%2F%2Fsourceforge.net%2Fprojects%2Fddclient%2F&ts=1404268199&use_mirror=ncu

$ tar jxf ddclient-3.8.2.tar.bz2

$ cd ddclient-3.8.2

# cp ddclient /usr/sbin/
# apt-get install libdigest-sha-perl

# mkdir /var/cache/ddclient/

# vi /etc/ddclient/ddclient.conf
use=if, if=ppp0
server=freedns.afraid.org
protocol=freedns
login=login_name
password=the_password
somedomain.mooo.com

# vi /etc/rc.local
/usr/sbin/ddclient -daemon=1 -syslog -quiet -force





FATAL: Error loading the Perl module Digest::SHA1 needed for freedns update.
FATAL: On Debian, the package libdigest-sha1-perl must be installed.


這是舊版 ddclient 的問題,debian 已移除套件 libdigest-sha1-perl,下載新版 ddclient 並安裝 libdigest-sha-perl

#734661 - ddclient: Please update to 3.8.2 - Debian Bug report logs



 
References :
Dynamic DNS clients
ddclient | Free System Administration software downloads at SourceForge.net

Lua library path

.so
/usr/local/lib/lua/5.1

.lua
/usr/local/share/lua/5.1

Gearman Python example

Basic Client and Worker | Gearman HQ | The hosted job queue management system for getting work done using Gearman.