Skip to content

Instantly share code, notes, and snippets.

@omsobliga
omsobliga / image_to_string.py
Last active June 13, 2018 04:19
保存图片到buffer
### 保存图片到内存
import StringIO
output = StringIO.StringIO()
format = 'PNG' # or 'JPEG' or whatever you want
image.save(output, format)
contents = output.getvalue()
output.close()
### 保存图片到文件
# INSERT INTO table_tags (tag) VALUES ('tag_a'),('tab_b'),('tag_c') ON DUPLICATE KEY UPDATE tag=tag;
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.sql.expression import Insert
@compiles(Insert)
def append_string(insert, compiler, **kw):
s = compiler.visit_insert(insert, **kw)
if 'append_string' in insert.kwargs:
return s + " " + insert.kwargs['append_string']
#!/usr/bin/env python
# coding: utf-8
from tornado.web import RequestHandler
class UploadHandler(RequestHandler):
def put(self):
username = self.get_body_argument('username')
@omsobliga
omsobliga / re.py
Last active November 16, 2017 03:28
import re
# 去除所有半角全角符号,只留字母、数字、中文。
def remove_punctuation(line):
rule = re.compile(ur'[^a-zA-Z0-9\u4e00-\u9fa5]')
line = rule.sub('',line)
return line
@omsobliga
omsobliga / csv.py
Last active November 16, 2017 10:54
import csv
file_ = open('file.csv', 'r')
reader = csv.reader(file_, delimiter=',',
quotechar='|', quoting=csv.QUOTE_MINIMAL)
file_ = open('file.csv', 'aw')
writer = csv.writer(file_, delimiter=',',
quotechar='|', quoting=csv.QUOTE_MINIMAL)
file_.flush()
import datetime
import time
# timestamp to datetime
ts = int(time.time())
print datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
# datetime to timestamp
print datetime.datetime(2017, 05, 23, 10, 30, 00).strftime('%s')
@omsobliga
omsobliga / rsa.py
Last active September 28, 2016 11:28
公开密钥加密 RSA
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 参考资料:
# * https://en.wikipedia.org/wiki/RSA
#
# Show RSA document:
# > from Crypto.PublicKey import RSA
# > help(RSA)
from Crypto.PublicKey import RSA
@omsobliga
omsobliga / aes.py
Last active March 21, 2018 06:26
对称加密 AES
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 参考资料:
# * https://en.wikipedia.org/wiki/Advanced_Encryption_Standard
# * https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation
#
# Show AES document:
# > from Crypto.Cipher import AES
# > help(AES)
@omsobliga
omsobliga / cors_server.py
Last active July 24, 2018 03:20 — forked from enjalot/cors_server.py
Allow CORS with python simple http server
# python cors_server.py
import SimpleHTTPServer
class CORSHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def send_head(self):
"""Common code for GET and HEAD commands.
This sends the response code and MIME headers.
Return value is either a file object (which has to be copied
@omsobliga
omsobliga / transaction_in_concurrent.py
Last active August 15, 2016 02:56
用多进程模拟数据库事务在并发环境下的表现
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
用多进程模拟数据库事务在并发环境下的表现。
测试环境:
一个数据库 server, 4 核机器, 四个进程
运行结果::
run 0 process
run 1 process