uuid/hmac/hashlib生成唯一ID
在有些情况下你需要生成一个唯一的字符串。我看到很多人使用md5()函数来达到此目的,但它确实不是以此为目的。其实有一个名为uuid()的Python函数是用于这个目的的。
import uuid
result = uuid.uuid1()
print result
# output => various attempts
# 9e177ec0-65b6-11e3-b2d0-e4d53dfcf61b
# be57b880-65b6-11e3-a04d-e4d53dfcf61b
# c3b2b90f-65b6-11e3-8c86-e4d53dfcf61b
你可能会注意到,即使字符串是唯一的,但它们后边的几个字符看起来很相似。这是因为生成的字符串与电脑的MAC地址是相联系的。
为了减少重复的情况,你可以使用这两个函数。
import hmac,hashlib
key='1'
data='a'
print hmac.new(key, data, hashlib.sha256).hexdigest()
m = hashlib.sha1()
m.update("The quick brown fox jumps over the lazy dog")
print m.hexdigest()
# c6e693d0b35805080632bc2469e1154a8d1072a86557778c27a01329630f8917
# 2fd4e1c67a2d28fced849ee1bb76e7391b93eb12
压缩字符
当谈起压缩时我们通常想到文件,比如ZIP结构。在Python中可以压缩长字符,不涉及任何档案文件。import zlib
string = """ Lorem ipsum dolor sit amet, consectetur
adipiscing elit. Nunc ut elit id mi ultricies
adipiscing. Nulla facilisi. Praesent pulvinar,
sapien vel feugiat vestibulum, nulla dui pretium orci,
non ultricies elit lacus quis ante. Lorem ipsum dolor
sit amet, consectetur adipiscing elit. Aliquam
pretium ullamcorper urna quis iaculis. Etiam ac massa
sed turpis tempor luctus. Curabitur sed nibh eu elit
mollis congue. Praesent ipsum diam, consectetur vitae
ornare a, aliquam a nunc. In id magna pellentesque
tellus posuere adipiscing. Sed non mi metus, at lacinia
augue. Sed magna nisi, ornare in mollis in, mollis
sed nunc. Etiam at justo in leo congue mollis.
Nullam in neque eget metus hendrerit scelerisque
eu non enim. Ut malesuada lacus eu nulla bibendum
id euismod urna sodales. """
print "Original Size: {0}".format(len(string))
compressed = zlib.compress(string)
print "Compressed Size: {0}".format(len(compressed))
decompressed = zlib.decompress(compressed)
print "Decompressed Size: {0}".format(len(decompressed))
# output
# Original Size: 1022
# Compressed Size: 423
# Decompressed Size: 1022
注册Shutdown函数
有个模块叫atexit,它可以让你在脚本运行完后立马执行一些代码。假如你想在脚本执行结束时测量一些基准数据,比如运行了多长时间:
import atexit
import time
import math
def microtime(get_as_float = False) :
if get_as_float:
return time.time()
else:
return '%f %d' % math.modf(time.time())
start_time = microtime(False)
atexit.register(start_time)
def shutdown():
global start_time
print "Execution took: {0} seconds".format(start_time)
atexit.register(shutdown)
# Execution took: 0.297000 1387135607 seconds
# Error in atexit._run_exitfuncs:
# Traceback (most recent call last):
# File "C:\Python27\lib\atexit.py", line 24, in _run_exitfuncs
# func(*targs, **kargs)
# TypeError: 'str' object is not callable
# Error in sys.exitfunc:
# Traceback (most recent call last):
# File "C:\Python27\lib\atexit.py", line 24, in _run_exitfuncs
# func(*targs, **kargs)
# TypeError: 'str' object is not callable
打眼看来很简单。只需要将代码添加到脚本的最底层,它将在脚本结束前运行。但如果脚本中有一个致命错误或者脚本被用户终止,它可能就不运行了。
当你使用atexit.register()时,你的代码都将执行,不论脚本因为什么原因停止运行(如这里atexit.register(start_time)出错,register接受的是函数对象而不是字符串,出错了,但是后面的atexit.register(shutdown)还是执行了,输出为Execution took: 0.297000 1387135607 seconds)。
web相关模块
wsgiref
webpy
Whitenoise
只需简单地修改Config文件,用户就可以按自己的意图来以静态文件方式部署Web应用,而不必依赖于Nginx、亚马逊S3等外部服务。Whitenoise能对打包内容进行压缩并设置高容量的缓存。
遵循WSGI规范的应用需要在部署时对Whitenoise配置进行调整:
这样做的重要性是什么?使用Gzip可有效地减少静态文件体积和页面载入。但是搜索引擎会侦测到Gzip压缩,这会导致网站不执行Gzip。所以需要透过上述修改来避免这种情况。
Spyne
一个用于构建RPC服务的工具集,支持SOAP,JSON,XML等多种流行的协议。
现在有诸如 flask-restful 以及 django-rest-framework 等框架用于 REST 服务的开发,人们对于 REST 之外的框架似乎兴趣不大。Spyne 很好地填补了这一空白,它支持多种协议,而且本身也封装地相当好:
class HelloWorldService(ServiceBase):
@srpc(Unicode, Integer, _returns=Iterable(Unicode))
def say_hello(name, times):
for i in range(times):
yield 'Hello, %s' % name
application = Application([HelloWorldService],
tns='spyne.examples.hello',
in_protocol=Soap11(validator='lxml'),
out_protocol=Soap11()
)
短短几行代码便实现了一个支持SOAP 1.1 协议的服务器端application,接入任何一个WSGI兼容的服务器后端就可以运行了。
[https://github.com/arskom/spyne]
benoitc/gunicorn
gunicorn ‘Green Unicorn’ is a WSGI HTTP Server for UNIX, fast clients and sleepy applications
一个Python WSGI UNIX的HTTP服务器,从Ruby的独角兽(Unicorn)项目移植。Gunicorn大致与各种Web框架兼容.
一个例子,运行你的flask app:
gunicorn myproject:app
使用起来超级简单!
[gunicorn]
smtplib 邮件模块
[Python_使用smtplib和email模块发送邮件]
[python模块学习 ---- smtplib 邮件发送]
创业公司喜爱的3款Python库
Instavest上发表了一篇博文,文章分享了深受创业公司喜爱的3款Python库,该文章在Hacker News上引发了开发者的激烈探讨。
1. Whitenoise(见上面)
2. Phonenumbers(精简版)
要识别出电话号码不是件容易的事情,而正则表达式也不一定能处理好各种五花八门的有效电话格式。
例如:
- 无效的:222-222-2222(这会通过正则测试)
- 有效的:313-442-1231 外线. 901
可见依赖于单一的正则检测不一定能得到想要的答案,所以,要适当借助工具—Phonenumbers。推荐原因是它小巧,实用简便,没有地理代编码,运营商,时区等metadata数据。它能识别多种格式,然后使用不同的格式/样式进行有效匹配。
3. Pdfkit
借助Pdfkit可以便捷地把HTML转换成PDF文件。这有何用处呢?比方说你的应用有一个含有发票信息的页面,你就可以透过Pdfkit帮助生成一个PDF文件供用户进行下载,其用法如下:
4.Python-dateutil
Numerous date utilities for calculating differences, etc. The most useful of these is a resilient date parser:
[ Three Useful Python Libraries for Startups ]
让人耳目一新的Python库
docopt
Github: https://github.com/docopt/docopt
Pythonic的命令行参数解析库:
"""Usage:
quick_example.py tcp <host> <port> [--timeout=<seconds>]
quick_example.py serial <port> [--baud=9600] [--timeout=<seconds>]
quick_example.py -h | --help | --version
"""
from docopt import docopt
if __name__ == '__main__':
arguments = docopt(__doc__, version='0.1.1rc')
print(arguments)
requests
Github: https://github.com/kennethreitz/requests
大神kennethreitz的作品,简易明了的HTTP请求操作库, 是urllib2的理想替代品。requests is an elegant HTTP library.
API简洁明了,这才是Python开发者喜欢的:
>>> r = requests.get('https://api.github.com/user', auth=('user', 'pass'))
>>> r.status_code
200
>>> r.headers['content-type']
'application/json; charset=utf8'
>>> r.encoding
'utf-8'
>>> r.text
u'{"type":"User"...'
>>> r.json()
{u'private_gists': 419, u'total_private_repos': 77, ...}
[python爬虫 - python requests网络请求简洁之道]
sh
http://amoffat.github.io/sh/
如其名,子进程接口。
from sh import ifconfig
print(ifconfig("wlan0"))
purl
github: https://github.com/codeinthehole/purl
拥有简洁接口的URL处理器:
>>> from purl import URL
>>> from_str = URL('https://www.google.com/search?q=testing')
>>> u.query_param('q')
u'testing'
>>> u.host()
u'www.google.com'
path.py
github: https://github.com/jaraco/path.py
一个文件系统处理库,不过目前还在开发阶段
from path import path
d = path('/home/guido/bin')
for f in d.files('*.py'):
f.chmod(0755)
Peewee
https://github.com/coleifer/peewee
小型ORM, 接口很漂亮:
# get tweets by editors ("<<" maps to IN)
Tweet.select().where(Tweet.user << editors)
# how many active users are there?
User.select().where(User.active == True).count()
类似的我的 CURD.py (https://github.com/hit9/CURD.py) :)
User.create(name="John", email="John@gmail.com") # create
User.at(2).update(email="John@github.com") # update
John = User.where(name="John").select().fetchone() # read
# who wrote posts?
for post, user in (Post & User).select().fetchall():
print "Author: %s, PostName: %s" % (user.name, post.name)
Pony ORM
https://github.com/ponyorm/pony
一个十分独特的ORM,接口简单干净,最大的特点是支持使用generator的语法来进行查询,可以使查询语句变得简洁,灵活,而且漂亮。
例如可以使用如下的语句来进行一个查询:
select(p for p in Product if p.name.startswith('A') and p.cost <= 1000)
同时,Pony ORM还提供了一个ER图编辑工具来进行数据库原型设计。
schema
https://github.com/halst/schema
同样是docopt的作者编写的,一个数据格式检查库,非常新颖:
>>> from schema import Schema
>>> Schema(int).validate(123)
123
>>> Schema(int).validate('123')
Traceback (most recent call last):
...
SchemaError: '123' should be instance of <type 'int'>
Traceback (most recent call last):
...
SchemaError: '123' should be instance of <type 'int'>
fn.py
https://github.com/kachayev/fn.py
增强Python的函数式编程:
from fn import _
print (_ + 2) # "(x1) => (x1 + 2)"
print (_ + _ * _) # "(x1, x2, x3) => (x1 + (x2 * x3))"
when.py
https://github.com/dirn/When.py
友好的时间日期库:
>>> import when
>>> when.timezone()
'Asia/Shanghai'
>>> when.today()
datetime.date(2013, 5, 14)
>>> when.tomorrow()
datetime.date(2013, 5, 15)
>>> when.now()
datetime.datetime(2013, 5, 14, 21, 2, 23, 78838)
clize
用 docopt 写程序的使用doc是不是很爽, clize是一个类似的库。可以用程序的函数名字来作为使用方法
#!/usr/bin/env python
from clize import clize
@clize
def echo(text, reverse=false):
if reverse:
text = text[::-1]
print(text)
if __name__ == '__main__':
import sys
echo(*sys.argv)
而这个小程序就可以这么使用:
$ ./echo.py --help
Usage: ./echo.py [OPTIONS] text
Positional arguments:
text
Options:
--reverse
-h, --help Show this help
Github上Python开发者应该关心的Repo
carbaugh/lice
lice : Generate license files for your projects
一个用来为你的项目生成许可证的工具。这下可方便了,不用手工的去修改了!
coleifer/peewee
peewee: a small, expressive orm – supports postgresql, mysql and sqlite
你在用SQLAlchemy ? 我强烈推荐你看下peewee
来看一个sample:
User.select().where(User.active == True).order_by(User.username)
一个单文件的Python ORM.相当轻巧,支持三个数据库。而且,它最讨人喜欢的是它的轻量级的语法。
docopt/docopt
docopt : Pythonic command line arguments parser, that will make you smile
用过doctest? 那来看看docopt。有时候你用py写一个命令行程序,需要接收命令行参数,看看这个例子:
"""
Usage: test.py <file> [--verbose]
"""
from docopt import docopt
print docopt(__doc__)
如果你这么执行程序:
python test.py somefile --verbose
你会得到这样的输出:
{'--verbose': True, '<file>': 'somefile'}
hhatto/autopep8
autopep8 : A tool that automatically formats Python code to conform to the PEP 8 style guide.
每个Python程序员都应该checkout的repo.自动的把你的Python代码转成符合PEP8风格的代码.
使用 -i 参数来直接修改你的 Python文件:
autopep8 -i mycode.py
kachayev/fn.py
fn.py : Functional programming in Python: implementation of missing features to enjoy FP
这是个很有趣的项目,来弥补Python在函数式编程方面没有的一些特性。来看个sample:
from fn import _
assert list(map(_ * 2, range(5))) == [0,2,4,6,8]
nose-devs/nose
nose : nose is nicer testing for python
或许nose已经不是新鲜的测试框架了,现在还有很多新的测试框架诞生,不过大家都在用它,而且似乎没要离开nose的意思。
amoffat/sh
sh : Python subprocess interface
这个库已经被津津乐道很久了。看代码:
from sh import git
git.clone("https://github.com/amoffat/sh")
是不是比 os.system 更简洁明了。
Lokaltog/powerline
如果你是个linux(or mac)下的开发者,又喜欢在终端下工作的话,你一定喜欢用powerline来美化自己的工作空间。
之前github上兴起了vim-powerline,tmux-powerline,还有powerline-bash,现在Lokaltog提供了一个统一的解决方案,只要安装这个python包,再追加些东西到配置文件就可以使用漂亮的powerline了
具体的效果请见repo : https://github.com/Lokaltog/powerline
faif/python-patterns
python-patterns : A collection of design patterns implemented (by other people) in python
这个repo收集了很多设计模式的python写法
gutworth/six/
six : Six is a Python 2 and 3 compatibility library
Six没有托管在Github上,而是托管在了Bitbucket上,不过这些都不是重点,重点是它的作用。
众所周知 Python 2 和 Python 3 版本的分裂给 Python 开发者们带来了很大的烦恼,为了使代码同时兼容两个版本,往往要增加大量的代码。 于是 Six 出现了。正如它的介绍所说,它是一个专门用来兼容 Python 2 和 Python 3 的库。它解决了诸如 urllib 的部分方法不兼容, str 和 bytes 类型不兼容等“知名”问题。
它的效果怎么样?pypi上单日十万以上,单月几百万的下载量足以说明了。要知道诸如 Flask 和 Django 这类知名的库,月下载量也只有几十万。
你可能没听过的11个Python库
1) delorean
Dolorean是一个非常酷的日期/时间库。类似JavaScript的moment,拥有非常完善的技术文档。
- from delorean import Delorean
- EST = "US/Eastern"
- d = Delorean(timezone=EST)
2) prettytable
你可能从未听过该库,因为它托管在GoogleCode。prettytable主要用于在终端或浏览器端构建很好的输出。
- from prettytable import PrettyTable
- table = PrettyTable(["animal", "ferocity"])
- table.add_row(["wolverine", 100])
- table.add_row(["grizzly", 87])
- table.add_row(["Rabbit of Caerbannog", 110])
- table.add_row(["cat", -1])
- table.add_row(["platypus", 23])
- table.add_row(["dolphin", 63])
- table.add_row(["albatross", 44])
- table.sort_key("ferocity")
- table.reversesort = True
- +----------------------+----------+
- | animal | ferocity |
- +----------------------+----------+
- | Rabbit of Caerbannog | 110 |
- | wolverine | 100 |
- | grizzly | 87 |
- | dolphin | 63 |
- | albatross | 44 |
- | platypus | 23 |
- | cat | -1 |
- +----------------------+----------+
好吧,我也是首次安装该库。这是一款非常瘦小的语言转换库,支持15种语言。
- from snowballstemmer import EnglishStemmer, SpanishStemmer
- EnglishStemmer().stemWord("Gregory")
- # Gregori
- SpanishStemmer().stemWord("amarillo")
- # amarill
4.wget
你是否还记得,每一次都会因为某个目的而编写网络爬虫工具,以后再也不用了,因为wget就足够你使用了。wget是Python版的网络爬虫库,简单好用。
- import wget
- wget.download("http://www.cnn.com/")
- # 100% [............................................................................] 280385 / 280385
5.PyMC
scikit-learn似乎是所有人的宠儿,但在我看来,PyMC更有魅力。PyMC主要用来做Bayesian分析。
- from pymc.examples import disaster_model
- from pymc import MCMC
- M = MCMC(disaster_model)
- M.sample(iter=10000, burn=1000, thin=10)
- [-----------------100%-----------------] 10000 of 10000 complete in 1.4 sec
6.sh
sh库用来将shell命令作为函数导入到Python中。在bash中使用是非常实用的,但是在Python中不容易记住怎么使用(即递归搜索文件)。
- from sh import find
- find("/tmp")
- /tmp/foo
- /tmp/foo/file1.json
- /tmp/foo/file2.json
- /tmp/foo/file3.json
- /tmp/foo/bar/file3.json
Fuzzywuzzy是一个可以对字符串进行模糊匹配的库,大家有空可以去 查看源码。
- from fuzzywuzzy import fuzz
- fuzz.ratio("Hit me with your best shot", "Hit me with your pet shark")
- # 85
progressbar是一个进度条库,该库提供了一个文本模式的progressbar。
- from progressbar import ProgressBar
- import time
- pbar = ProgressBar(maxval=10)
- for i in range(1, 11):
- pbar.update(i)
- time.sleep(1)
- pbar.finish()
- # 60% |######################################################## |
9.colorama
colorama主要用来给文本添加各种颜色,并且非常简单易用。
10.uuid
uuid是基于Python实现的UUID库,它实现了UUID标注的1,3,4和5版本,在确保唯一性上真的非常方便。
- import uuid
- print uuid.uuid4()
- # e7bafa3d-274e-4b0a-b9cc-d898957b4b61
bashplotlib是一个绘图库,它允许你使用stdin绘制柱状图和散点图等。
- $ pip install bashplotlib
- $ scatter --file data/texas.txt --pch x
[英文原文: 11 Python Libraries You Might Not Know]
哪些 Python 库让你相见恨晚?
Watchdog:Watchdog — watchdog 0.8.0 documentation监视文件系统改动。
Path:API — path.py 5.2 documentation简化文件系统相关操作。
- lxml提供的xpath解析器来解析HTML。xpath是一套标准的HTML DOM查询语法,再不用Beaultiful Soup4那么罗嗦又不好维护的语法了。而且最棒的是你可以直接从Firefox或者Chrome的development tool里复制某个DOM元素的xpath路径。其他不论,光lxml使用C实现的代码,效率上就比bs4高很多。用过之后再也不想去用bs4了。
Sphinx 爱上写文档 What users say:“Cheers for a great tool that actually makes programmers want to write documentation!”
微信框架:
网络:
爬虫:
- scrapy
-
爬虫:requests + lxml (取代urllib2 + BeautifulSoup)
ORM:
模板引擎:
图像处理:
命令行应用:
静态网站生成器 数据处理:
其他:
docopt,替代argparse,简洁明快。最关键的是它的思路完全不同。
that make use of innovative user interfaces, such as multi-touch apps.
from:http://blog.csdn.net/pipisorry/article/details/47185795
ref:TOP 10 PYTHON LIBRARIES OF 2015