python的sh库使用案例

发布在 Python

sh 可让你调用任意程序,就好象是一个函数一般 http://amoffat.github.io/sh/

这里我用unzip以及mv为例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#coding=utf-8
'''
@CreateDate: Fri Feb 14 15:48:13 CST 2014
@FileName:unzip.py
@Description:负责解压并重命名聊天记录
'''
import os
from sh import unzip,mv
def myunzip():
'''只负责解压'''
path = os.getcwd()
path = "%s/%s" % (path,"qqfile")
for root,dirs,files in os.walk(path):
#print root,type(dirs)
for fn in files:
if fn.endswith(".zip"):
zippath = os.path.join(root,fn)
abs_zippath = os.path.join(root,fn.replace(".zip",""))
print zippath,abs_zippath
unzip(zippath,d=abs_zippath)
def rename():
'''只负责把解压出来的txt重命名'''
path = os.getcwd()
path = "%s/%s" % (path,"qqfile")
for root,dirs,files in os.walk(path):
for fn in files:
if fn.endswith(".txt"):
filename = root.split("/")[-1]
old = os.path.join(root,fn)
new = "%s/%s.txt" % (root,filename)
mv(old,new)
if __name__ == "__main__":
myunzip()
#rename()

评论和分享

django数据库分库

发布在 Django

有些时候我们需要项目中的app访问不同的数据库,这时就要进行分库操作。

首先建立一个db_router.py,内容示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#coding=utf-8
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'xxxx', # Or path to database file if using sqlite3.
'USER': 'root', # Not used with sqlite3.
'PASSWORD': '123456', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '3306', # Set to empty string for default. Not used with sqlite3.
'OPTIONS': {
'init_command': 'SET storage_engine=MyISAM',
},
},
'analysis_db':{
'ENGINE': 'django.db.backends.mysql',
'NAME': 'analysis_qq', #分析相关的操作用这个库
'HOST': '',
'USER': 'root',
'PASSWORD': '123456',
'PORT':'3306',
'OPTIONS':{
'init_command': 'SET storage_engine=MyISAM',
},
},
}
class MasterSlaveRouter(object):
def db_for_read(self, model, **hints):
if model._meta.app_label == 'analysisqq':
return 'analysis_db'
else:
return 'default'
def db_for_write(self, model, **hints):
if model._meta.app_label == 'analysisqq':
return 'analysis_db'
else:
return 'default'
def allow_relation(self, obj1, obj2, **hints):
db_list = ('default','analysis_db',)
if obj1._state.db in db_list and obj2._state.db in db_list:
return True
return None
def allow_syncdb(self, db, model):
if db == 'analysis_db':
print " in analysis db"
return True
elif db == 'default':
return False
else:
return None
DATABASE_ROUTERS = ['db_router.MasterSlaveRouter']

然后在settings.py中删除和数据库相关的代码,添加from db_router import *,这样之后指定的app就会使用特定的库了。

注意,这里分库是针对于读写操作,以及default已经存在后的syncdb,如果说你想执行syncdb同时就在不同数据库建表,这样操作是无效的。知道怎么做的请告知!

评论和分享

  • 第 1 页 共 1 页
作者的图片

Roy

微信公众号:hi-roy


野生程序猿


China