Skip to content

Instantly share code, notes, and snippets.

@huyx
huyx / trim_docstring
Created December 20, 2013 02:23
处理 docstring 缩进 参考: http://www.python.org/dev/peps/pep-0257/
# -*- coding: utf-8 -*-
import sys
def trim_docstring(docstring):
'''Handling Docstring Indentation
Reference:
- [PEP 257](http://www.python.org/dev/peps/pep-0257/) -- Docstring Conventions
'''
@huyx
huyx / tornado_thread_example.py
Created December 21, 2013 13:25
tornado 多线程操作
'''
See:
- https://gist.github.com/akhenakh/2894704/raw/0735da48251e77ad8a29230b92f6a6ce3a4f604c/gistfile1.py
'''
import functools
import time
import threading
import logging
import Queue
@huyx
huyx / adbapi.py
Last active December 10, 2020 04:02
Twisted MySQL 接口扩展,支持: - 自动重连 - 返回INSERT的自增ID - 返回多个查询结果集
# -*- coding: utf-8 -*-
from twisted.enterprise import adbapi
from twisted.python import log
import MySQLdb
import itertools
class ReconnectingMixin:
"""MySQL 重新连接时, ConnectionPool 可以正确执行指定的操作,流程是:
- 执行操作
# -*- coding: utf-8 -*-
import functools
def unicode2str(o, encoding='utf-8', errors='strict'):
'''把对象中的 unicode 字符串编码成 str
:param o: 要解码的对象
:param encoding: 编码类型
:param errors: strict|ignore|replace 参见 ''.encode 中的说明
@huyx
huyx / dotdict-old.py
Last active January 2, 2016 02:09
用 . 操作 dict 中的元素
# -*- coding: utf-8 -*-
class dotdict(dict):
'''用 . 操作 dict 中的元素
>>> dd = dotdict(a=1, b=2)
>>> dd.c = 3
>>> dd
{'a': 1, 'c': 3, 'b': 2}
>>> del dd.c
# -*- coding: utf-8 -*-
class dotdict(dict):
'''用 . 操作 dict 中的元素
>>> dd = dotdict(a=1, b=2)
>>> dd.c = 3
>>> dd
{'a': 1, 'c': 3, 'b': 2}
>>> del dd.c
@huyx
huyx / twisted-web-py-file.py
Created January 4, 2014 12:02
支持 Twisted Web 中的 rpy 文件,作了下列定制: - 由于很多编辑器不支持 .rpy 文件的语法高亮,改用 .py 作为 rpy 文件扩展名 - 允许不指定 .html 和 .py 扩展名,默认按照 .html 和 .py 的顺序查找文件 - 索引文件默认为: index.html, index.py
# -*- coding: utf-8 -*-
from twisted.web import static, script
class PyFile(static.File):
u'''支持 Twisted Web 中的 rpy 文件,作了下列定制:
- 由于很多编辑器不支持 .rpy 文件的语法高亮,改用 .py 作为 rpy 文件扩展名
- 允许不指定 .html 和 .py 扩展名,默认按照 .html 和 .py 的顺序查找文件
- 索引文件默认为: index.html, index.py
'''
@huyx
huyx / htmlbuilder.py
Created January 7, 2014 08:35
从 flaskext.htmlbuilder 精简过来
# -*- coding: utf-8 -*-
u"""html builder
从 flaskext.htmlbuilder 精简过来
对比了很多 html 生成工具,包括看起开很不错的:
- [PyH]()
- [Dominate](https://github.com/Knio/dominate) -- 从 pyy 进化而来
@huyx
huyx / writeable.py
Last active January 4, 2016 10:59
文件和目录是否可写
import os
import tempfile
def dir_writeable(dir):
try:
(fd, name) = tempfile.mkstemp(dir=dir)
os.close(fd)
os.unlink(name)
except IOError:
return False
from collections import namedtuple
from urllib import urlencode
import os
FormFile = namedtuple('FormFile', 'filename, data')
def encode_form(fields, multipart=False, headers=None):
headers = headers or {}