0%

  • 这将会在你的当前目录下生成一个 mysite 目录

admin startproject mysite

新建数据库

  • 配置mysite下的setting.py中的数据库设置
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    DATABASES = {
    'default': {
    'ENGINE': 'django.db.backends.mysql',
    'NAME': 'test', #数据库名字
    'USER': 'root',
    'PASSWORD': '',
    'HOST': '127.0.0.1',
    'PORT': '3306',
    }
    }
  • 安装py3驱动mysql
    1
    pip install PyMySQL
    找到mysite/mysite/init.py,在里面输入以下内容并保存:
    1
    2
    import pymysql
    pymysql.install_as_MySQLdb()
  • 执行下列命令
    1
    python manage.py runserver
    就会看到如下所示:
    1
    2
    3
    4
    5
    6
    7
    8
    System check identified no issues (0 silenced).

    You have 13 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
    Run 'python manage.py migrate' to apply them.
    February 06, 2017 - 14:47:11
    Django version 1.10.5, using settings 'mysite.settings'
    Starting development server at http://127.0.0.1:8000/
    Quit the server with CTRL-BREAK.
  • 浏览器打开后出现个异常提示:
    1
    2
    Of course, you haven't actually done any work yet. Next, start your first app by running python manage.py startapp [app_label].
    You're seeing this message because you have DEBUG = True in your Django settings file and you haven't configured any URLs. Get to work!
  • 设置setting.py
    1
    2
    DEBUG = False
    ALLOWED_HOSTS = ['*']

最后再次运行:

1
2
python manage.py runserver

类视图如下

本文来自:http://www.wmhfly.com/php/python3-mysql-class.html

我自己改造了一次,加入到自己的自动化接口测试框架里面:

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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
  FIND_BY_SQL = "findBySql" # 根据sql查找
COUNT_BY_SQL = "countBySql" # 自定义sql 统计影响行数
INSERT = "insert" # 插入
UPDATE_BY_ATTR = "updateByAttr" # 更新数据
DELETE_BY_ATTR = "deleteByAttr" # 删除数据
FIND_BY_ATTR = "findByAttr" # 根据条件查询一条记录
FIND_ALL_BY_ATTR = "findAllByAttr" #根据条件查询多条记录
COUNT = "count" # 统计行
EXIST = "exist" # 是否存在该记录


import mysql.connector
import mysql.connector.errors
from common.customConst import Const
class MySQLet:
"""Connection to a MySQL"""
# def __init__(self,user='',password='',database='',charset=None,port=3306):
def __init__(self,**kwargs):
try:
self._conn = mysql.connector.connect(host=kwargs["host"], user=kwargs["user"], password=kwargs["password"],
charset=kwargs["charset"], database=kwargs["database"], port=kwargs["port"])
self.__cursor = None
print("连接数据库")
#set charset charset = ('latin1','latin1_general_ci')
except mysql.connector.errors.ProgrammingError as err:
print('mysql连接错误:' + err.msg)

# def findBySql(self, sql, params={}, limit=0, join='AND'):
def findBySql(self, **kwargs):
"""
自定义sql语句查找
limit = 是否需要返回多少行
params = dict(field=value)
join = 'AND | OR'
"""
cursor = self.__getCursor()
# sql = self.__joinWhere(kwargs["sql"], kwargs["params"], kwargs["join"])
if kwargs.get("join", 0) == 0: kwargs["join"] = "AND"
sql = self.__joinWhere(**kwargs)
cursor.execute(sql, tuple(kwargs["params"].values()))
rows = cursor.fetchmany(size=kwargs["limit"]) if kwargs["limit"] > 0 else cursor.fetchall()
result = [dict(zip(cursor.column_names,row)) for row in rows] if rows else None
return len(result)

# def countBySql(self,sql,params = {},join = 'AND'):
def countBySql(self, **kwargs):
"""自定义sql 统计影响行数"""
if kwargs.get("join", 0) == 0: kwargs["join"] = "AND"
cursor = self.__getCursor()
# sql = self.__joinWhere(kwargs["sql"], kwargs["params"], kwargs["join"])
sql = self.__joinWhere(**kwargs)
cursor.execute(sql, tuple(kwargs["params"].values()))
result = cursor.fetchall() # fetchone是一条记录, fetchall 所有记录
return len(result) if result else 0

# def insert(self,table,data):
def insert(self, **kwargs):
"""新增一条记录
table: 表名
data: dict 插入的数据
"""
fields = ','.join('`'+k+'`' for k in kwargs["data"].keys())
values = ','.join(("%s", ) * len(kwargs["data"]))
sql = 'INSERT INTO `%s` (%s) VALUES (%s)' % (kwargs["table"], fields, values)
cursor = self.__getCursor()
cursor.execute(sql, tuple(kwargs["data"].values()))
insert_id = cursor.lastrowid
self._conn.commit()
return insert_id

# def updateByAttr(self,table,data,params={},join='AND'):
def updateByAttr(self, **kwargs):
# """更新数据"""
if kwargs.get("params", 0) == 0:
kwargs["params"] = {}
if kwargs.get("join", 0) == 0:
kwargs["join"] = "AND"
fields = ','.join('`' + k + '`=%s' for k in kwargs["data"].keys())
values = list(kwargs["data"].values())


values.extend(list(kwargs["params"].values()))
sql = "UPDATE `%s` SET %s " % (kwargs["table"], fields)
kwargs["sql"] = sql
sql = self.__joinWhere(**kwargs)
cursor = self.__getCursor()
cursor.execute(sql, tuple(values))
self._conn.commit()
return cursor.rowcount


# def updateByPk(self,table,data,id,pk='id'):
def updateByPk(self, **kwargs):
"""根据主键更新,默认是id为主键"""
return self.updateByAttr(**kwargs)

# def deleteByAttr(self,table,params={},join='AND'):
def deleteByAttr(self, **kwargs):
"""删除数据"""
if kwargs.get("params", 0) == 0:
kwargs["params"] = {}
if kwargs.get("join", 0) == 0:
kwargs["join"] = "AND"
# fields = ','.join('`'+k+'`=%s' for k in kwargs["params"].keys())
sql = "DELETE FROM `%s` " % kwargs["table"]
kwargs["sql"] = sql
# sql = self.__joinWhere(sql, kwargs["params"], kwargs["join"])
sql = self.__joinWhere(**kwargs)
cursor = self.__getCursor()
cursor.execute(sql, tuple(kwargs["params"].values()))
self._conn.commit()
return cursor.rowcount

# def deleteByPk(self,table,id,pk='id'):
def deleteByPk(self, **kwargs):
"""根据主键删除,默认是id为主键"""
return self.deleteByAttr(**kwargs)

# def findByAttr(self,table,criteria = {}):
def findByAttr(self, **kwargs):
"""根據條件查找一條記錄"""
return self.__query(**kwargs)

# def findByPk(self,table,id,pk='id'):
def findByPk(self, **kwargs):
return self.findByAttr(**kwargs)

# def findAllByAttr(self,table,criteria={}, whole=true):
def findAllByAttr(self, **kwargs):
"""根據條件查找記錄"""
return self.__query(**kwargs)

# def count(self,table,params={},join='AND'):
def count(self, **kwargs):
"""根据条件统计行数"""
if kwargs.get("join", 0) == 0: kwargs["join"] = "AND"
sql = 'SELECT COUNT(*) FROM `%s`' % kwargs["table"]
# sql = self.__joinWhere(sql, kwargs["params"], kwargs["join"])
kwargs["sql"] = sql
sql = self.__joinWhere(**kwargs)
cursor = self.__getCursor()
cursor.execute(sql, tuple(kwargs["params"].values()))
result = cursor.fetchone()
return result[0] if result else 0

# def exist(self,table,params={},join='AND'):
def exist(self, **kwargs):
"""判断是否存在"""
return self.count(**kwargs) > 0

def close(self):
"""关闭游标和数据库连接"""
if self.__cursor is not None:
self.__cursor.close()
self._conn.close()

def __getCursor(self):
"""获取游标"""
if self.__cursor is None:
self.__cursor = self._conn.cursor()
return self.__cursor

# def __joinWhere(self,sql,params,join):
def __joinWhere(self, **kwargs):
"""转换params为where连接语句"""
if kwargs["params"]:
keys,_keys = self.__tParams(**kwargs)
where = ' AND '.join(k+'='+_k for k,_k in zip(keys,_keys)) if kwargs["join"] == 'AND' else ' OR '.join(k+'='+_k for k,_k in zip(keys,_keys))
kwargs["sql"]+=' WHERE ' + where
return kwargs["sql"]

# def __tParams(self,params):
def __tParams(self, **kwargs):
keys = ['`'+k+'`' for k in kwargs["params"].keys()]
_keys = ['%s' for k in kwargs["params"].keys()]
return keys,_keys

# def __query(self,table,criteria,whole=False):
def __query(self, **kwargs):
if kwargs.get("whole", False) == False or kwargs["whole"] is not True:
kwargs["whole"] = False
kwargs["criteria"]['limit'] = 1
# sql = self.__contact_sql(kwargs["table"], kwargs["criteria"])
sql = self.__contact_sql(**kwargs)
cursor = self.__getCursor()
cursor.execute(sql)
rows = cursor.fetchall() if kwargs["whole"] else cursor.fetchone()
result = [dict(zip(cursor.column_names, row)) for row in rows] if kwargs["whole"] else dict(zip(cursor.column_names, rows)) if rows else None
return result

# def __contact_sql(self,table,criteria):
def __contact_sql(self, **kwargs):
sql = 'SELECT '
if kwargs["criteria"] and type(kwargs["criteria"]) is dict:
#select fields
if 'select' in kwargs["criteria"]:
fields = kwargs["criteria"]['select'].split(',')
sql+= ','.join('`'+field+'`' for field in fields)
else:
sql+=' * '
#table
sql+=' FROM `%s`'% kwargs["table"]
#where
if 'where' in kwargs["criteria"]:
sql+=' WHERE '+ kwargs["criteria"]['where']
#group by
if 'group' in kwargs["criteria"]:
sql+=' GROUP BY '+ kwargs["criteria"]['group']
#having
if 'having' in kwargs["criteria"]:
sql+=' HAVING '+ kwargs["criteria"]['having']
#order by
if 'order' in kwargs["criteria"]:
sql+=' ORDER BY '+ kwargs["criteria"]['order']
#limit
if 'limit' in kwargs["criteria"]:
sql+=' LIMIT '+ str(kwargs["criteria"]['limit'])
#offset
if 'offset' in kwargs["criteria"]:
sql+=' OFFSET '+ str(kwargs["criteria"]['offset'])
else:
sql+=' * FROM `%s`'% kwargs["table"]
return sql
def findKeySql(self, key ,**kwargs):
sqlOperate = {
Const.COUNT: lambda: self.count(**kwargs),
Const.COUNT_BY_SQL: lambda: self.countBySql(**kwargs),
Const.DELETE_BY_ATTR: lambda: self.deleteByAttr(**kwargs),
Const.EXIST: lambda: self.exist(**kwargs),
Const.FIND_ALL_BY_ATTR: lambda: self.findAllByAttr(**kwargs),
Const.INSERT: lambda: self.insert(**kwargs),
Const.FIND_BY_ATTR: lambda: self.findByAttr(**kwargs),
Const.UPDATE_BY_ATTR: lambda: self.updateByAttr(**kwargs),
Const.FIND_BY_SQL: lambda: self.findBySql(**kwargs)

}
return sqlOperate[key]()


if __name__ == "__main__":
mysqlet = MySQLet(host="127.0.0.1", user="root", password="", charset="utf8", database="userinfo", port=3306)
# 根据字段统计count, join>>AND,OR,可以不传,默认为AND
print(mysqlet.findKeySql(Const.COUNT, table="info", params={"id": "11", "name": "666"}, join="OR"))
# 自定义sql语句统计count
print(mysqlet.findKeySql(Const.COUNT_BY_SQL, sql="select * from info", params={"name": "666"}, join="AND"))
#插入数据
print(mysqlet.findKeySql(Const.INSERT, table="info", data={"name":"333", "pwd": "111"}))
#根据字段删除,不传params参数,就是删除全部
print(mysqlet.findKeySql(Const.DELETE_BY_ATTR, table="info", params={"id": 20}))
# 查找是否存在该记录,不传params参数,就是查找全部.join同上
print(mysqlet.findKeySql(Const.EXIST, table="info", params={"id": 180},join='AND'))
#根据字段查找多条记录,whole不传就查一条记录,criteria里面可以传where,group by,having,order by,limt,offset
print(mysqlet.findKeySql(Const.FIND_ALL_BY_ATTR, table="info", criteria= {"where": "name=333"}, whole=True))
# 根据字段查一条记录,和上面的查多条记录参数基本一样,少了个whole参数
print(mysqlet.findKeySql(Const.FIND_BY_ATTR, table="info", criteria= {"where": "name=333"}))
# 根据字段更新数据库中的记录,join可以传AND,OR,不传默认取AND
print(mysqlet.findKeySql(Const.UPDATE_BY_ATTR, table="info",data={"name": "-09"}, params={"id": 18, "name": "333"}, join='AND'))
# 根据自定义sql语句查询记录,limit:0表示所有记录,join:AND|OR.不传取AND
print(mysqlet.findKeySql(Const.FIND_BY_SQL, sql="select * from info", params={"name": "333", "id": 18}, limit=0))

  • http简单封装

    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
    class ConfigHttp:
    def __init__(self, host, port,headers):
    self.host = host
    self.port = port
    self.headers = headers
    # 封装HTTP GET请求方法
    def get(self, url, params=None):
    # params = urllib.parse.urlencode(params)
    url = "http://"+self.host+":"+self.port+url
    print(url)
    try:
    r = requests.get(url, params=params, headers=self.headers)
    r.encoding = 'UTF-8'
    dcit_r = json.loads(r.text)
    print(json.loads(r.text))
    return dcit_r
    except Exception:
    print('no json data returned')
    return {}
    # 封装HTTP POST请求方法,支持上传图片
    def post(self, url, data=None, files=None):
    # data = eval(data)
    url = 'http://' + self.host + ':' + str(self.port)+url
    r =requests.post(url, files=files, data=data)
    json_response = r.text
    print(json_response)
    return json_response
  • 上传视频

    1
    2
    3
    4
    5
    6
    7
    8
    9
    def upload():
    getToken()
    f = {'Filename':'视频上传测试1',
    'Filedata':('1.mp4',open(u'D:/app/dgm/1.mp4','rb'),'application/octet-stream'),
    'Upload':'视频上传测试2'
    }
    up = baseHttp.ConfigHttp(host=UPLOAD_HOST,port=UPLOAD_PORT,headers=HEADER)
    url = "/api/upload?do=upload&type=4&op=video&sid="+CODE +"&token=" + TOKEN
    res = up.post(url=url, files=f)

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

class MyClass(object):
def __init__(self):
self.ids = "001"

def t1(self, path=""):
print("这个是实例化方法")

@staticmethod
def get_result(path):
print("这个是静态方法")
MyClass().t1() # 显示调用类的实例化方法
print(MyClass().ids)

@classmethod
def get_test1(cls, path):
print("这个是类方法")
cls().t1() # 调用类的实例化方法
print(cls().ids)


MyClass().t1("调用实例化方法")
MyClass.get_result("调用静态方法")
MyClass.get_test1("调用类方法")

总结

  • 类中一般包含三种方法
    • 实例化方法(MyClass().t1()
    • 静态方法(staticmethod
    • 类方法(classmethod
  • classmethod(类方法),第一个参数必须是cls,这个cls指向了类本身,因此可以直接用cls实例化来访问类的内部方法或者属性。
    • cls().t1()
  • staticmethod(静态方法),如果要调用类的内部方法,只能显示地引用类MyClass,这对继承来说可不是一件好事情
    • MyClass().t1()

因此

  • 只要不调用类的内部方法和属性,classmethodstaticmethod都可以使用
  • 若要调用类的内部方法和属性,推荐使用classmethod

1
2
3
class Count():
def add(self):
pass
  • 用mock测试
1
2
3
4
5
6
7
8
9
10
11
12
13
14
from unittest import mock
import unittest
from modular import Count
class TestCount(unittest.TestCase):

def test_add(self):
count = Count()
count.add = mock.Mock(return_value=13)
result = count.add(8,5)
self.assertEqual(result,13)


if __name__ == '__main__':
unittest.main()

HTTPretty

Python 的 HTTP 请求 mock 工具,不支持py3

  • 安装
1
pip install HTTPretty
  • 使用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import requests
import httpretty

def test_one():
httpretty.enable() # enable HTTPretty so that it will monkey patch the socket module
httpretty.register_uri(httpretty.GET, "http://yipit.com/",
body="Find the best daily deals")

response = requests.get('http://yipit.com')

assert response.text == "Find the best daily deals"

httpretty.disable() # disable afterwards, so that you will have no problems in code that uses that socket module
httpretty.reset() # reset H
  • post
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import requests
from sure import expect
import httpretty


@httpretty.activate
def test_yipit_api_integration():
httpretty.register_uri(httpretty.POST, "http://api.yipit.com/foo/",
body='{"repositories": ["HTTPretty", "lettuce"]}')

response = requests.post('http://api.yipit.com/foo',
'{"username": "gabrielfalcao"}',
headers={
'content-type': 'text/json',
})

expect(response.text).to.equal('{"repositories": ["HTTPretty", "lettuce"]}')
expect(httpretty.last_request().method).to.equal("POST")
expect(httpretty.last_request().headers['content-type']).to.equal('text/json')
  • 也可以使用正则
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    @httpretty.activate
    def test_httpretty_should_allow_registering_regexes():
    u"HTTPretty should allow registering regexes"

    httpretty.register_uri(
    httpretty.GET,
    re.compile("api.yipit.com/v2/deal;brand=(\w+)"),
    body="Found brand",
    )

    response = requests.get('https://api.yipit.com/v2/deal;brand=GAP')
    expect(response.text).to.equal('Found brand')
    expect(httpretty.last_request().method).to.equal('GET')
    expect(httpretty.last_request().path).to.equal('/v1/deal;brand=GAP')

查看HTTPretty源码

httmock

针对 Python 2.6+ 和 3.2+ 生成 伪造请求的库。

  • 安装

    1
    pip install httmock
  • 使用

1
2
3
4
5
6
7
8
9
10
from httmock import urlmatch, HTTMock
import requests

@urlmatch(netloc=r'(.*\.)?google\.com$')
def google_mock(url, request):
return 'Feeling lucky, punk?'

with HTTMock(google_mock):
r = requests.get('http://google.com/')
print r.content # 'Feeling lucky, punk?'
1
2
3
4
5
6
7
8
9
10
11
12
13
from httmock import all_requests, HTTMock
import requests

@all_requests
def response_content(url, request):
return {'status_code': 200,
'content': 'Oh hai'}

with HTTMock(response_content):
r = requests.get('https://foo_bar')

print r.status_code
print r.content
  • cookie
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from httmock import all_requests, response, HTTMock
import requests

@all_requests
def response_content(url, request):
headers = {'content-type': 'application/json',
'Set-Cookie': 'foo=bar;'}
content = {'message': 'API rate limit exceeded'}
return response(403, content, headers, None, 5, request)

with HTTMock(response_content):
r = requests.get('https://api.github.com/users/whatever')

print r.json().get('message')
print r.cookies['foo']

查看httmock源码

map函数

  • map函数会根据提供的函数对指定序列做映射。

  • map函数的定义:map(function, sequence[, sequence, …]) -> list

    • 通过定义可以看到,这个函数的第一个参数是一个函数,剩下的参数是一个或多个序列,返回值是一个集合。
      function可以理解为是一个一对一或多对一函数,map的作用是以参数序列中的每一个元素调用function函数,返回包含每次function函数返回值的list。

    lambda 结合的例子

1
2
3
map(lambda x: x ** 2, [1, 2, 3, 4, 5])
返回结果为:
[1, 4, 9, 16, 25]

单参数例子

1
2
3
4
5
6
def add100(x):
return x+100

hh = [11,22,33]
map(add100,hh)
[111, 122, 133]
  • ** list参数的例子**
    1
    2
    3
    4
    5
    6
    7
    8
    >>> def abc(a, b, c):
    ... return a*10000 + b*100 + c
    ...
    >>> list1 = [11,22,33]
    >>> list2 = [44,55,66]
    >>> list3 = [77,88,99]
    >>> map(abc,list1,list2,list3)
    [114477, 225588, 336699]
  • function为None的例子
    1
    2
    3
    4
    5
    6
    7
    8
    >>> list1 = [11,22,33]
    >>> map(None,list1)
    [11, 22, 33]
    >>> list1 = [11,22,33]
    >>> list2 = [44,55,66]
    >>> list3 = [77,88,99]
    >>> map(None,list1,list2,list3)
    [(11, 44, 77), (22, 55, 88), (33, 66, 99)]

filter函数

  • filter函数会对指定序列执行过滤操作。
  • filter函数的定义:filter(function or None, sequence) -> list, tuple, or string
    • function是一个谓词函数,接受一个参数,返回布尔值True或False。

    • filter函数会对序列参数sequence中的每个元素调用function函数,最后返回的结果包含调用结果为True的元素。返回值的类型和参数sequence的类型相同

    • 返回序列中的所有奇数

1
2
3
4
5
def is_even(x):
return x & 1 != 0
filter(is_even, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
返回结果为:
[1, 3, 5, 7, 9]
  • 如果function参数为None,返回结果和sequence参数相同。

reduce函数

  • reduce函数,reduce函数会对参数序列中元素进行累积。
  • py3以后使用,必须导入 from functools import reduce
  • reduce函数的定义:reduce(function, sequence[, initial]) -> value
    • function参数是一个有两个参数的函数,reduce依次从sequence中取一个元素,和上一次调用function的结果做参数再次调用function。
      第一次调用function时,如果提供initial参数,会以sequence中的第一个元素和initial作为参数调用function,否则会以序列sequence中的前两个元素做参数调用function。

    • 累加例子

1
2
3
4
5
def myadd(x,y):  
return x+y
sum=reduce(myadd,(1,2,3,4,5,6,7))
print(sum)
#结果就是输出1+2+3+4+5+6+7的结果即28
  • lambda 结合的例子
1
2
3
4
reduce(lambda x, y: x + y, [2, 3, 4, 5, 6], 1)
结果为21( (((((1+2)+3)+4)+5)+6) )
reduce(lambda x, y: x + y, [2, 3, 4, 5, 6])
结果为20
  • 注意function函数不能为None。

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
import xlrd  # 导入模块
from xlutils.copy import copy # 导入copy模块

class EditExcel():

def __init__(self, path, sheet_name):
self.path = path
self.sheet_name = sheet_name

def get_excel_sheet(self):
# 打开excel
read_open_xls = xlrd.open_workbook(self.path)
# 得到excel中的sheet_name
read_xlsx_sheet = read_open_xls.sheet_by_name(self.sheet_name)
# 拷贝excel
copy_book = copy(read_open_xls)
return copy_book, read_xlsx_sheet,

def write_value(self):
copy_book, read_xlsx_sheet = self.get_excel_sheet()
# 获取行数
row_max = read_xlsx_sheet.nrows
# 获取第一行的值
rows = read_xlsx_sheet.row_values(0)
# 获取列数
col_max = read_xlsx_sheet.ncols
for row in range(row_max):
row_value = read_xlsx_sheet.row_values(row)
for col in range(col_max):
current_value = read_xlsx_sheet.cell(row, col).value
# 按照条件过滤
if current_value == 'Pass':
copy_sheet = copy_book.get_sheet(0)
copy_sheet.write(row, col, '11111')
copy_book.save(self.path)


EditExcel("test.xls", "Sheet1").write_value()

注意

  • 不支持xlsx文件的修改,只支持xls

sql注入

网络

  • Scapy: send, sniff and dissect and forge network packets. Usable interactively or as a library
  • pypcapPcapy and pylibpcap: several different Python bindings for libpcap
  • libdnet: low-level networking routines, including interface lookup and Ethernet frame transmission
  • dpkt: fast, simple packet creation/parsing, with definitions for the basic TCP/IP protocols
  • Impacket: craft and decode network packets. Includes support for higher-level protocols such as NMB and SMB
  • pynids: libnids wrapper offering sniffing, IP defragmentation, TCP stream reassembly and port scan detection
  • Dirtbags py-pcap: read pcap files without libpcap
  • flowgrep: grep through packet payloads using regular expressions
  • Knock Subdomain Scan, enumerate subdomains on a target domain through a wordlist
  • Mallory, extensible TCP/UDP man-in-the-middle proxy, supports modifying non-standard protocols on the fly
  • Pytbull: flexible IDS/IPS testing framework (shipped with more than 300 tests)

调试和逆向工程

  • Paimei: reverse engineering framework, includes PyDBG, PIDA, pGRAPH
  • Immunity Debugger: scriptable GUI and command line debugger
  • mona.py: PyCommand for Immunity Debugger that replaces and improves on pvefindaddr
  • IDAPython: IDA Pro plugin that integrates the Python programming language, allowing scripts to run in IDA Pro
  • PyEMU: fully scriptable IA-32 emulator, useful for malware analysis
  • pefile: read and work with Portable Executable (aka PE) files
  • pydasm: Python interface to the libdasm x86 disassembling library
  • PyDbgEng: Python wrapper for the Microsoft Windows Debugging Engine
  • uhooker: intercept calls to API calls inside DLLs, and also arbitrary addresses within the executable file in memory
  • diStorm: disassembler library for AMD64, licensed under the BSD license
  • python-ptrace: debugger using ptrace (Linux, BSD and Darwin system call to trace processes) written in Python
  • vdb / vtrace: vtrace is a cross-platform process debugging API implemented in python, and vdb is a debugger which uses it
  • Androguard: reverse engineering and analysis of Android applications

Fuzzing

  • Sulley: fuzzer development and fuzz testing framework consisting of multiple extensible components
  • Peach Fuzzing Platform: extensible fuzzing framework for generation and mutation based fuzzing (v2 was written in Python)
  • antiparser: fuzz testing and fault injection API
  • TAOF, (The Art of Fuzzing) including ProxyFuzz, a man-in-the-middle non-deterministic network fuzzer
  • untidy: general purpose XML fuzzer
  • Powerfuzzer: highly automated and fully customizable web fuzzer (HTTP protocol based application fuzzer)
  • SMUDGE
  • Mistress: probe file formats on the fly and protocols with malformed data, based on pre-defined patterns
  • Fuzzbox: multi-codec media fuzzer
  • Forensic Fuzzing Tools: generate fuzzed files, fuzzed file systems, and file systems containing fuzzed files in order to test the robustness of forensics tools and examination systems
  • Windows IPC Fuzzing Tools: tools used to fuzz applications that use Windows Interprocess Communication mechanisms
  • WSBang: perform automated security testing of SOAP based web services
  • Construct: library for parsing and building of data structures (binary or textual). Define your data structures in a declarative manner
  • fuzzer.py (feliam): simple fuzzer by Felipe Andres Manzano
  • Fusil: Python library used to write fuzzing programs

Web

  • Requests: elegant and simple HTTP library, built for human beings
  • HTTPie: human-friendly cURL-like command line HTTP client
  • ProxMon: processes proxy logs and reports discovered issues
  • WSMap: find web service endpoints and discovery files
    Twill: browse the Web from a command-line interface. Supports automated Web testing
  • Ghost.py: webkit web client written in Python
  • Windmill: web testing tool designed to let you painlessly automate and debug your web application
  • FunkLoad: functional and load web tester
  • spynner: Programmatic web browsing module for Python with Javascript/AJAX support
  • python-spidermonkey: bridge to the Mozilla SpiderMonkey JavaScript engine; allows for the evaluation and calling of Javascript scripts and functions
  • mitmproxy: SSL-capable, intercepting HTTP proxy. Console interface allows traffic flows to be inspected and edited on the fly
  • pathod / pathoc: pathological daemon/client for tormenting HTTP clients and servers

取证

  • Volatility: extract digital artifacts from volatile memory (RAM) samples
  • LibForensics: library for developing digital forensics applications
  • TrIDLib, identify file types from their binary signatures. Now includes Python binding
  • aft: Android forensic toolkit

恶意程序分析

  • pyew: command line hexadecimal editor and disassembler, mainly to analyze malware
  • Exefilter: filter file formats in e-mails, web pages or files. Detects many common file formats and can remove active content
  • pyClamAV: add virus detection capabilities to your Python software
  • jsunpack-n, generic JavaScript unpacker: emulates browser functionality to detect exploits that target browser and browser plug-in vulnerabilities
  • yara-python: identify and classify malware samples
  • phoneyc: pure Python honeyclient implementation

PDF

  • Didier Stevens’ PDF tools: analyse, identify and create PDF files (includes PDFiDpdf-parserand make-pdf and mPDF)
  • Opaf: Open PDF Analysis Framework. Converts PDF to an XML tree that can be analyzed and modified.
  • Origapy: Python wrapper for the Origami Ruby module which sanitizes PDF files
  • pyPDF: pure Python PDF toolkit: extract info, spilt, merge, crop, encrypt, decrypt…
  • PDFMiner: extract text from PDF files
  • python-poppler-qt4: Python binding for the Poppler PDF library, including Qt4 support

Misc

  • InlineEgg: toolbox of classes for writing small assembly programs in Python
  • Exomind: framework for building decorated graphs and developing open-source intelligence modules and ideas, centered on social network services, search engines and instant messaging
  • RevHosts: enumerate virtual hosts for a given IP address
  • simplejson: JSON encoder/decoder, e.g. to use Google’s AJAX API
  • PyMangle: command line tool and a python library used to create word lists for use with other penetration testing tools
  • Hachoir: view and edit a binary stream field by field
  • py-mangle: command line tool and a python library used to create word lists for use with other penetration testing tools

其他有用的Py库和工具

  • IPython: enhanced interactive Python shell with many features for object introspection, system shell access, and its own special command system
  • Beautiful Soup: HTML parser optimized for screen-scraping
  • matplotlib: make 2D plots of arrays
  • Mayavi: 3D scientific data visualization and plotting
  • RTGraph3D: create dynamic graphs in 3D
  • Twisted: event-driven networking engine
  • Suds: lightweight SOAP client for consuming Web Services
  • M2Crypto: most complete OpenSSL wrapper
  • NetworkX: graph library (edges, nodes)
  • Pandas: library providing high-performance, easy-to-use data structures and data analysis tools
  • pyparsing: general parsing module
  • lxml: most feature-rich and easy-to-use library for working with XML and HTML in the Python language
  • Whoosh: fast, featureful full-text indexing and searching library implemented in pure Python
  • Pexpect: control and automate other programs, similar to Don Libes Expect system
  • Sikuli, visual technology to search and automate GUIs using screenshots. Scriptable inJython
  • PyQt and PySide: Python bindings for the Qt application framework and GUI library

其他
Python 作为程序员的宠儿,越来越得到人们的关注,使用 Python 进行应用程序开发的越来也多。那么,在 2013 年有哪些流行的 Python 项目呢?下面,我们一起来看下。
一、测试和调试

  • python_koans:Python Koans 算 “Ruby Koans” 的一部分,作为交互式教程,可以学习 TDD 技巧。
  • sure:Sure 是最适合自动化测试的 Python 工具,包含流利的断言、深度选择器等等特性。
  • responses:用 responses 能令测试更加轻松,这是一个可以伪装各种请求的库。
  • boom:Boom! Apache Bench 的替代品。作为一个命令行工具,Boom 能对你的应用进行快捷的 smoke test
  • cricketBeeWare 套件的一部分,cricket 是种图形化工具,协助你进行案例测试。
  • bugjarBeeWare 套件的一部分,bugjar 是针对 Python 的图形化交互式调试器。
  • pudb:pudn 是针对 Python 的全屏命令行调试器。
  • voltron:更好的 gdb 界面。

二、Web 框架

  • django-stronghold:试过将 login_required 装饰器四处乱放? 在你的堡垒中令所有 Django 视图有默认 login_required 呗。
  • Falcon Framework:Falcon 自称为髙性能云接口框架,号称能在相同硬件条件下提高服务端性能 30 倍! 听起来有点儿意思?
  • django-xadmin:用 bootstrap 对 django-admin 进行了深度升级,提供了可插件安装的仪表盘。
  • clay:基于 Flask 的封装,能令我们轻松的创建 RESTful 后端服务,完整文档可查看 clay
  • flask-restful:基于 Flask 的简单框架,用以创建 REST 接口。
  • sandman:Sandman 希望通过 REST 接口暴露你现有的 app,相关 博客也值得一读。
  • Django Unchained:名字很髙大上,也的确是 Python Django 初学者的靠谱指南。

三、并发

  • pulsar:部署新 web 服务器走起! 有趣的事件驱动的并发框架 ! 兼容从 2.6+ 到 pypy 的所有 python 版本!
  • toro:同步化的 Tornado 协程支持。
  • offset:Offset Go 的并发模式在 Python 中的实现,请参考相关演讲 幻灯来理解!

四、任务调度

  • pyres:从 resque 获得灵感的纯 Python 任务调度模块,是 celery 的替代。
  • dagobah:Dagobah 是 Python 完成的简单关系依赖为基础的任务调度模块,还包含很 COOL 的关联任务工作流图形工具。
  • schedule:使用生成器模式来为定期任务生成配置的进程调度模块。

五、实用工具

  • howdoi:发觉你总在 Google 一些简单的最简单的编程任务? howdoi 能让你远离浏览器,就解决这类事儿!
  • delorean:时间旅行?简单! Delorean 的目标就是令你的 Python 项目在处理时间/日期时轻而易举!查阅完备的 文档
  • powerline-shell:对于那些想让常用工具漂亮起来人,一定要用 powerline-bash,能打造漂亮的 shell 提示符,增加力线(powerline),兼容 Bash/Zsh。
  • fn.py:在 Python 中谈及函数编程时失落的那节”电池”终于出现了! 如果对 Python 函数式编程有兴趣的立即下手安装体验吧!
  • lice:为你的开源工程方便的追加许可证,而不用自个儿去 Google,支持 BSD、MIT 和 GPL 以及变种协议。
  • usblock:基于 USB 来锁定或是解锁你的笔记本!
  • Matchbox:MatchBox 能在你自个儿的服务器上提供类似 Dropbox 风格的备份服务! 基于 Flask 并通过 http 协议进行文件传输。
  • cleanify:用 cleanify 能异步美化你项目的所有 html/css/js 文件。
  • locksmith:Locksmith 是 AES 加密的口令管理器,看起来不错,完全开源,源代码、截屏都有。
  • storm:在 Storm 的命令行界面,管理你所有的 SSH 连接。
  • sqlparse::这个很给力! sqlparse 是个 SQL 有效性分析器,支持解析/分裂/格式化 SQL 语句。
  • autopep8:能自动化以 pep8来格式化你的代码。
  • colout:colout 用以在命令行中色彩化输出,这就从其 github page 查看范例来体验吧。
  • bumpversion:版本号冲撞总是恼人的,而每个人总是忘记给发行版本打 tag,bumpversion 用一条简单的命令简化了这方面的操作。
  • pyenv:需要更好的管理你 Python 的多版本环境 ? pyenv 让你能简洁的作到!(甚至超出你的预期!有插件能将 VirtualEnv 也无缝结合进来!)
  • pip-tools:一整套能令你的 Python 项目保持清爽的工具。
  • cdiff:Cdiff 是种非常 nice 的工具,可以用彩色输出统一 diff 格式信息,或用双栏形式来展示。

六、数据科学及可视化

  • data_hacks:由 bitly 发布的一堆数据分析用命令行工具。这些工具接受命令行或是其它工具输入的数据,轻易的生成柱图以及直方图等等。
    给黒客的概率编程和贝叶斯方法:这书是极好的,介绍如何用贝叶斯方法和概率编程进行数据分析,而且每章都提供了用以 iPython Notebooks 的示例。
  • simmetrica:想对自个儿的应用基于时间的数据序列进行展示、汇总、分享嘛? 赶紧上 simmetrica 吧,同时还提供了可定制的仪表盘。
  • vincent: Python 构建的专为运用 D3.js 进行可视化的 vega 转换工具。
  • bamboo:一种简洁的实时数据分析应用,bamboo 提供了一个进行合并、汇总、数值计算的数据实时接口。
  • dataset:难以置信的工具,dataset 让对数据库的读写简单的象对 JSON 文件的操作,没有其它的文件配置,顷刻间就让你在 BOSS 面前高大上起来。
  • folium:喜欢地图?也爱 Python? Folium 让你在地图上自在操纵数据。
  • prettyplotlib:用 prettyplotlib 来强化你的 matplotlib,让你默认的 matplotlib 输出图片更加漂亮.
  • lifelines:有兴趣在 Python 中研究生存分析的话,不用观望了,用 lifelines! 包含对 Kaplan-Meier、Nelson-Aalen 和生存回归分析。

七、编辑器及其改善*

  • sublime-snake:想在无尽的 coding 中喘口气? 当然是这种经典游戏了……
  • spyderlib:又一个用 Python 写的开源 IDE。
  • vimfox:对于 Vim 党最贴心的 web 专发工具,VimFox 能让 vim 实时的看到 css/js/html 的修改效果,能神奇的让 vim 中的修订,立即在浏览器中看到。
  • pcode:基于 Py3 的 IDE,通过简单的 UI 提供了重构、工程管理等。

八、持续交付

  • metrology:这个库很酷,支持你对应用进行多种测量并轻松输出给类似 graphite 的外部系统。
  • python-lust:支持在 Unix 系统中用 Python 实现一个守护进程。
  • scales:Scales 对你的 Python 应用进行持续状态和统计,并发送数据到 graphite
  • glances:跨平台,基于 curses 命令行的系统监视工具。
  • ramona:企业级的应用监管。 Ramona 保证每个进程在值,一但需要立即重启,并有监控/日志输出,会发送邮件提醒。
  • salmon:基于 Salt Stack 的多服务监视系统,即能作报警系统,也能当监控系统。
  • graph-explorer:Graph-explorer 是对 Graphite 面板的增强,比原版的好很多,值得体验。
  • sovereign:Sovereign 是一系列 ansible 的攻略手册,能为自个儿建造个私人云。
  • shipyard:能在指定的机器上弹出你的弹窗实例,也支持你创建/删除等等对弹窗的远程控制。
  • docker-py:疯狂的 docker 工程接口的 Python 包装。
  • dockerui:基于 docker 接口通过 web 界面进行交互操作的工具。
  • django-docker:如果想知道怎么将 Djnago 应用同 Docker 结合? 可以从这里学习。
    diamond:Python 实现的守护进程,自动从你的服务或是其它指定数据源中提取数值,并 graphite以及其它支持的状态面板/收集系统输出。

九、Git

  • git-workflow:可视化你的 git 工作流程的工具,示例: Demo
  • gitto:简洁的库,协助你建立自个儿的 git 主机。
  • git-imerge:git-imerge 能让 git 进行增量合并。 本质上是允许你在进行 imerge 有冲突时,有机会先合并掉,再继续。

十、邮件与聊天

  • mailbox:Mailbox 是对 Python 的 IMAP 一个人性化的再造。 基于简单即是美的态度,作者对 IMAP 接口给出了一个简单又好理解的形式。
  • deadchat:deadchat 旨在不安全的网络环境中提供安全的单一房间群聊服务以及客户端。
  • Mailpile:Mailpile 是针对邮件的索引及搜索引擎 。

十一、音频和视频

  • pms:穷人的 Spotify,搜索和收集音乐流!
  • dejavu:在琢磨 Shazam 的原理? 音频指纹识别算法的 Python 实现在此!(译注:Shazam:是个神奇的音乐识别应用,对她啍个几秒调子,就能精确告诉你是什么歌曲、作者、歌词……)
  • HTPC-Manager:为 HTPC 粉丝准备的工具,提供了完备的界面来管理所有家庭媒体服务器上的好物。
  • cherrymusic:Python 实现的一个音乐流媒体服务器。 流化输出你的音乐到所有设备上。
  • moviepy:脚本化的电影剪辑包,切/串/插入标题等基本操作,几行就搞定!

十二、其它

  • emit:用 redis 为你的函式追加可订阅能力,很有趣。
  • zipline:Zipline 是种很 Pythonic 的交易算法库。
  • raspberry.io:Raspberry.io 是树莓派的社区实现。 刚刚发布,汇集了各种创意想法,有兴趣的话立即检出折腾吧。
  • NewsBlur:Google Reader 已经关张儿了,Newsblur 已经发布了有段日子了,开源的 RSS 阅读器,这绝对是应该首先体验的。
  • macropy:Macropy 是在 Python 中实现 macros 的库。 检出文档,参考所有功能,看怎么用上了。
    - mini:对编译器以及语言设计有兴趣的,一定要看看这个仓库,以及配套的录像!
  • parsimonious:Parsimonious 的目标是最快的 arbitrary-lookahead 解析器。 用 Python 实现,基本可用。
  • isso:Disqus 的开源替代,从 demo 看很不错,而且提供了更好的隐私设置。
  • deaddrop:Deaddrop 能为新闻机构或是其它人提供在线投递箱,详细信息参考其 github page
  • nude.py:裸体检测的 Python 实现,是 node.js 的仿制。
  • kaptan: Kaptan 是你应用的配置管理器!
  • luigi:Luigi 帮你构建复杂的管道来完成批处理。
  • gramme:Gramme 以简单而优雅的方式,通过 UDP 接口对易失数据完成消息包装序列化。
  • q:为你的 Python 程序提供快速而随性的日志。 有一系列帮手来追踪你的函式参数,并能在控制台快速交互式加载。
  • fuqit:来自伟大的 Zed Shaw 最新作品,fuqit 试图令你忘记 MVC 的经验,用全新的方式专注简洁一切。
  • simplicity:基于靠谱的 pydanny 将你的新结构化文本转换为 JSON 格式。
  • lassie:Lassie 允许你轻松的从网站检索出内容来。
  • paperwork:Paperwork 是个 OCR 文档并完成可搜索转化的工具,用 GTK/Glade 实现了友好的界面。
  • cheat:cheat 允许你创建并查阅命令行上的交互式备忘。设计目的是帮助 *nix 的系统管理员们在习惯的环境中,快速调阅不易记忆的常用命令。
  • cookiecutter:良心模块! 提供一堆有用但是不常写,所以记不下来的代码模板,也支持自制代码模板。
  • pydown:支持用 Python 构建亮丽的 HTML5 效果幻灯,Demo
    Ice:模拟器粉丝们现在能用 Ice 向 Steam 里塞 ROM 来玩了。
  • pants:用以编写异步网络应用的轻量级框架。 Pants 是单线程,回调服务,也包含支持 Websockets 的 HTTP 服务、WSGI 支持和一个简单的 web 框架。
  • pipeless:Pipeless 是一个构建简单 数据管道的框架。
  • marshmallow:marshmallow 是个 ORM 无关的库,能将复杂的数据类型转换为 Python 原生类型对象,以便容易的转换为 JSON 提供接口使用。
  • twosheds:Python 实现的库,用来构造命令或是 shell 解释器。Twosheds 让你用 Python 来定制自个儿的 shell 环境。

来自:http://www.cnblogs.com/hongfei/p/3874419.html

直接上代码

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
from email.header import Header
from email.mime.text import MIMEText
from email.utils import parseaddr, formataddr
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
import smtplib
# 第三方 SMTP 服务
mail_host="smtp.qq.com" #设置服务器
mail_user="111@qq.com" #用户名
mail_pass="adfafda" #口令

def _format_addr(s):
name, addr = parseaddr(s)
return formataddr((Header(name, 'utf-8').encode(), addr))


def send_mail(f, to_addr):
'''

:param f: 附件路径
:param to_addr:发给的人 []
:return:
'''
from_addr = mail_user
password = mail_pass
# to_addr = "ashikun@126.com"
smtp_server = mail_host

msg = MIMEMultipart()

# msg = MIMEText('hello, send by Python...', 'plain', 'utf-8')
msg['From'] = _format_addr('坤少发的邮件<%s>' % from_addr)
msg['To'] = _format_addr('大人 <%s>' % to_addr)
msg['Subject'] = Header('接口测试报告……', 'utf-8').encode()

msg.attach(MIMEText('接口测试报告.', 'plain', 'utf-8'))
part = MIMEApplication(open(f, 'rb').read())
part.add_header('Content-Disposition', 'attachment', filename=f)
msg.attach(part)

server = smtplib.SMTP_SSL(smtp_server, 465)
server.set_debuglevel(1)
server.login(from_addr, password)
server.sendmail(from_addr, to_addr, msg.as_string())
server.quit()
  • 被这里密码坑了好长时间,切记这里的密码不是登陆密码,而是授权码
  • QQ发邮件用25端口发送不成功,用搞定ssl的465

运行下面的代码,可以自动给指定的微信好友发消息

1
2
3
4
5
6
7
8
9
10
11
import itchat

#产生二维码
itchat.auto_login(hotReload=True)
#定义用户的昵称
send_userid='亲爱的'
#查找用户的userid
itcaht_user_name = itchat.search_friends(name=send_userid)[0]['UserName']
#利用send_msg发送消息
itchat.send_msg('这是一个测试',toUserName=itcaht_user_name)

运行下面的代码,好友发消息给你后自动回复

  • 自动回复的内容用的是图灵机器人
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
import requests
import itchat
# 去图灵机器人官网注册后会生成一个apikey,可在个人中心查看
KEY = '8edce3ce905a4c1dbb96**************'
def get_response(msg):
apiUrl = 'http://www.tuling123.com/openapi/api'
data = {
'key' : KEY,
'info' : msg, # 这是要发送出去的信息
'userid' : 'wechat-rebot', #这里随意写点什么都行
}
try:
# 发送一个post请求
r = requests.post(apiUrl, data =data).json()
# 获取文本信息,若没有‘Text’ 值,将返回Nonoe
return r.get('text')
except:
return
# 通过定义装饰器加强函数 tuling_reply(msg) 功能,获取注册文本信息
@itchat.msg_register(itchat.content.TEXT)
def tuling_reply(msg):
# 设置一个默认回复,在出现问题仍能正常回复信息
defaultReply = 'I received: ' +msg['Text']
reply = get_response(msg['Text'])
# a or b 表示,如有a有内容,那么返回a,否则返回b
return reply or defaultReply
# 使用热启动,不需要多次扫码
itchat.auto_login(hotReload=True)
itchat.run()

其他