├── README.md ├── chapter000 ├── 01-学习路线 │ └── 学习路线图.jpg └── 02-章节地图 │ └── 13.Python数据库编程.jpg ├── chapter002 └── chapter_0201.py ├── chapter003 ├── chapter_0301.py └── chapter_0302.py ├── chapter004 ├── chapter_0403.py ├── chapter_0404.py ├── chapter_0405.py ├── chapter_0406.py ├── chapter_0407.py ├── chapter_0408.py ├── chapter_0409.py ├── chapter_0410.py ├── chapter_0411.py ├── chapter_0412.py ├── chapter_0413.py └── toutiao.py ├── chapter005 ├── chapter_0501.py ├── chapter_0502.py ├── chapter_0503.py ├── chapter_0504.py ├── chapter_0505.py └── chapter_0506.py ├── chapter006 ├── __init__.py ├── chapter_0601.py ├── chapter_0602.py ├── chapter_0603.py ├── chapter_0604.py └── hello.txt ├── chapter007 ├── __init__.py ├── chapter_0701.py ├── chapter_0702.py ├── chapter_0703.py ├── chapter_0704.py ├── chapter_0705.py ├── chapter_0706.py ├── chapter_0707.py ├── chapter_0708.py ├── chapter_0709.py ├── hello.txt └── temp2 │ └── hello.txt ├── chapter008 ├── 111.txt ├── __init__.py ├── chapter_0801.py ├── chapter_0802.py ├── chapter_0803.py ├── chapter_0804.py ├── chapter_0805.py ├── chapter_0806.py ├── chapter_0807.py ├── hello.txt └── temp2 │ └── 111.txt ├── chapter009 ├── __init__.py ├── __pycache__ │ ├── __init__.cpython-36.pyc │ ├── chapter_0901.cpython-36.pyc │ └── chapter_0902.cpython-36.pyc ├── chapter_0901.py ├── chapter_0902.py ├── chapter_0903.py └── chapter_0904.py ├── chapter010 ├── chapter_01001.py ├── chapter_01002.py ├── chapter_01003.py └── chapter_01004.py ├── chapter011 ├── chapter_01101.py ├── chapter_01102.py ├── chapter_01103.py ├── chapter_01104.py ├── chapter_01105.py ├── chapter_01106.py ├── chapter_01107.py ├── chapter_01108.py ├── chapter_01109.py ├── chapter_01110.py ├── chapter_01111.py └── chapter_01112.py ├── chapter012 ├── chapter_01200.py ├── chapter_01201.py ├── chapter_01202.py ├── chapter_01203.py └── chapter_01204.py ├── chapter013 ├── ch13_conn.py ├── ch13_full.py ├── chapter_01303.py ├── chapter_01304.py ├── chapter_01305.py ├── chapter_01306.py └── chapter_01307.py ├── chapter014 ├── chapter_01401.py ├── chapter_01402.py ├── chapter_01403.py ├── chapter_01405.py ├── chapter_01406.py ├── chapter_01407.py ├── chapter_01408.py ├── chapter_01409.py ├── chapter_01410.py ├── chapter_01411.py ├── chapter_01412.py ├── chapter_01415.py ├── chapter_01416.py ├── chapter_01417.py ├── chapter_01418.py └── chapter_01419.py ├── chapter015 ├── chapter_01501.py ├── chapter_01502.py ├── chapter_01503.py ├── chapter_01504.py ├── chapter_01505.py └── chapter_01506.py ├── chapter016 ├── ch1601-csvread.py ├── ch1602-csvwrite.py ├── ch1603-full.py ├── ch1604-full.py ├── ch1604-xlsx-read.py ├── ch1605-xls-write.py └── data │ ├── ReadMe.txt │ ├── ch1601-data.csv │ ├── ch1602-data-write.csv │ ├── ch1603-data-write.csv │ ├── ch1603-data.csv │ ├── ch1604-data-write.xls │ ├── ch1604-data.xlsx │ └── ch1604-write.xls ├── chapter017 └── chapter_01701.py ├── chapter018 ├── chapter_01801.py ├── chapter_01802.py ├── chapter_01803.py ├── chapter_01804.py ├── chapter_01805.py ├── chapter_01806.py └── stu_info.json └── chapter019 ├── chapter_01901.py └── myapp ├── db.sqlite3 ├── manage.py ├── myapp ├── __init__.py ├── __pycache__ │ ├── __init__.cpython-36.pyc │ ├── dbhandler.cpython-36.pyc │ ├── search.cpython-36.pyc │ ├── settings.cpython-36.pyc │ ├── urls.cpython-36.pyc │ ├── view.cpython-36.pyc │ └── wsgi.cpython-36.pyc ├── asgi.py ├── dbhandler.py ├── search.py ├── settings.py ├── urls.py ├── view.py └── wsgi.py ├── mymodel ├── __init__.py ├── __pycache__ │ ├── __init__.cpython-36.pyc │ ├── admin.cpython-36.pyc │ └── models.cpython-36.pyc ├── admin.py ├── apps.py ├── migrations │ ├── 0001_initial.py │ ├── __init__.py │ └── __pycache__ │ │ ├── 0001_initial.cpython-36.pyc │ │ └── __init__.cpython-36.pyc ├── models.py ├── tests.py └── views.py ├── run.bat └── templates ├── hello.html └── name.html /README.md: -------------------------------------------------------------------------------- 1 | # RoadPython 2 | 图说Python菜鸟版配套源码 3 | ## 学习路线图 4 | ![Alt](https://github.com/zhangziliang04/RoadPython/blob/master/chapter000/01-%E5%AD%A6%E4%B9%A0%E8%B7%AF%E7%BA%BF/%E5%AD%A6%E4%B9%A0%E8%B7%AF%E7%BA%BF%E5%9B%BE.jpg) 5 | 6 | ## 章节目录 7 | ### 第一部分:语法基础篇 8 | --------------------------- 9 | - 第01章 Python语言简介 10 | - 第02章 Python环境部署 11 | - 第03章 Python语法基础 12 | - 第04章 Python数据类型 13 | - 第05章 Python控制语句 14 | - 第06章 Python输入输出 15 | - 第07章 Python文件操作 16 | - 第08章 Python目录操作 17 | - 第09章 Python函数模块 18 | - 第10章 Python面向对象 19 | - 第11章 Python异常调试 20 | 21 | ### 第二部分:能力提升篇 22 | - 第12章 Python正则表达式 23 | - 第13章 Python数据库编程 24 | - 第14章 Python多线程编程 25 | - 第15章 Python网络通讯编程 26 | - 第16章 Python Excel编程 27 | - 第17章 Python XML文件解析 28 | - 第18章 Python JSON文件解析 29 | - 第19章 Python Djangoweb编程 30 | 31 | ### 第三部分:实战案例篇 32 | - 第20章 Python网络爬虫 33 | - 第21章 Python人脸识别 34 | 35 | ## 章节学习地图 36 | 37 | 38 | 链接 39 | --------------------------- 40 | 链接: [link](https://mp.csdn.net). 41 | 42 | -------------------------------------------------------------------------------- /chapter000/01-学习路线/学习路线图.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhangziliang04/RoadPython/5a68ed62b987c228b5e56f445d43904223dfe6a9/chapter000/01-学习路线/学习路线图.jpg -------------------------------------------------------------------------------- /chapter000/02-章节地图/13.Python数据库编程.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhangziliang04/RoadPython/5a68ed62b987c228b5e56f445d43904223dfe6a9/chapter000/02-章节地图/13.Python数据库编程.jpg -------------------------------------------------------------------------------- /chapter002/chapter_0201.py: -------------------------------------------------------------------------------- 1 | # 2 | print("Hello Python 你好2019!.") -------------------------------------------------------------------------------- /chapter003/chapter_0301.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | #多行注释:单引号 3 | ''' 4 | 这是多行注释,用三个单引号 5 | 这是多行注释,用三个单引号 6 | 这是多行注释,用三个单引号 7 | ''' 8 | #多行注释:双引号 9 | """ 10 | 这是多行注释,用三个双引号 11 | 这是多行注释,用三个双引号 12 | 这是多行注释,用三个双引号 13 | """ 14 | 15 | #单行注释 16 | print("Hello Python") -------------------------------------------------------------------------------- /chapter003/chapter_0302.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | import keyword 3 | 4 | #保留关键字 5 | print(keyword.kwlist) 6 | 7 | 8 | #行与缩进 9 | if True: 10 | print("True") 11 | else: 12 | print("False") 13 | 14 | #缩进演示2 15 | if True: 16 | print("Answer") 17 | print("True") 18 | else: 19 | print("Answer") 20 | print("False") -------------------------------------------------------------------------------- /chapter004/chapter_0403.py: -------------------------------------------------------------------------------- 1 | # 数据类型程序实例3:数值类型 2 | # 01:创建变量 3 | print("------------变量初始化-------------") 4 | val1 = 10 5 | val2 = 10.22 6 | val3 = 10+4j 7 | val4 = True 8 | 9 | # 02:类型判定 10 | print("------------类型判定-------------") 11 | print(type(val1),type(val2),type(val3),type(val4)) 12 | val5 = 11 13 | print(isinstance(val5,int)) 14 | 15 | # 03:删除对象引用 16 | print("------------删除对象引用-------------") 17 | val6 = 14 18 | del val6 19 | # print(val6) # 抛出异常 20 | 21 | # 04 :数值计算 22 | print("------------数值计算-------------") 23 | val1 = 10 24 | val2 = 12 25 | val3 = val1 + val2 26 | print(val3) 27 | -------------------------------------------------------------------------------- /chapter004/chapter_0404.py: -------------------------------------------------------------------------------- 1 | # 字符串 2 | str = 'Python全栈工程师' 3 | 4 | # 索引 5 | print(str) # 输出字符串 6 | print(str[0:-1]) # 输出第一个到倒数第二个的所有字符 7 | print(str[0]) # 输出字符串第一个字符 8 | print(str[2:5]) # 输出从第三个开始到第五个的字符 9 | print(str[2:]) # 输出从第三个开始的后的所有字符 10 | print(str * 2) # 输出字符串两次 11 | # 连接 12 | print(str + "魔鬼训练营") 13 | # 转义 14 | print("换行\r\n") 15 | print("Tab制表符\t") 16 | 17 | # 成员运算符 18 | if 'P' in str: 19 | print("P is in ", str) 20 | # 格式化符 21 | print("PI = %.2f" % 3.1415926) 22 | -------------------------------------------------------------------------------- /chapter004/chapter_0405.py: -------------------------------------------------------------------------------- 1 | # 数据类型程序实例5:列表 2 | # 01:创建变量 3 | list = ["北京","上海","天津","深圳"] 4 | print(list) 5 | 6 | # 02:访问元素 7 | list = ["北京","上海","天津","深圳"] 8 | print(list[0]) 9 | print(list[1:3]) 10 | 11 | # 03:更新列表 12 | print("------------更新操作-------------") 13 | list = ["北京","上海","天津","深圳"] 14 | list[0] = "南京" 15 | print(list) 16 | list.append("雄安新区") 17 | print(list) 18 | list2 = ["南京","石家庄"] 19 | list = list + list2 # 列表元素允许重复 20 | print(list) 21 | 22 | # 04:删除操作 23 | print("------------删除操作-------------") 24 | list = ["北京","上海","天津","深圳"] 25 | print(list[0]) 26 | # 删除单个元素 27 | del list[0] 28 | print(list) 29 | # 删除整个列表 30 | del list 31 | print(list) 32 | -------------------------------------------------------------------------------- /chapter004/chapter_0406.py: -------------------------------------------------------------------------------- 1 | # Python数据类型之元组 2 | # 01:创建 3 | tuple = ("北京","深圳",50) 4 | print(tuple) 5 | 6 | #02: 元素访问 7 | tuple = ("北京","深圳","上海","天津","雄安新区") 8 | print(tuple[0]) 9 | print(tuple[1:3]) 10 | 11 | 12 | # 03:修改元组 13 | tup1 = ("北京","深圳","上海","天津") 14 | tup2 = ("雄安新区",) 15 | tup3 = tup1 + tup2 16 | print(tup3) 17 | 18 | # 04:删除元祖 19 | tup = ("北京","深圳","上海","天津") 20 | print(tup) 21 | # del tup[0] 22 | del tup 23 | # print(tup) #抛出异常 -------------------------------------------------------------------------------- /chapter004/chapter_0407.py: -------------------------------------------------------------------------------- 1 | # Python数据类型之字典 2 | # 01:创建 3 | dict = {"首都":"北京","特区":"深圳","年份":50} 4 | print(dict) 5 | dict = {"首都":"北京","特区":("深圳","雄安新区")} 6 | print(dict) 7 | 8 | # 02:访问 9 | print("-----------访问元素--------------") 10 | dict = {"首都":"北京","特区":"深圳","年份":50} 11 | print(dict["首都"]) 12 | # 如果key 不存在,则抛出异常 13 | #print(dict["首都2"]) 14 | 15 | # 03: 修改元素 16 | print("-----------修改元素--------------") 17 | dict = {"首都":"北京","特区":"深圳","年份":50} 18 | dict["首都"] = "重庆" 19 | print(dict) 20 | 21 | # 04 :删除元素 22 | print("-----------删除元素--------------") 23 | dict = {"首都":"北京","特区":"深圳","年份":50} 24 | del dict["首都"] 25 | print(dict) 26 | # 清空 27 | dict.clear() 28 | print(dict) 29 | # 清空 30 | del dict 31 | print(dict) -------------------------------------------------------------------------------- /chapter004/chapter_0408.py: -------------------------------------------------------------------------------- 1 | # 01:添加数据,单个元素,可以是任意类型 2 | myset = {"北京","上海","天津"} 3 | myset.add("深圳") 4 | print(myset) 5 | # {'上海', '北京', '天津', '深圳'} 6 | # 添加元素:允许-元组、列表、词典、集合;不允许-数字、字符串 7 | myset.update("雄安新区") 8 | print(myset) 9 | # {'安', '区', '上海', '北京', '新', '天津', '雄', '深圳'} 10 | myset.update({"雄安新区"}) 11 | print(myset) 12 | # {'安', '区', '上海', '北京', '新', '天津', '雄', '雄安新区', '深圳'} 13 | 14 | 15 | # 02:删除数据 16 | print("-----------删除元素--------------") 17 | # 方法1:remove(x) 18 | myset = {"北京","上海","天津"} 19 | print(myset) 20 | myset.remove("北京") 21 | print("北京") 22 | print(myset) 23 | # 删除不存在元素,报异常 24 | myset.remove("北京") 25 | 26 | # 方法2:discard(x) 27 | myset = {"北京","上海","天津"} 28 | print(myset) 29 | myset.discard("北京") 30 | print(myset) 31 | # 删除不存在的元素,无提示 32 | myset.discard("北京") 33 | print(myset) 34 | 35 | # 方法3:pop() 随机删除 36 | 37 | myset = {"北京","上海","天津"} 38 | print(myset) 39 | myset.pop() 40 | print(myset) 41 | myset.pop() 42 | print(myset) 43 | myset.pop() 44 | print(myset) 45 | # 无元素可删除时,程序异常 46 | # myset.pop() 47 | 48 | # 03:计算集合元素个数 49 | print("-----------计算元素个数--------------") 50 | myset = {"北京","上海","天津"} 51 | print(len(myset)) 52 | 53 | # 4:判断元素是否在集合中 54 | print("-----------判断元素是否在集合中--------------") 55 | myset = {"北京","上海","天津"} 56 | print("北京" in myset) 57 | print("广州" in myset) 58 | 59 | # 5:集合元素访问 60 | print("-----------访问集合中元素--------------") 61 | # print(myset[1]) # 异常:不支持索引访问 62 | lst = list(myset) 63 | print(lst[0]) 64 | 65 | 66 | 67 | -------------------------------------------------------------------------------- /chapter004/chapter_0409.py: -------------------------------------------------------------------------------- 1 | # 扩展类型: 2 | # 3 | # 双向队列 4 | import collections 5 | 6 | # 对象声明 7 | deq = collections.deque('abcd') 8 | print(deq) 9 | 10 | # 01.添加元素 - 右侧 11 | deq.append(11) 12 | print(deq) 13 | 14 | # 01.添加元素 - 左侧 15 | deq.appendleft(12) 16 | print(deq) 17 | 18 | # 01.添加元素 - 指定位置插入元素 19 | deq.insert(4, 44) 20 | 21 | # 02.队列拓展 - 右侧 22 | deq.extend([11, 22, 33]) 23 | print(deq) 24 | 25 | # 02.队列拓展 - 左侧 26 | deq.extendleft([11, 22, 33]) 27 | print(deq) 28 | 29 | # 03.取元素索引位置 30 | print(deq.index('a')) 31 | 32 | # 04.移除元素 33 | print(deq) 34 | deq.pop() # 右侧 35 | deq.popleft() # 左侧 36 | deq.remove('a') # 指定元素 37 | deq.rotate(-2) # N < 0 左侧移除;N > 0 右侧移除 38 | print(deq) 39 | 40 | # 05.队列反转 41 | deq.reverse(); 42 | print(deq) 43 | 44 | # 06.元素 45 | # 清空队列 46 | deq.clear() 47 | print(deq) 48 | 49 | 50 | 51 | -------------------------------------------------------------------------------- /chapter004/chapter_0410.py: -------------------------------------------------------------------------------- 1 | # 计数器 2 | import collections 3 | 4 | # 对象声明 5 | c = collections.Counter('abcdeabcdabcaba') 6 | print(c) 7 | 8 | # 元素访问:按照顺序输出 9 | print(list(c.elements())) 10 | 11 | # 增加元素重复次数 12 | c.update('a') 13 | print(c) 14 | 15 | # 减少元素重复次数 16 | c.subtract('a') 17 | print(c) 18 | -------------------------------------------------------------------------------- /chapter004/chapter_0411.py: -------------------------------------------------------------------------------- 1 | # 有序字典:记住了项目的插入顺序 2 | # 重要:python3.6+ dict类型,默认支持按照插入顺序记录元素,不需要额外的OrderDict 3 | from collections import OrderedDict 4 | 5 | # 普通字典 6 | d = dict([('a', 1), ('c', 3), ('b', 2), ('d', 4), ('e', 5), ('f', 6)]) 7 | print(d) 8 | 9 | items = d.items() 10 | # items.sort() # python3.x 版本items返回类型不是列表,不支持sort 11 | items = sorted(items) 12 | 13 | for key, value in items: 14 | print(key, value) # print key,dict[key] 15 | 16 | # 有序字典:Key会按照插入的顺序排列,不是Key本身排序 17 | od = OrderedDict([('a', 1), ('c', 3), ('b', 2)]) # 18 | print(od) 19 | 20 | items = od.items() 21 | items = sorted(items) 22 | for key, value in items: 23 | print(key, value) # print key,dict[key] 24 | 25 | # 更新元素:不存在是新增 26 | od.update({'a':'5'}) 27 | print(od) 28 | 29 | # 移动到尾部 30 | od.move_to_end('a') 31 | print(od) 32 | 33 | # 删除元素 34 | od.pop('a') # 指定元素 35 | print(od) 36 | od.popitem() # 有序删除:右侧 37 | print(od) 38 | od.clear() # 清空 39 | print(od) 40 | -------------------------------------------------------------------------------- /chapter004/chapter_0412.py: -------------------------------------------------------------------------------- 1 | # 默认字典: 2 | from collections import defaultdict 3 | values = [11, 22, 33, 44, 55, 66, 77, 88, 99, 90] 4 | # defaultdict(必须为callable一个可调用的) 5 | my_dict = defaultdict(list) 6 | for value in values: 7 | if value > 66: 8 | my_dict['k1'].append(value) 9 | else: 10 | my_dict['k2'].append(value) 11 | print(my_dict) 12 | 13 | # 如果key不存在返回None 14 | print(my_dict['k3']) 15 | -------------------------------------------------------------------------------- /chapter004/chapter_0413.py: -------------------------------------------------------------------------------- 1 | # 可命名元组 2 | import collections 3 | # 通过namedtuple自定义一个TupleName类 4 | TupleName=collections.namedtuple('TupleName',['a','b','c']) 5 | # 通过类创建对象obj 6 | obj = TupleName(11, 22, 33) 7 | print(obj) 8 | 9 | -------------------------------------------------------------------------------- /chapter004/toutiao.py: -------------------------------------------------------------------------------- 1 | # 搜索关键字,并下载文章标题 2 | import requests 3 | import json 4 | from urllib.parse import quote 5 | print(quote('广州地铁塌陷')) 6 | ''' 7 | >>> from urllib.parse import quote 8 | >>> quote('汉字') 9 | '%E6%B1%89%E5%AD%97' 10 | >>> import urllib 11 | >>> urllib.parse.unquote('%E6%B1%89%E5%AD%97') 12 | '汉字' 13 | >>> 14 | >>> url = 'http://localhost:8000/odooallpro/%E7%9B%B8%E5%86%8C/' 15 | >>> urllib.parse.unquote(url) 16 | 'http://localhost:8000/odooallpro/相册/' 17 | >>> 18 | ''' 19 | 20 | def page(startPage, endPage): 21 | for i in range(startPage-1, endPage): 22 | print("当前第%s页" % (i+1)) 23 | url="https://www.toutiao.com/api/search/content/?aid=24&app_name=web_search&offset={}&format=json&keyword=%E5%B9%BF%E5%B7%9E%E5%9C%B0%E9%93%81%E5%A1%8C%E9%99%B7&autoload=true&count=20&en_qc=1&cur_tab=1&from=search_tab&pd=synthesis×tamp=1562467283218".format(i*20) 24 | print(url) 25 | isPage=loadPage(url) 26 | if isPage==False: 27 | return 28 | 29 | def loadPage(url): 30 | headers = { 31 | "user-agent": "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36", 32 | "cookie":"tt_webid=6710713392061285902; WEATHER_CITY=%E5%8C%97%E4%BA%AC; tt_webid=6710713392061285902; UM_distinctid=16bc9db8a29f6-0417349b599406-516d3e71-13c680-16bc9db8a2d85; csrftoken=5eb2a0e00bcbb888f417ef261ee5269a; CNZZDATA1259612802=1761938442-1562456487-https%253A%252F%252Fwww.baidu.com%252F%7C1562461887; s_v_web_id=ddb620b1224506f21ba99de20d4169e3; __tasessionId=ned4t635k1562467258609" 33 | } 34 | try: 35 | data = requests.get(url, headers=headers).text 36 | news = json.loads(data) 37 | print(news) 38 | for new in news["data"]: 39 | if "title" in new.keys(): 40 | print(new["title"]) 41 | except Exception as e: 42 | print(e) 43 | return False 44 | return True 45 | 46 | if __name__ == '__main__': 47 | startPage = int(input("请输入起始页码:")) 48 | endPage = int(input("请输入终止页码:")) 49 | page(startPage,endPage) 50 | 51 | -------------------------------------------------------------------------------- /chapter005/chapter_0501.py: -------------------------------------------------------------------------------- 1 | # 顺序语句 2 | print("Line1") 3 | print("Line2") 4 | print("Line3") 5 | 6 | # 语句 + 函数 7 | print("顺序语句") 8 | 9 | 10 | # 函数声明:声明时不会被调用 11 | def fun(): 12 | print("fun函数") 13 | 14 | 15 | # 函数调用:顺序执行,即使有主函数 16 | fun() 17 | 18 | ''' 19 | 20 | 21 | # 主函数 22 | def main(): 23 | print("main函数执行:") 24 | fun() 25 | 26 | 27 | # 执行主函数 28 | if __name__ == '__main__': 29 | main() 30 | ''' -------------------------------------------------------------------------------- /chapter005/chapter_0502.py: -------------------------------------------------------------------------------- 1 | # 条件语句 2 | age = int(input("请输入你的年龄:")) 3 | if age <= 18: 4 | print("未成年人") 5 | elif 18 < age < 35: 6 | print("青年人") 7 | elif 35 < age < 50: 8 | print("中年人") 9 | else: 10 | print("火星人") 11 | -------------------------------------------------------------------------------- /chapter005/chapter_0503.py: -------------------------------------------------------------------------------- 1 | # 循环语句 2 | # 3 | # 01.for 4 | print("---------for-----------") 5 | # TypeError: 'int' object is not iterable 6 | ''' 7 | count = 10 8 | for i in count: 9 | print(i) 10 | i = i + 1 11 | 12 | 13 | ''' 14 | 15 | 16 | index = 0 17 | numbers = [1, 3, 5, 7, 9, 11, 13, 20, 29] 18 | for index in range(len(numbers)): 19 | print(numbers[index]) 20 | 21 | 22 | # 02.while 23 | print("---------while-----------") 24 | j = 0 25 | counts = 10 26 | while j < counts: 27 | print(j) 28 | j = j + 1 29 | else: 30 | print('Else语句被执行,j = ', j) 31 | -------------------------------------------------------------------------------- /chapter005/chapter_0504.py: -------------------------------------------------------------------------------- 1 | # break 2 | print("----------break--------------") 3 | index = 0 4 | numbers = [1, 3, 5, 7, 9, 11, 13, 20, 29] 5 | for index in range(len(numbers)): 6 | if index == 3: 7 | break 8 | print(numbers[index]) 9 | 10 | # continue 11 | print("----------continue--------------") 12 | index = 0 13 | numbers = [1, 3, 5, 7, 9, 11, 13, 20, 29] 14 | for index in range(len(numbers)): 15 | if index == 3: 16 | continue 17 | print(numbers[index]) 18 | 19 | # pass 20 | print("----------pass--------------") 21 | index = 0 22 | numbers = [1, 3, 5, 7, 9, 11, 13, 20, 29] 23 | 24 | for index in range(len(numbers)): 25 | if index == 3: 26 | pass 27 | print(numbers[index]) -------------------------------------------------------------------------------- /chapter005/chapter_0505.py: -------------------------------------------------------------------------------- 1 | # 嵌套循环 2 | 3 | # for 4 | print("----------for--------------") 5 | for i in range(1, 10): 6 | for j in range(1, i+1): 7 | k = i*j 8 | print("%s*%s=%s" % (i, j, k), end=' ') 9 | print('i = %d' % i) 10 | 11 | print("----------while--------------") 12 | i = 1 13 | j = 1 14 | while i < 10: 15 | j = 1 16 | while j < i + 1: 17 | k = i * j 18 | print("%s*%s=%s" % (i, j, k), end=' ') 19 | j = j + 1 20 | i = i + 1 21 | print('i==%d' % i) 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /chapter005/chapter_0506.py: -------------------------------------------------------------------------------- 1 | # 嵌套条件 2 | num = int(input("输入一个数字:")) 3 | if num % 2 == 0: 4 | if num % 3 == 0: 5 | print("你输入的数字可以整除 2 和 3") 6 | else: 7 | print("你输入的数字可以整除 2,但不能整除 3") 8 | else: 9 | if num % 3 == 0: 10 | print("你输入的数字可以整除 3,但不能整除 2") 11 | else: 12 | print("你输入的数字不能整除 2 和 3") 13 | -------------------------------------------------------------------------------- /chapter006/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhangziliang04/RoadPython/5a68ed62b987c228b5e56f445d43904223dfe6a9/chapter006/__init__.py -------------------------------------------------------------------------------- /chapter006/chapter_0601.py: -------------------------------------------------------------------------------- 1 | # 输出语句 2 | print("输出表达式1,", "输出表达式2") 3 | 4 | # 输入语句 5 | x = input("请输入:x=") 6 | y = input("请输入:y=") 7 | z = x+y 8 | print("x+y=", z) 9 | 10 | 11 | # 常见异常 12 | # print "常见异常" 13 | # print(“常见异常”) -------------------------------------------------------------------------------- /chapter006/chapter_0602.py: -------------------------------------------------------------------------------- 1 | # 字符串格式控制 2 | mystr = "Python全栈工程师" 3 | print("str:", str(mystr)) 4 | print("repr:", repr(mystr)) 5 | print("str(int):", str(1/4)) 6 | 7 | # % 格式说明 8 | PI = 3.1415926 9 | print("PI-整型:%2d" % PI) 10 | print("PI-字符串:%s" % PI) 11 | print("PI-浮点数:%f" % PI) 12 | print("PI-两位小数:%.2f" % PI) 13 | print("指定占位符宽度(左对齐):%-5.2f" % PI) 14 | print("字符串截取:%.2s" % PI) 15 | 16 | 17 | # str.format() 18 | print("------str.format()----------") 19 | print("PI-整型:{}".format(PI)) 20 | print("PI-实数:{0:f}".format(PI)) 21 | print("PI-两位小数:{0:.2f}".format(PI)) 22 | print("PI-指定占位符宽度:{0:5.2f}".format(PI)) 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /chapter006/chapter_0603.py: -------------------------------------------------------------------------------- 1 | # 文件打开 2 | file = open("hello.txt", "r") 3 | print("open") 4 | file.close() 5 | 6 | # 文件写入 write() 7 | print("--------- write ------------") 8 | file = open("hello.txt", "a+") 9 | file.write(" Python\n") 10 | file.close() 11 | 12 | # 文件写入 writelines() 13 | print("--------- writelines ------------") 14 | data = ["string1", "string2"] 15 | file = open("hello.txt", "a+") 16 | file.writelines(data) 17 | # file.writelines([line+'\n' for line in data]) # 换行处理 18 | file.close() 19 | 20 | 21 | # 文件读取:read 22 | print("--------- read------------") 23 | file = open("hello.txt", "r") 24 | context = file.read() 25 | print(context) 26 | file.close() 27 | 28 | # 文件读取:readline 29 | print("--------- readline------------") 30 | file = open("hello.txt", "r") 31 | line = file.readline() 32 | print(line) 33 | file.close() 34 | 35 | # 文件读取:readlines 所有行,直到文件结束 36 | print("--------- readlines------------") 37 | file = open("hello.txt", "r") 38 | line = file.readlines() 39 | print(line) 40 | file.close() 41 | 42 | -------------------------------------------------------------------------------- /chapter006/chapter_0604.py: -------------------------------------------------------------------------------- 1 | # 矩形输出 2 | print("----------------------矩形输出---------------------------") 3 | for i in range(1,10): 4 | for j in range(1,10): 5 | if i <= 9: 6 | print(f"{j}×{i} = {i * j}", end="\t") 7 | print("") 8 | print("----------------------左下三角形---------------------------") 9 | # 左下三角形式九九乘法表 10 | for i in range(1,10): 11 | for j in range(1,i+1): 12 | print(f"{j}×{i}={i*j}", end="\t") 13 | print(" ") 14 | 15 | # 左上三角形式九九乘法表 16 | print("----------------------左上三角形---------------------------") 17 | for i in range(1,10): 18 | for j in range(i,10): 19 | print(f"{i}×{j}={i * j}", end="\t") 20 | print(" ") 21 | 22 | # 右下三角形式九九乘法表 23 | print("----------------------右下三角形---------------------------") 24 | for i in range(1,10): 25 | for k in range(1,10-i): 26 | print(end=" ") #此处七个空格 27 | for j in range(1,i+1): 28 | print("%d×%d=%2d" % (i, j, i*j), end=" ") 29 | # 切记此处不能用格式化输出.format方式或者f"{}", 要用格式化输出只能pycharm中才会显示下面的样式。 30 | print(" ") 31 | 32 | # 右上三角形式九九乘法表 33 | print("----------------------右上三角形---------------------------") 34 | for i in range(1, 10): 35 | for k in range(1, i): 36 | print(end=" ") #此处8个空格 37 | for j in range(i, 10): 38 | print("%d×%d=%2d" % (i, j, i * j), end=" ") # 切记此处不能用格式化输出.format方式或者f"{}", 要用格式化输出只能pycharm中才会显示下面的样式。 39 | print(" ") 40 | -------------------------------------------------------------------------------- /chapter006/hello.txt: -------------------------------------------------------------------------------- 1 | string1 2 | string2 3 | string1string2 -------------------------------------------------------------------------------- /chapter007/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhangziliang04/RoadPython/5a68ed62b987c228b5e56f445d43904223dfe6a9/chapter007/__init__.py -------------------------------------------------------------------------------- /chapter007/chapter_0701.py: -------------------------------------------------------------------------------- 1 | # 文件写入 2 | import os 3 | import sys 4 | 5 | # 打开文件 6 | fd = os.open("hello.txt", os.O_RDWR | os.O_CREAT) 7 | 8 | # 写入字符串 9 | os.write(fd, str.encode("写入测试")) 10 | 11 | # 关闭文件 12 | os.close(fd) 13 | 14 | print("关闭文件成功!!") 15 | -------------------------------------------------------------------------------- /chapter007/chapter_0702.py: -------------------------------------------------------------------------------- 1 | # 文件读取 2 | import os, sys 3 | 4 | # 打开文件 5 | fd = os.open("hello.txt", os.O_RDWR) 6 | 7 | # 读取文本 8 | result = os.read(fd, 12) 9 | print(result) 10 | 11 | # 关闭文件 12 | os.close(fd) 13 | print("关闭文件成功!!") 14 | -------------------------------------------------------------------------------- /chapter007/chapter_0703.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhangziliang04/RoadPython/5a68ed62b987c228b5e56f445d43904223dfe6a9/chapter007/chapter_0703.py -------------------------------------------------------------------------------- /chapter007/chapter_0704.py: -------------------------------------------------------------------------------- 1 | # 文件描述符复制 2 | import os, sys 3 | # 打开文件 4 | fd = os.open("hello.txt", os.O_RDWR | os.O_CREAT) 5 | # 复制文件描述符 6 | d_fd = os.dup(fd) 7 | # 使用复制的文件描述符写入文件 8 | os.write(d_fd, "基于文件描述符复制,写入测试".encode()) 9 | # 关闭文件 10 | os.closerange(fd, d_fd) 11 | print("关闭所有文件成功!!") 12 | -------------------------------------------------------------------------------- /chapter007/chapter_0705.py: -------------------------------------------------------------------------------- 1 | import os 2 | # 打开一个文件 3 | file = open('hello.txt', os.O_RDWR | os.O_CREAT) 4 | # 将这个文件描述符代表的文件,传递给 1 描述符指向的文件(stdout) 5 | # 目标、源 6 | os.dup2(file.fileno(), 1) 7 | # 关闭文件 8 | file.close() 9 | # print 输出到标准输出流,就是文件描述符1 10 | print('输出1') 11 | print('输出2') 12 | -------------------------------------------------------------------------------- /chapter007/chapter_0706.py: -------------------------------------------------------------------------------- 1 | # 文件写入 2 | import os, sys 3 | 4 | # 打开文件 5 | fd = os.open("hello.txt", os.O_RDWR | os.O_CREAT) 6 | 7 | # 写入字符串 8 | str1 = "This is a Test" 9 | ret = os.write(fd, bytes(str1, 'GBK')) 10 | 11 | # 输入返回值 12 | print("写入的位数为: ", ret) 13 | print("内容写入成功") 14 | 15 | # 关闭文件 16 | os.close(fd) 17 | print("关闭文件成功!!") 18 | -------------------------------------------------------------------------------- /chapter007/chapter_0707.py: -------------------------------------------------------------------------------- 1 | # 文件写入 2 | import os, sys 3 | 4 | # 打开文件 5 | fd = os.open("hello.txt", os.O_RDWR | os.O_CREAT) 6 | 7 | # 写入字符串 8 | str1 = "This is a Test" 9 | ret = os.write(fd, bytes(str1, 'GBK')) 10 | 11 | # 输入返回值 12 | print("写入的位数为: ", ret) 13 | print("内容写入成功") 14 | 15 | # 关闭文件 16 | os.closerange(fd, fd) 17 | print("关闭文件成功!") 18 | -------------------------------------------------------------------------------- /chapter007/chapter_0708.py: -------------------------------------------------------------------------------- 1 | # 根据文件,修改当前目录 2 | import os 3 | 4 | # 输出当前目录 5 | print("当前工作目录为 : %s" % os.getcwd()) 6 | 7 | # 打开新目录 temp2 8 | fd = os.open("temp2/hello.txt", os.O_RDONLY) 9 | 10 | # 修改当前目录 11 | os.fchdir(fd) 12 | # 输出当前目录 13 | print("当前工作目录为 : %s" % os.getcwd()) 14 | # 关闭打开的目录 15 | os.close(fd) 16 | -------------------------------------------------------------------------------- /chapter007/chapter_0709.py: -------------------------------------------------------------------------------- 1 | # 修改文件属性,仅限Unix使用 2 | import os 3 | import stat 4 | 5 | # 打开文件 6 | fd = os.open("hello.txt", os.O_RDONLY) 7 | 8 | # 设置文件可通过组执行 9 | os.fchmod(fd, stat.S_IXGRP) 10 | 11 | # 设置文件可被其他用户写入 12 | os.fchmod(fd, stat.S_IWOTH) 13 | 14 | print("修改权限成功!!") 15 | 16 | # 关闭文件 17 | os.close(fd) 18 | -------------------------------------------------------------------------------- /chapter007/hello.txt: -------------------------------------------------------------------------------- 1 | 基于文件描述符复制,写入测试 -------------------------------------------------------------------------------- /chapter007/temp2/hello.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhangziliang04/RoadPython/5a68ed62b987c228b5e56f445d43904223dfe6a9/chapter007/temp2/hello.txt -------------------------------------------------------------------------------- /chapter008/111.txt: -------------------------------------------------------------------------------- 1 | 基于文件描述符复制,写入测试输出1 2 | 输出2 3 | -------------------------------------------------------------------------------- /chapter008/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhangziliang04/RoadPython/5a68ed62b987c228b5e56f445d43904223dfe6a9/chapter008/__init__.py -------------------------------------------------------------------------------- /chapter008/chapter_0801.py: -------------------------------------------------------------------------------- 1 | # 文件&文件夹 访问权限验证 2 | import os, sys 3 | # 假定 hello.txt 文件存在,并有读写权限; 4 | # 注意:如果文件不存在,显示为False 5 | # 01.是否存在 6 | ret = os.access("./temp", os.F_OK) 7 | print("F_OK - 返回值 %s" % ret) 8 | 9 | # 02.是否可读 10 | ret = os.access("111.txt", os.R_OK) 11 | print("R_OK - 返回值 %s" % ret) 12 | 13 | # 03. 是否可写 14 | ret = os.access("hello.txt", os.W_OK) 15 | print("W_OK - 返回值 %s" % ret) 16 | 17 | # 04. 是否可执行 18 | ret = os.access("hello.txt", os.X_OK) 19 | print("X_OK - 返回值 %s" % ret) 20 | -------------------------------------------------------------------------------- /chapter008/chapter_0802.py: -------------------------------------------------------------------------------- 1 | # 改变当前工作目录 2 | import os, sys 3 | 4 | path = "/temp" 5 | # 查看当前工作目录 6 | ret1 = os.getcwd() 7 | print("当前工作目录为: %s" % ret1) 8 | # 修改当前工作目录 9 | os.chdir(path) 10 | 11 | # 查看修改后的工作目录 12 | ret2 = os.getcwd() 13 | print("目录修改成功:%s" % ret2) 14 | 15 | 16 | -------------------------------------------------------------------------------- /chapter008/chapter_0803.py: -------------------------------------------------------------------------------- 1 | # 更改文件权限 2 | import os, sys, stat 3 | 4 | # 设置只读属性 5 | os.chmod("hello.txt", stat.S_IREAD) 6 | 7 | # 设置写属性 8 | os.chmod("hello.txt", stat.S_IWRITE) 9 | 10 | print("修改成功!!") 11 | -------------------------------------------------------------------------------- /chapter008/chapter_0804.py: -------------------------------------------------------------------------------- 1 | # !/usr/bin/python 2 | # -*- coding: UTF-8 -*- 3 | import os, sys 4 | 5 | # 更改当前进程的根目录为指定的目录,使用该函数需要管理员权限 6 | # 设置根目录为 /temp 7 | os.chroot("/temp") 8 | print("修改根目录成功!!") -------------------------------------------------------------------------------- /chapter008/chapter_0805.py: -------------------------------------------------------------------------------- 1 | # !/usr/bin/python 2 | # -*- coding: UTF-8 -*- 3 | import os, sys 4 | # 列出目录 5 | print("目录为: %s" % os.listdir(os.getcwd())) 6 | 7 | # 移除:目录必须为空,否则异常 8 | os.removedirs("temp") 9 | 10 | # 列出移除后的目录 11 | print("移除后目录为:%s" % os.listdir(os.getcwd())) 12 | -------------------------------------------------------------------------------- /chapter008/chapter_0806.py: -------------------------------------------------------------------------------- 1 | # !/usr/bin/python 2 | # -*- coding: UTF-8 -*- 3 | import os, sys 4 | 5 | # 列出当前目录 6 | print("目录为: %s" % os.listdir(os.getcwd())) 7 | 8 | # 重命名文件夹 9 | os.rename("temp", "temp3") 10 | print("重命名成功。") 11 | 12 | # 列出重命名后的目录 13 | print("目录为: %s" % os.listdir(os.getcwd())) 14 | -------------------------------------------------------------------------------- /chapter008/chapter_0807.py: -------------------------------------------------------------------------------- 1 | # !/usr/bin/python 2 | # -*- coding: UTF-8 -*- 3 | import os, sys 4 | 5 | # 列出当前目录 6 | print("目录为: %s" % os.listdir(os.getcwd())) 7 | 8 | # 重命名文件夹 9 | os.renames("hello.txt", "temp/111.txt") 10 | print("重命名成功。") 11 | 12 | # 列出重命名后的目录 13 | print("目录为: %s" % os.listdir(os.getcwd())) 14 | -------------------------------------------------------------------------------- /chapter008/hello.txt: -------------------------------------------------------------------------------- 1 | 111 2 | -------------------------------------------------------------------------------- /chapter008/temp2/111.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhangziliang04/RoadPython/5a68ed62b987c228b5e56f445d43904223dfe6a9/chapter008/temp2/111.txt -------------------------------------------------------------------------------- /chapter009/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhangziliang04/RoadPython/5a68ed62b987c228b5e56f445d43904223dfe6a9/chapter009/__init__.py -------------------------------------------------------------------------------- /chapter009/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhangziliang04/RoadPython/5a68ed62b987c228b5e56f445d43904223dfe6a9/chapter009/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /chapter009/__pycache__/chapter_0901.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhangziliang04/RoadPython/5a68ed62b987c228b5e56f445d43904223dfe6a9/chapter009/__pycache__/chapter_0901.cpython-36.pyc -------------------------------------------------------------------------------- /chapter009/__pycache__/chapter_0902.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhangziliang04/RoadPython/5a68ed62b987c228b5e56f445d43904223dfe6a9/chapter009/__pycache__/chapter_0902.cpython-36.pyc -------------------------------------------------------------------------------- /chapter009/chapter_0901.py: -------------------------------------------------------------------------------- 1 | def add(a, b): 2 | """加法函数""" 3 | c = a + b 4 | print("add 函数:%d + %d = %d " % (a, b, c)) 5 | return c 6 | 7 | 8 | # 函数定义: 求和函数 9 | def add1(a, b): 10 | """加法函数""" 11 | c = a + b 12 | print("add1 函数:%d + %d = %d " % (a, b, c)) 13 | return c 14 | 15 | 16 | def add2(a, b): 17 | """加法函数""" 18 | c = a + b 19 | print("add2 函数:%d + %d = %d " % (a, b, c)) 20 | return c 21 | 22 | # add(10, 20) 23 | 24 | 25 | def main(): 26 | a = int(input("请输入第一个数字:")) 27 | b = int(input("请输入第二个数字:")) 28 | add(a, b) 29 | 30 | 31 | # main 函数 32 | if __name__ == '__main__': 33 | print("main:", __name__) 34 | main() 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /chapter009/chapter_0902.py: -------------------------------------------------------------------------------- 1 | # 模块 2 | import chapter009.chapter_0901 3 | 4 | 5 | # 主函数 6 | def main(): 7 | a = int(input("请输入第一个数字:")) 8 | b = int(input("请输入第二个数字:")) 9 | chapter009.chapter_0901.add(a, b) 10 | chapter009.chapter_0901.add1(a, b) 11 | chapter009.chapter_0901.add2(a, b) 12 | 13 | 14 | # 执行主函数 15 | if __name__ == '__main__': 16 | main() -------------------------------------------------------------------------------- /chapter009/chapter_0903.py: -------------------------------------------------------------------------------- 1 | # 模块 2 | from chapter009.chapter_0901 import add, add1 3 | 4 | 5 | # 主函数 6 | def main(): 7 | a = int(input("请输入第一个数字:")) 8 | b = int(input("请输入第二个数字:")) 9 | add1(a, b) 10 | 11 | 12 | # 执行主函数 13 | if __name__ == '__main__': 14 | main() -------------------------------------------------------------------------------- /chapter009/chapter_0904.py: -------------------------------------------------------------------------------- 1 | # 打印搜索路径 2 | import sys 3 | print(sys.path) 4 | 5 | 6 | # 添加搜索路径 7 | sys.path.append("..") -------------------------------------------------------------------------------- /chapter010/chapter_01001.py: -------------------------------------------------------------------------------- 1 | # 类的声明 2 | class MyClass: 3 | """类注释部分 """ 4 | # 成员变量 5 | age = None 6 | name = None 7 | 8 | # 成员函数 9 | def get_age(self): 10 | print(self.age) 11 | return self.age 12 | 13 | def set_age(self, age): 14 | self.age = age 15 | print(age) 16 | 17 | 18 | def main(): 19 | # 无参数的对象声明 20 | mycls = MyClass() 21 | print(mycls.age) 22 | mycls.get_age() 23 | mycls.set_age(10) 24 | print(mycls.age) 25 | 26 | 27 | # 执行主函数 28 | if __name__ == '__main__': 29 | main() 30 | 31 | 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /chapter010/chapter_01002.py: -------------------------------------------------------------------------------- 1 | # 类的声明 2 | class MyClass: 3 | """类注释部分 """ 4 | # 初始化函数 5 | def __init__(self, age): 6 | self.age = age 7 | 8 | # 成员函数 9 | def get_age(self): 10 | print(self.age) 11 | return self.age 12 | 13 | def set_age(self, age): 14 | self.age = age 15 | print(age) 16 | 17 | 18 | def main(): 19 | # 有参数的对象声明 20 | mycls = MyClass(20) 21 | mycls.get_age() 22 | 23 | # 执行主函数 24 | if __name__ == '__main__': 25 | main() 26 | -------------------------------------------------------------------------------- /chapter010/chapter_01003.py: -------------------------------------------------------------------------------- 1 | # 类的声明 2 | class MyClass: 3 | """类注释部分 """ 4 | # 初始化函数 5 | def __init__(self, age, name, job): # 特殊函数:双下划线开始+双下划线结束,系统定义的特殊函数,不能在类外部访问 6 | self.age = age # 公有成员: 对所有人公开,可以在类的外部直接访问 7 | self._name = name # 保护成员:不能够通过 "from module import *" 的方式导入 8 | self.__job = job # 私有成员:双下划线开始,无双下划线结束;类的外部不能直接访问,需要调用类的公开成员方法访问 9 | 10 | # 公有成员函数 11 | def get_age(self): 12 | print(self.age) 13 | return self.age 14 | 15 | def set_age(self, age): 16 | self.age = age 17 | print(age) 18 | 19 | # 保护成员函数 20 | def _get_name(self): 21 | return self._name 22 | 23 | # 私有成员函数 24 | def __get_job(self): 25 | return self.__job 26 | 27 | 28 | 29 | def main(): 30 | # 有参数的对象声明 31 | mycls = MyClass(20, "张子良", "Python全栈工程师") 32 | mycls.get_age() 33 | print(mycls._name) # 访问保护成员变量 34 | # print(mycls.__job) # 访问私有成员变量,会提示无法找到该变量 35 | 36 | mycls._get_name() # 访问保护成员函数 37 | mycls.__get_job() # 访问私有成员函数 38 | 39 | 40 | # 执行主函数 41 | if __name__ == '__main__': 42 | main() 43 | -------------------------------------------------------------------------------- /chapter010/chapter_01004.py: -------------------------------------------------------------------------------- 1 | # 类的继承 2 | class BaseClass: 3 | """基类""" 4 | # 成员变量 5 | def __init__(self, age, name, job): # 特殊函数:双下划线开始+双下划线结束,系统定义的特殊函数,不能在类外部访问 6 | self.age = age # 公有成员: 对所有人公开,可以在类的外部直接访问 7 | self._name = name # 保护成员:不能够通过 "from module import *" 的方式导入 8 | self.__job = job # 私有成员:双下划线开始,无双下划线结束;类的外部不能直接访问,需要调用类的公开成员方法访问 9 | 10 | print("BaseClass init") 11 | 12 | # 成员函数 13 | def get_age(self): 14 | print(self.age) 15 | return self.age 16 | 17 | def set_age(self, age): 18 | self.age = age 19 | print(age) 20 | # 保护成员函数 21 | def _get_name(self): 22 | return self._name 23 | 24 | # 私有成员函数 25 | def __get_job(self): 26 | return self.__job 27 | 28 | 29 | # 派生类 30 | class DriverdClass(BaseClass): 31 | def __init__(self, age, name, job, cardno): 32 | BaseClass.__init__(self, age, name, job) 33 | self.cardno = cardno 34 | print("DriverdClass init") 35 | 36 | def get_age(self): 37 | print("DriverdClass get_age") 38 | 39 | 40 | def main(): 41 | # 有参数的对象声明 42 | mycls = DriverdClass(20, "张子良", "Python全栈工程师", "SVIP_0001") 43 | mycls.get_age() # 增加重载的情况 44 | print(mycls._name) 45 | mycls._get_name() # 访问保护成员函数 46 | 47 | 48 | # 执行主函数 49 | if __name__ == '__main__': 50 | main() -------------------------------------------------------------------------------- /chapter011/chapter_01101.py: -------------------------------------------------------------------------------- 1 | # 语法错误 2 | while True print('Hello world') 3 | -------------------------------------------------------------------------------- /chapter011/chapter_01102.py: -------------------------------------------------------------------------------- 1 | # 语法错误-修正后 2 | while True: 3 | print('Hello world') -------------------------------------------------------------------------------- /chapter011/chapter_01103.py: -------------------------------------------------------------------------------- 1 | # 语法错误 2 | if True print('Hello woifrld') -------------------------------------------------------------------------------- /chapter011/chapter_01104.py: -------------------------------------------------------------------------------- 1 | # 运行异常 2 | # 01-分母为0 3 | a = 10 * (1/0) 4 | print(a) 5 | 6 | # 02-变量未声明 7 | b = 4 + spam*3 8 | print(b) 9 | 10 | # 03-数据类型 11 | c = '2' + 2 12 | print(c) 13 | -------------------------------------------------------------------------------- /chapter011/chapter_01105.py: -------------------------------------------------------------------------------- 1 | # 运行异常 2 | # 01-分母为0 3 | a = 10 * (1/2) 4 | print(a) 5 | 6 | # 02-变量未声明 7 | b = 4 + spam*3 8 | print(b) 9 | 10 | # 03-数据类型 11 | c = '2' + 2 12 | print(c) 13 | 14 | -------------------------------------------------------------------------------- /chapter011/chapter_01106.py: -------------------------------------------------------------------------------- 1 | # 运行异常 2 | # 01-分母为0 3 | a = 10 * (1/2) 4 | print(a) 5 | 6 | # 02-变量未声明 7 | b = 4 + spam*3 8 | print(b) 9 | 10 | # 03-数据类型 11 | c = '2' + 2 12 | print(c) -------------------------------------------------------------------------------- /chapter011/chapter_01107.py: -------------------------------------------------------------------------------- 1 | # 异常捕获 2 | try: 3 | # 正常语句 4 | b = 4 + spam * 3 5 | print(b) 6 | except ValueError: 7 | print("ValueError") 8 | except OSError: 9 | print("OSError") 10 | # 注意:未知类型,全部在此处处理 11 | except: 12 | print("未知异常") 13 | # 无以上异常,执行 14 | else: 15 | print("Else") 16 | # 无论Try子句里面有没有发生异常,finally 子句都会执行 17 | finally: 18 | print("Finally") 19 | -------------------------------------------------------------------------------- /chapter011/chapter_01108.py: -------------------------------------------------------------------------------- 1 | # 主动抛出异常 2 | try: 3 | raise NameError('NameError Message') 4 | except NameError: 5 | print('NameError Message Except!') 6 | 7 | -------------------------------------------------------------------------------- /chapter011/chapter_01109.py: -------------------------------------------------------------------------------- 1 | # 自定义异常类型: 基于Exception类派生 2 | class MyError(Exception): 3 | def __init__(self, value): 4 | self.value = value 5 | 6 | def __str__(self): 7 | return repr(self.value) 8 | # 异常捕获 9 | try: 10 | raise MyError("MyError Message") 11 | except NameError: 12 | print('NameError Message Except!') 13 | except MyError as error: 14 | print('MyError Message Except:',error.value) -------------------------------------------------------------------------------- /chapter011/chapter_01110.py: -------------------------------------------------------------------------------- 1 | # 运行时异常练习 2 | import sys 3 | try: 4 | f = open('myfile.txt') 5 | s = f.readline() 6 | i = int(s.strip()) 7 | except OSError as err: 8 | print("OS error: {0}".format(err)) 9 | except ValueError: 10 | print("Could not convert data to an integer.") 11 | except: 12 | print("Unexpected error:", sys.exc_info()[0]) 13 | raise 14 | -------------------------------------------------------------------------------- /chapter011/chapter_01111.py: -------------------------------------------------------------------------------- 1 | # 断点调试 2 | import sys 3 | try: 4 | f = open('myfile.txt') 5 | s = f.readline() 6 | i = int(s.strip()) 7 | except OSError as err: 8 | print("OS error: {0}".format(err)) 9 | except ValueError: 10 | print("Could not convert data to an integer.") 11 | except: 12 | print("Unexpected error:", sys.exc_info()[0]) 13 | raise -------------------------------------------------------------------------------- /chapter011/chapter_01112.py: -------------------------------------------------------------------------------- 1 | # 断点调试-练一练 2 | try: 3 | # 正常语句 4 | b = 4 + spam * 3 5 | print(b) 6 | except ValueError: 7 | print("ValueError") 8 | except OSError: 9 | print("OSError") 10 | # 注意:未知类型,全部在此处处理 11 | except: 12 | print("未知异常") 13 | # 无以上异常,执行 14 | else: 15 | print("Else") 16 | # 无论Try子句里面有没有发生异常,finally 子句都会执行 17 | finally: 18 | print("Finally") -------------------------------------------------------------------------------- /chapter012/chapter_01200.py: -------------------------------------------------------------------------------- 1 | # 模块函数:直接匹配 2 | import re 3 | url = "http://m.study.163.com/provider/1016839500/index.htm?share=2&shareId=1016839500" 4 | 5 | # 方法1:pattern独立存在 6 | print("-----------------re.match()----------------------") 7 | print(re.match('http', url)) 8 | 9 | 10 | # 方法2:pattern复用 11 | patter1 = re.compile('http') 12 | print(patter1.match(url)) 13 | 14 | 15 | -------------------------------------------------------------------------------- /chapter012/chapter_01201.py: -------------------------------------------------------------------------------- 1 | # 模块函数:直接匹配 2 | import re 3 | url = "http://m.study.163.com/provider/1016839500/index.htm?share=2&shareId=1016839500" 4 | 5 | # re.match() :从起始位置开始匹配 6 | print("-----------------re.match()----------------------") 7 | print(re.match('http', url)) 8 | print(re.match('com', url)) 9 | 10 | # re.search() 11 | print("-----------------re.search()----------------------") 12 | print(re.search('http', url)) 13 | print(re.search('com', url)) 14 | 15 | # re.findall 16 | url2 = "http://m.study.163.com/provider/1016839500/index.htm?share=2&shareId=1016839500https" 17 | print("-----------------re.findall()----------------------") 18 | print(re.findall('http', url2)) 19 | 20 | # re.sub 21 | print("-----------------re.sub()----------------------") 22 | print(re.sub('http', 'https', url)) 23 | -------------------------------------------------------------------------------- /chapter012/chapter_01202.py: -------------------------------------------------------------------------------- 1 | # 正则表达式对象(正则对象) 2 | import re 3 | url = "http://m.study.163.com/provider/1016839500/index.htm?share=2&shareId=1016839500" 4 | pattern1 = re.compile('http') 5 | pattern2 = re.compile('com') 6 | 7 | # pattern.match() :从起始位置开始匹配 8 | print("-----------------pattern.match()----------------------") 9 | print(pattern1.match(url)) 10 | print(pattern2.match(url)) 11 | 12 | # pattern.search() 13 | print("-----------------pattern.search()----------------------") 14 | print(pattern1.search(url)) 15 | print(pattern2.search(url)) 16 | 17 | # pattern.findall 18 | url2 = "http://m.study.163.com/provider/1016839500/index.htm?share=2&shareId=1016839500https" 19 | print("-----------------pattern.findall()----------------------") 20 | print(pattern1.findall(url2)) 21 | 22 | # pattern.sub 23 | print("-----------------pattern.sub()----------------------") 24 | print(pattern1.sub('https', url2)) 25 | -------------------------------------------------------------------------------- /chapter012/chapter_01203.py: -------------------------------------------------------------------------------- 1 | # 身份证匹配案例 2 | import re 3 | 4 | # 待匹配字符串 5 | str1 = '110101198001017032' # 18位身份证号 6 | str2 = '1101011980010170' # 16位字符串 7 | 8 | # 模式字符串 9 | p1 = '^[1-9]\d{13,16}[0-9x]$' 10 | p2 = '^[1-9]\d{14}(\d{2}[0-9x])?$' 11 | p3 = '^([1-9]\d{16}[0-9x]|[1-9]\d{14})$' 12 | 13 | # 模式字符串异常 - 同时可匹配多个场景的情况 14 | # 有效的身份证号可以匹配:18位 15 | print("-----------------有效身份证----------------------") 16 | m = re.match(p1, str1) 17 | print(m.group(0)) 18 | # 无效的省份证号,也可以匹配 16位数字 19 | print("-----------------非有效身份证----------------------") 20 | m = re.match(p1, str2) 21 | print(m.group(0)) 22 | 23 | # 模式字符串优化: 24 | # 约束后3位出现的次数为:0-1次; 15+3 25 | print("-----------------增加后三位约束----------------------") 26 | # p2 = '^[1-9]\d{14}(\d{2}[0-9x])?$' 27 | print(re.match(p2, str2)) 28 | 29 | print("-----------------先匹配情况1,如果失败再匹配情况2------------------") 30 | # p3 = '^([1-9]\d{16}[0-9x]|[1-9]\d{14})$' 31 | m = re.match(p3, str1) 32 | print(m.group(0)) 33 | 34 | m = re.match(p3, str2) 35 | print(m) 36 | 37 | -------------------------------------------------------------------------------- /chapter012/chapter_01204.py: -------------------------------------------------------------------------------- 1 | # 正则表达式对象(正则对象) 2 | import re 3 | url = "http://m.study.163.com/provider/1016839500/index.htm?share=2&shareId=1016839500https" 4 | pattern1 = re.compile("http") 5 | 6 | # pattern.match() :从起始位置开始匹配 7 | m1 = pattern1.match(url) 8 | print(pattern1.match(url)) 9 | print(m1.group(0)) 10 | print(m1.span()) 11 | 12 | # pattern.search() 13 | m2 = pattern1.search(url) 14 | print(pattern1.search(url)) 15 | print(m2) 16 | 17 | 18 | -------------------------------------------------------------------------------- /chapter013/ch13_conn.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | import pymysql.cursors 3 | 4 | #连接到数据库 5 | connection = pymysql.connect(host='localhost', 6 | port=3306, 7 | user='root', 8 | password='zhangzl', 9 | db='my_db', 10 | charset='utf8', 11 | cursorclass=pymysql.cursors.DictCursor) 12 | 13 | try: 14 | with connection.cursor() as cursor: 15 | #查看全部数据库 16 | sql = "show databases" 17 | dbs = cursor.execute(sql) 18 | results = cursor.fetchall() 19 | print(results) 20 | # connection is not autocommit by default. So you must commit to save 21 | connection.commit() 22 | with connection.cursor() as cursor: 23 | # 查看所有表 24 | sql = "show tables" 25 | cursor.execute(sql) 26 | result = cursor.fetchall() 27 | print(result) 28 | finally: 29 | connection.close() -------------------------------------------------------------------------------- /chapter013/ch13_full.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | import os 3 | import csv 4 | import sys 5 | import pymysql.cursors 6 | import time 7 | 8 | def txtRead(): 9 | with open("D:\\work\\code\\mysql\\text_data_1.txt",'r',encoding='UTF-8') as txtfile: 10 | lines = txtfile.readlines() 11 | for line in lines: 12 | line = line.strip().split("\t") 13 | print(line[0]) 14 | ''' 15 | import pymysql.cursors 16 | 17 | # 连接数据库 18 | connect = pymysql.Connect( 19 | host='localhost', 20 | port=3306, 21 | user='woider', 22 | passwd='3243', 23 | db='python', 24 | charset='utf8' 25 | ) 26 | 27 | # 获取游标 28 | cursor = connect.cursor() 29 | 30 | # 插入数据 31 | sql = "INSERT INTO trade (name, account, saving) VALUES ( '%s', '%s', %.2f )" 32 | data = ('雷军', '13512345678', 10000) 33 | cursor.execute(sql % data) 34 | connect.commit() 35 | print('成功插入', cursor.rowcount, '条数据') 36 | 37 | # 修改数据 38 | sql = "UPDATE trade SET saving = %.2f WHERE account = '%s' " 39 | data = (8888, '13512345678') 40 | cursor.execute(sql % data) 41 | connect.commit() 42 | print('成功修改', cursor.rowcount, '条数据') 43 | 44 | # 查询数据 45 | sql = "SELECT name,saving FROM trade WHERE account = '%s' " 46 | data = ('13512345678',) 47 | cursor.execute(sql % data) 48 | for row in cursor.fetchall(): 49 | print("Name:%s\tSaving:%.2f" % row) 50 | print('共查找出', cursor.rowcount, '条数据') 51 | 52 | # 删除数据 53 | sql = "DELETE FROM trade WHERE account = '%s' LIMIT %d" 54 | data = ('13512345678', 1) 55 | cursor.execute(sql % data) 56 | connect.commit() 57 | print('成功删除', cursor.rowcount, '条数据') 58 | 59 | # 事务处理 60 | sql_1 = "UPDATE trade SET saving = saving + 1000 WHERE account = '18012345678' " 61 | sql_2 = "UPDATE trade SET expend = expend + 1000 WHERE account = '18012345678' " 62 | sql_3 = "UPDATE trade SET income = income + 2000 WHERE account = '18012345678' " 63 | 64 | try: 65 | cursor.execute(sql_1) # 储蓄增加1000 66 | cursor.execute(sql_2) # 支出增加1000 67 | cursor.execute(sql_3) # 收入增加2000 68 | except Exception as e: 69 | connect.rollback() # 事务回滚 70 | print('事务处理失败', e) 71 | else: 72 | connect.commit() # 事务提交 73 | print('事务处理成功', cursor.rowcount) 74 | 75 | # 关闭连接 76 | cursor.close() 77 | connect.close() 78 | 79 | ''' 80 | 81 | 82 | def load2mysql(): 83 | # 连接数据库 84 | connect = pymysql.Connect( 85 | host='localhost', 86 | port=3306, 87 | user='root', 88 | passwd='zhangzl', 89 | db='login', 90 | charset='utf8' 91 | ) 92 | 93 | # 获取游标 94 | cursor = connect.cursor() 95 | #读取文件 96 | with open("D:\\work\\code\\mysql\\text_data_1.txt",'r',encoding='UTF-8') as txtfile: 97 | lines = txtfile.readlines() 98 | 99 | i = 0 100 | for line in lines: 101 | line = line.strip().split("\t") 102 | start = time.time() 103 | sql = "INSERT INTO login (userid, errorcode, actiontype) VALUES ( '%s', '%s', %s )" 104 | data = (line[0],line[1],line[2]) 105 | cursor.execute(sql % data) 106 | 107 | i = i + 1 108 | if(i%20000 == 0): 109 | connect.commit() 110 | print("提交:%d",i) 111 | end = time.time() 112 | print("成功插入记录:",";所用时间:",(end - start),"秒"); 113 | #print(line) 114 | # 插入数据i 115 | connect.commit() 116 | print('成功插入', cursor.rowcount, '条数据') 117 | # 关闭连接 118 | cursor.close() 119 | connect.close() 120 | if __name__=="__main__": 121 | # 管理系统路径 122 | sys.path.append("../") 123 | load2mysql() 124 | print("处理结束") 125 | -------------------------------------------------------------------------------- /chapter013/chapter_01303.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # 创建数据库表 3 | import pymysql.cursors 4 | 5 | 6 | # 创建数据库表 7 | def db_createtable(): 8 | # 连接到数据库 9 | connection = pymysql.connect(host='localhost', 10 | port=3306, 11 | user='root', 12 | password='zhangzl', 13 | db='my_db', 14 | charset='utf8', 15 | cursorclass=pymysql.cursors.DictCursor) 16 | 17 | try: 18 | with connection.cursor() as cursor: 19 | # 使用 execute() 方法执行 SQL,如果表存在则删除 20 | cursor.execute("DROP TABLE IF EXISTS EMPLOYEE") 21 | # 使用预处理语句创建表 22 | sql = """CREATE TABLE EMPLOYEE ( 23 | FIRST_NAME CHAR(20) NOT NULL, 24 | LAST_NAME CHAR(20), 25 | AGE INT, 26 | SEX CHAR(1), 27 | INCOME FLOAT )""" 28 | # 执行SQL操作 29 | dbs = cursor.execute(sql) 30 | connection.commit() 31 | # 查看所有表 32 | sql = "show tables" 33 | cursor.execute(sql) 34 | for result in cursor.fetchall(): 35 | print(result) 36 | finally: 37 | connection.close() 38 | 39 | 40 | # 执行主函数 41 | if __name__ == '__main__': 42 | db_createtable() 43 | -------------------------------------------------------------------------------- /chapter013/chapter_01304.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # 插入数据 3 | import pymysql.cursors 4 | 5 | 6 | # 插入数据记录 7 | def db_insert(): 8 | # 连接到数据库 9 | connection = pymysql.connect(host='localhost', 10 | port=3306, 11 | user='root', 12 | password='zhangzl', 13 | db='my_db', 14 | charset='utf8', 15 | cursorclass=pymysql.cursors.DictCursor) 16 | 17 | try: 18 | with connection.cursor() as cursor: 19 | # SQL 插入语句 20 | sql = """INSERT INTO EMPLOYEE(FIRST_NAME, 21 | LAST_NAME, AGE, SEX, INCOME) 22 | VALUES ('张', 'Python2', 25, 'M', 2000)""" 23 | 24 | # 执行SQL操作 25 | try: 26 | nrow = cursor.execute(sql) 27 | # 返回1代表成功 28 | if nrow == 1: 29 | print("数据插入成功!") 30 | connection.commit() 31 | except: 32 | connection.rollback() 33 | finally: 34 | connection.close() 35 | 36 | 37 | # 执行主函数 38 | if __name__ == '__main__': 39 | db_insert() 40 | -------------------------------------------------------------------------------- /chapter013/chapter_01305.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # 查询数据库表 3 | import pymysql.cursors 4 | 5 | 6 | # 查询数据库表 7 | def db_query(): 8 | # 连接到数据库 9 | connection = pymysql.connect(host='localhost', 10 | port=3306, 11 | user='root', 12 | password='zhangzl', 13 | db='my_db', 14 | charset='utf8', 15 | cursorclass=pymysql.cursors.DictCursor) 16 | 17 | try: 18 | with connection.cursor() as cursor: 19 | # SQL 插入语句 20 | sql = "SELECT * FROM EMPLOYEE WHERE INCOME > %s" % (1000) 21 | 22 | try: 23 | # 执行SQL语句,返回影响的行数 24 | row_count = cursor.execute(sql) 25 | print(row_count) 26 | # 获取所有记录列表 27 | results = cursor.fetchall() 28 | print(results) 29 | for row in results: 30 | # 此处不可以用索引访问:row[0] 31 | fname = row["FIRST_NAME"] 32 | lname = row["LAST_NAME"] 33 | age = row["AGE"] 34 | sex = row["SEX"] 35 | income = row["INCOME"] 36 | # 打印结果 37 | print("fname=%s,lname=%s,age=%s,sex=%s,income=%s" % (fname, lname, age, sex, income)) 38 | except: 39 | print("错误:数据查询操作失败") 40 | 41 | finally: 42 | connection.close() 43 | 44 | 45 | # 执行主函数 46 | if __name__ == '__main__': 47 | db_query() 48 | -------------------------------------------------------------------------------- /chapter013/chapter_01306.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # 数据删除操作 3 | import pymysql.cursors 4 | 5 | 6 | # 数据删除 7 | def db_delete(): 8 | # 连接到数据库 9 | connection = pymysql.connect(host='localhost', 10 | port=3306, 11 | user='root', 12 | password='zhangzl', 13 | db='my_db', 14 | charset='utf8', 15 | cursorclass=pymysql.cursors.DictCursor) 16 | 17 | try: 18 | with connection.cursor() as cursor: # 基于with,不需要执行cursor.close() 19 | # SQL 插入语句 20 | sql = "DELETE FROM EMPLOYEE WHERE AGE > '%d'" % (20) 21 | 22 | try: 23 | # 执行SQL语句,返回影响的行数 24 | row_count = cursor.execute(sql) 25 | # 提交修改:不可调用游标的cursor.commit 26 | connection.commit() 27 | print('数据删除成功,影响行数:%d' % row_count) 28 | except: 29 | # 回滚操作 30 | print("数据删除异常:执行回滚") 31 | connection.rollback() 32 | finally: 33 | connection.close() 34 | 35 | 36 | # 执行主函数 37 | if __name__ == '__main__': 38 | db_delete() 39 | -------------------------------------------------------------------------------- /chapter013/chapter_01307.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # 数据更新操作 3 | import pymysql.cursors 4 | 5 | 6 | # 数据更新 7 | def db_update(): 8 | # 连接到数据库 9 | connection = pymysql.connect(host='localhost', 10 | port=3306, 11 | user='root', 12 | password='zhangzl', 13 | db='my_db', 14 | charset='utf8', 15 | cursorclass=pymysql.cursors.DictCursor) 16 | 17 | try: 18 | with connection.cursor() as cursor: # 基于with,不需要执行cursor.close() 19 | # SQL 插入语句:年龄 + 1 20 | sql = "UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = '%c'" % ('M') 21 | try: 22 | # 执行SQL语句,返回影响的行数 23 | row_count = cursor.execute(sql) 24 | # 提交修改:不可调用游标的cursor.commit 25 | connection.commit() 26 | print('数据更新成功,影响行数:%d' % row_count) 27 | except: 28 | # 回滚操作 29 | print("数据更新异常:执行回滚") 30 | connection.rollback() 31 | finally: 32 | connection.close() 33 | 34 | 35 | # 执行主函数 36 | if __name__ == '__main__': 37 | db_update() 38 | -------------------------------------------------------------------------------- /chapter014/chapter_01401.py: -------------------------------------------------------------------------------- 1 | # 线程创建:基于自定义函数 2 | import os 3 | import time 4 | import threading 5 | 6 | 7 | # 线程执行函数 8 | def fun(n): 9 | print('-------start:---------') 10 | time.sleep(1) 11 | my_thread_name = threading.current_thread().name # 获取当前线程名称 12 | my_thread_id = threading.current_thread().ident # 获取当前线程id 13 | print('当前线程名为:{},线程id为:{},所在进程为:{},参数为:{}'.format(my_thread_name, my_thread_id, os.getpid(), n)) 14 | print('-------end:---------') 15 | 16 | 17 | # 创建线程对象 18 | mythread = threading.Thread(target=fun, name='线程1', args=('参数1',)) 19 | # 启动线程执行 20 | mythread.start() 21 | time.sleep(2) 22 | 23 | # 主线程信息 24 | main_thread_name = threading.current_thread().name 25 | main_thread_id = threading.current_thread().ident 26 | print('主线程名为:{},线程id为:{},所在进程为:{}'.format(main_thread_name, main_thread_id, os.getpid())) 27 | -------------------------------------------------------------------------------- /chapter014/chapter_01402.py: -------------------------------------------------------------------------------- 1 | # 线程创建:基于面向对象 2 | import os 3 | import time 4 | import threading 5 | 6 | 7 | # 自定义线程类 8 | class MyThread(threading.Thread): 9 | def __init__(self, n, name=None): 10 | super().__init__() 11 | self.name = name 12 | self.n = n 13 | 14 | def run(self): 15 | print('-------start:---------') 16 | time.sleep(1) 17 | my_thread_name = threading.current_thread().name 18 | my_thread_id = threading.current_thread().ident 19 | print('当前线程为:{},线程id为:{},所在进程为:{},您输入的参数为:{}'.format(my_thread_name, 20 | my_thread_id, os.getpid(), self.n)) 21 | print('--------end------------') 22 | 23 | 24 | # 对象创建 25 | mythread = MyThread(name='线程1', n=1) 26 | mythread.start() 27 | time.sleep(2) 28 | 29 | # 主线程信息 30 | main_thread_name = threading.current_thread().name 31 | main_thread_id = threading.current_thread().ident 32 | print('主线程为:{},线程id为:{},所在进程为:{}'.format(main_thread_name ,main_thread_id , os.getpid())) -------------------------------------------------------------------------------- /chapter014/chapter_01403.py: -------------------------------------------------------------------------------- 1 | # 线程对象: 属性变量 + 属性函数 2 | import time 3 | import threading 4 | 5 | 6 | # 执行函数 7 | def fun(): 8 | print('------------启动:子线程------------------------') 9 | for i in range(3): 10 | time.sleep(1) 11 | my_thread_name1 = threading.current_thread().name 12 | print('{} - 已运行:{}秒……'.format(my_thread_name1, i + 1)) 13 | print('------------结束:子线程------------------------') 14 | # 主线程 15 | 16 | 17 | print('-------------启动:主线程------------------') 18 | mythread = threading.Thread(target=fun, name='线程1') 19 | # 设置为守护线程 20 | mythread.daemon = True 21 | mythread.start() 22 | mythread.join() 23 | for i in range(3): 24 | time.sleep(1) 25 | my_thread_name2 = threading.current_thread().name 26 | print('{} - 已运行{}:秒……'.format(my_thread_name2, i + 1)) 27 | print('-------------结束:主线程------------------') 28 | 29 | -------------------------------------------------------------------------------- /chapter014/chapter_01405.py: -------------------------------------------------------------------------------- 1 | # 线程同步问题:同时操作全局变量的情况 2 | import time 3 | import threading 4 | 5 | 6 | # 类声明 7 | class MyThread(threading.Thread): 8 | def __init__(self, name=None): 9 | super().__init__() 10 | self.name = name 11 | 12 | def run(self): 13 | print('-----------------start:%s--------------------' % self.getName()) 14 | global num 15 | temp = num 16 | time.sleep(0.2) 17 | temp -= 1 18 | num = temp 19 | print('t_name = %s : num = %s' % (self.getName(), temp)) 20 | print('-----------------end:%s-----------------------' % self.getName()) 21 | 22 | 23 | # 主线程 24 | print('-------------启动:主线程------------------') 25 | thread_lst = [] 26 | num = 10 # 全局变量 27 | # 对象创建 28 | for i in range(10): 29 | t = MyThread(name=str(i),) 30 | thread_lst.append(t) 31 | t.start() 32 | # 等待执行 33 | [t.join() for t in thread_lst] 34 | print('num最后的值为:{}'.format(num)) 35 | print('-------------结束:主线程------------------') 36 | 37 | -------------------------------------------------------------------------------- /chapter014/chapter_01406.py: -------------------------------------------------------------------------------- 1 | # 互斥锁: 2 | import time 3 | import threading 4 | from threading import Thread 5 | from threading import Lock 6 | 7 | 8 | # 类声明 9 | class MyThread(threading.Thread): 10 | def __init__(self, name=None, lock=None): 11 | super().__init__() 12 | self.name = name 13 | self.lock = lock 14 | 15 | def run(self): 16 | print('-----------------start:%s--------------------' % self.getName()) 17 | # 获取锁: 18 | self.lock.acquire() 19 | global num 20 | temp = num 21 | time.sleep(0.2) 22 | temp -= 1 23 | num = temp 24 | print('t_name = %s : num = %s' % (self.getName(), temp)) 25 | # 释放锁: 26 | self.lock.release() 27 | print('-----------------end:%s-----------------------' % self.getName()) 28 | 29 | 30 | # 主线程 31 | print('-------------启动:主线程------------------') 32 | lock1 = threading.Lock() 33 | thread_lst = [] 34 | num = 10 # 全局变量 35 | 36 | # 对象创建 37 | for i in range(5): 38 | t = MyThread(name=str(i),lock=lock1) 39 | thread_lst.append(t) 40 | t.start() 41 | # 等待执行 42 | [t.join() for t in thread_lst] 43 | print('num最后的值为:{}'.format(num)) 44 | print('-------------结束:主线程------------------') 45 | 46 | -------------------------------------------------------------------------------- /chapter014/chapter_01407.py: -------------------------------------------------------------------------------- 1 | # 死锁问题:两个互斥锁,科学家吃面模型 - 只有一副餐具,同时四个线程 2 | import time 3 | from threading import Lock 4 | from threading import Thread 5 | 6 | 7 | # 吃面函数1:先拿面 8 | def eatNoodles_1(noodle_lock, fork_lock, scientist): 9 | noodle_lock.acquire() 10 | print('{} :拿到了面'.format(scientist)) 11 | fork_lock.acquire() 12 | print('{} :拿到了叉子'.format(scientist)) 13 | time.sleep(1) 14 | print('{} :吃到了面'.format(scientist)) 15 | fork_lock.release() 16 | noodle_lock.release() 17 | print('{} :放下了面'.format(scientist)) 18 | print('{} :放下了叉子'.format(scientist)) 19 | 20 | 21 | # 吃面函数2:先拿叉子 22 | def eatNoodles_2(noodle_lock, fork_lock, scientist): 23 | fork_lock.acquire() 24 | print('{}: 拿到了叉子'.format(scientist)) 25 | noodle_lock.acquire() 26 | print('{}:拿到了面'.format(scientist)) 27 | print('{}:吃到了面'.format(scientist)) 28 | noodle_lock.release() 29 | print('{}:放下了面'.format(scientist)) 30 | fork_lock.release() 31 | print('{}:放下了叉子'.format(scientist)) 32 | 33 | 34 | # 科学家列表 35 | list1 = ['霍金', '居里夫人'] 36 | list2 = ['爱因斯坦', '富兰克林'] 37 | # 面条锁 38 | noodle_lock = Lock() 39 | # 叉子锁 40 | fork_lock = Lock() 41 | # 线程组1:两个线程 42 | for i in list1: 43 | t = Thread(target=eatNoodles_1, args=(noodle_lock, fork_lock, i)) 44 | t.start() 45 | # 线程组2:两个线程 46 | for i in list2: 47 | t = Thread(target=eatNoodles_2, args=(noodle_lock, fork_lock, i)) 48 | t.start() 49 | -------------------------------------------------------------------------------- /chapter014/chapter_01408.py: -------------------------------------------------------------------------------- 1 | # 递归锁:此处用一个锁,可重入 2 | import time 3 | import threading 4 | from threading import RLock 5 | 6 | 7 | # 类声明 8 | class MyThread1(threading.Thread): 9 | def __init__(self, name=None, noodlelock=None, forklock=None, scientist = None): 10 | super().__init__() 11 | self.name = name 12 | self.noodle_lock = noodlelock 13 | self.fork_lock = forklock 14 | self.scientist = scientist 15 | 16 | def run(self): 17 | print('-----------------start:%s--------------------' % self.getName()) 18 | # 获取锁: 19 | noodle_lock.acquire() 20 | print('{} :拿到了面'.format(self.scientist)) 21 | fork_lock.acquire() 22 | print('{} :拿到了叉子'.format(self.scientist)) 23 | time.sleep(1) 24 | print('{} :吃到了面'.format(self.scientist)) 25 | fork_lock.release() 26 | noodle_lock.release() 27 | print('{} :放下了面'.format(self.scientist)) 28 | print('{} :放下了叉子'.format(self.scientist)) 29 | print('-----------------end:%s-----------------------' % self.getName()) 30 | 31 | 32 | # 类声明 33 | class MyThread2(threading.Thread): 34 | def __init__(self, name=None,noodlelock=None, forklock=None, scientist=None): 35 | super().__init__() 36 | self.name = name 37 | self.noodle_lock = noodlelock 38 | self.fork_lock = forklock 39 | self.scientist = scientist 40 | 41 | def run(self): 42 | print('-----------------start:%s--------------------' % self.getName()) 43 | self.fork_lock.acquire() 44 | print('{}: 拿到了叉子'.format(self.scientist)) 45 | self.noodle_lock.acquire() 46 | print('{}:拿到了面'.format(self.scientist)) 47 | print('{}:吃到了面'.format(self.scientist)) 48 | self.noodle_lock.release() 49 | print('{}:放下了面'.format(self.scientist)) 50 | self.fork_lock.release() 51 | print('{}:放下了叉子'.format(self.scientist)) 52 | print('-----------------end:%s-----------------------' % self.getName()) 53 | 54 | 55 | # 科学家列表 56 | list1 = ['霍金', '居里夫人'] 57 | list2 = ['爱因斯坦', '富兰克林'] 58 | # 面条锁 59 | noodle_lock = fork_lock = RLock() 60 | # 叉子锁 61 | # fork_lock = RLock() 62 | # 线程组1:两个线程 63 | for i in list1: 64 | t = MyThread1("线程1", noodle_lock, fork_lock, i) 65 | t.start() 66 | # 线程组2:两个线程 67 | for i in list2: 68 | t = MyThread2("线程2", noodle_lock, fork_lock, i) 69 | t.start() 70 | -------------------------------------------------------------------------------- /chapter014/chapter_01409.py: -------------------------------------------------------------------------------- 1 | # 递归锁:此处用两个锁,各自锁定不同资源,仍然会死锁 2 | import time 3 | import threading 4 | from threading import RLock 5 | 6 | 7 | # 类声明 8 | class MyThread1(threading.Thread): 9 | def __init__(self, name=None, noodlelock=None, forklock=None, scientist = None): 10 | super().__init__() 11 | self.name = name 12 | self.noodle_lock = noodlelock 13 | self.fork_lock = forklock 14 | self.scientist = scientist 15 | 16 | def run(self): 17 | print('-----------------start:%s--------------------' % self.getName()) 18 | # 获取锁: 19 | noodle_lock.acquire() 20 | print('{} :拿到了面'.format(self.scientist)) 21 | fork_lock.acquire() 22 | print('{} :拿到了叉子'.format(self.scientist)) 23 | time.sleep(1) 24 | print('{} :吃到了面'.format(self.scientist)) 25 | fork_lock.release() 26 | noodle_lock.release() 27 | print('{} :放下了面'.format(self.scientist)) 28 | print('{} :放下了叉子'.format(self.scientist)) 29 | print('-----------------end:%s-----------------------' % self.getName()) 30 | 31 | 32 | # 类声明 33 | class MyThread2(threading.Thread): 34 | def __init__(self, name=None,noodlelock=None, forklock=None, scientist=None): 35 | super().__init__() 36 | self.name = name 37 | self.noodle_lock = noodlelock 38 | self.fork_lock = forklock 39 | self.scientist = scientist 40 | 41 | def run(self): 42 | print('-----------------start:%s--------------------' % self.getName()) 43 | self.fork_lock.acquire() 44 | print('{}: 拿到了叉子'.format(self.scientist)) 45 | self.noodle_lock.acquire() 46 | print('{}:拿到了面'.format(self.scientist)) 47 | print('{}:吃到了面'.format(self.scientist)) 48 | self.noodle_lock.release() 49 | print('{}:放下了面'.format(self.scientist)) 50 | self.fork_lock.release() 51 | print('{}:放下了叉子'.format(self.scientist)) 52 | print('-----------------end:%s-----------------------' % self.getName()) 53 | 54 | 55 | # 科学家列表 56 | list1 = ['霍金', '居里夫人'] 57 | list2 = ['爱因斯坦', '富兰克林'] 58 | # ----------------------------------------------- 59 | # 面条锁 60 | noodle_lock = RLock() 61 | # 叉子锁 62 | fork_lock = RLock() 63 | # ----------------------------------------------- 64 | # 线程组1:两个线程 65 | for i in list1: 66 | t = MyThread1("线程1", noodle_lock, fork_lock, i) 67 | t.start() 68 | # 线程组2:两个线程 69 | for i in list2: 70 | t = MyThread2("线程2", noodle_lock, fork_lock, i) 71 | t.start() 72 | -------------------------------------------------------------------------------- /chapter014/chapter_01410.py: -------------------------------------------------------------------------------- 1 | # 条件变量: 2 | import threading 3 | import time 4 | 5 | 6 | # 生产者线程: 7 | class ProduceThread(threading.Thread): 8 | def __init__(self, name=None, con=None ): 9 | super().__init__() 10 | self.name = name 11 | self.con = con 12 | 13 | def run(self): 14 | # 锁定线程 15 | global num 16 | self.con.acquire() 17 | print("工厂开始生产……") 18 | while True: 19 | num += 1 20 | print("已生产商品数量:{}".format(num)) 21 | time.sleep(1) 22 | if num >= 5: 23 | print("商品数量达到5件,仓库饱满,停止生产……") 24 | con.notify() # 唤醒消费者 25 | con.wait() # 生产者自身陷入沉睡 26 | # 释放锁 27 | self.con.release() 28 | 29 | 30 | # 消费者 31 | class ConsumerThread(threading.Thread): 32 | def __init__(self, name=None, con=None ): 33 | super().__init__() 34 | self.name = name 35 | self.con = con 36 | 37 | def run(self): 38 | con.acquire() 39 | global num 40 | print("消费者开始消费……") 41 | while True: 42 | num -= 1 43 | print("剩余商品数量:{}".format(num)) 44 | time.sleep(2) 45 | if num <= 0: 46 | print("库存为0,通知工厂开始生产……") 47 | con.notify() # 唤醒生产者线程 48 | con.wait() # 消费者自身陷入沉睡 49 | 50 | con.release() 51 | 52 | 53 | con = threading.Condition() 54 | num = 0 55 | p = ProduceThread("生产者线程", con) 56 | c = ConsumerThread("消费者线程", con) 57 | p.start() 58 | c.start() -------------------------------------------------------------------------------- /chapter014/chapter_01411.py: -------------------------------------------------------------------------------- 1 | # 信号量:无信号量的情况 2 | """ 3 | 场景描述:有10个人吃饭,但只有一张餐桌,只允许做3个人,没上桌的人不允许吃饭,已上桌吃完饭离座之后, 4 | 下面的人才能抢占桌子继续吃饭,如果不用信号量,肯定是10人一窝蜂一起吃饭. 5 | """ 6 | from threading import Thread 7 | import time 8 | import random 9 | 10 | 11 | # 线程: 12 | class MyThread(Thread): 13 | def __init__(self, name=None, customer=None): 14 | super().__init__() 15 | self.name = name 16 | self.custom = customer 17 | 18 | def run(self): 19 | print('{}号顾客:上座,开始吃饭'.format(self.custom)) 20 | time.sleep(random.random()) 21 | print('{}号顾客:离座,吃完饭了'.format(self.custom)) 22 | 23 | 24 | # 主函数 25 | if __name__ == '__main__': 26 | for i in range(20): 27 | p = MyThread("线程%d" % i, i) 28 | p.start() 29 | -------------------------------------------------------------------------------- /chapter014/chapter_01412.py: -------------------------------------------------------------------------------- 1 | # 信号量:无信号量的情况 2 | """ 3 | 场景描述:有10个人吃饭,但只有一张餐桌,只允许做3个人,没上桌的人不允许吃饭,已上桌吃完饭离座之后, 4 | 下面的人才能抢占桌子继续吃饭,如果不用信号量,肯定是10人一窝蜂一起吃饭. 5 | """ 6 | import time 7 | import random 8 | from threading import Thread 9 | from threading import Semaphore 10 | 11 | 12 | # 线程: 13 | class MyThread(Thread): 14 | def __init__(self, name=None, semaph=None, customer=None): 15 | super().__init__() 16 | self.name = name 17 | self.sem = semaph 18 | self.custom = customer 19 | 20 | def run(self): 21 | self.sem.acquire() 22 | print('{}号顾客:上座,开始吃饭'.format(self.custom)) 23 | time.sleep(random.random()) 24 | print('{}号顾客:离座,吃完饭了'.format(self.custom)) 25 | self.sem.release() 26 | 27 | 28 | # 主函数 29 | if __name__ == '__main__': 30 | sem = Semaphore(3) 31 | for i in range(20): 32 | p = MyThread("线程%d" % i,sem, i) 33 | p.start() -------------------------------------------------------------------------------- /chapter014/chapter_01415.py: -------------------------------------------------------------------------------- 1 | # 线程池执行程序1: 2 | from concurrent.futures import ThreadPoolExecutor 3 | import time 4 | 5 | 6 | # 执行函数 7 | def func(n): 8 | time.sleep(1) 9 | print(n) 10 | return n * n 11 | 12 | 13 | # 线程池对象 14 | print("----------------启动主线程-------------------") 15 | thread_pool = ThreadPoolExecutor(max_workers=5) 16 | thread_list = [] 17 | # 18 | for i in range(10): 19 | # 执行任务,传递参数 20 | r = thread_pool.submit(func, 2) 21 | # 获取任务返回结果 22 | thread_list.append(r.result()) 23 | 24 | thread_pool.shutdown() # 相当于close() + join() 25 | print(thread_list) 26 | print('---------------主线程运行结束------------------') -------------------------------------------------------------------------------- /chapter014/chapter_01416.py: -------------------------------------------------------------------------------- 1 | # 线程池实例程序2: 2 | from concurrent.futures import ThreadPoolExecutor 3 | import time 4 | 5 | 6 | # 参数times用来模拟网络请求的时间 7 | def get_html(times): 8 | time.sleep(times) 9 | print("get page {}s finished".format(times)) 10 | return times 11 | 12 | 13 | # 线程池执行器 14 | executor = ThreadPoolExecutor(max_workers=2) 15 | # 通过submit函数提交执行的函数到线程池中,submit函数立即返回,不阻塞 16 | task1 = executor.submit(get_html, (3)) 17 | task2 = executor.submit(get_html, (2)) 18 | 19 | # done方法用于判定某个任务是否完成 20 | print(task1.done()) 21 | # cancel方法用于取消某个任务,该任务没有放入线程池中才能取消成功 22 | print(task2.cancel()) 23 | time.sleep(4) 24 | print(task1.done()) 25 | # result方法可以获取task的执行结果 26 | print(task1.result()) 27 | -------------------------------------------------------------------------------- /chapter014/chapter_01417.py: -------------------------------------------------------------------------------- 1 | # 线程池:任务执行结束判定1 2 | from concurrent.futures import ThreadPoolExecutor, as_completed 3 | import time 4 | 5 | 6 | # 参数times用来模拟网络请求的时间 7 | def get_html(times): 8 | time.sleep(times) 9 | print("get page {}s finished".format(times)) 10 | return times 11 | 12 | 13 | executor = ThreadPoolExecutor(max_workers=2) 14 | urls = [3, 2, 4] # 并不是真的url 15 | all_task = [executor.submit(get_html, (url)) for url in urls] 16 | 17 | for future in as_completed(all_task): 18 | data = future.result() 19 | print("in main: get page {}s success".format(data)) -------------------------------------------------------------------------------- /chapter014/chapter_01418.py: -------------------------------------------------------------------------------- 1 | # 线程池:任务执行结束判定2 2 | from concurrent.futures import ThreadPoolExecutor 3 | import time 4 | 5 | 6 | # 参数times用来模拟网络请求的时间 7 | def get_html(times): 8 | time.sleep(times) 9 | print("get page {}s finished".format(times)) 10 | return times 11 | 12 | 13 | # 线程池执行器 14 | executor = ThreadPoolExecutor(max_workers=2) 15 | urls = [3, 2, 4] # 并不是真的url 16 | # 无需提交任务,等待任务结束 17 | for data in executor.map(get_html, urls): 18 | print("in main: get page {}s success".format(data)) -------------------------------------------------------------------------------- /chapter014/chapter_01419.py: -------------------------------------------------------------------------------- 1 | # 线程池:任务执行结束判定1 2 | from concurrent.futures import ThreadPoolExecutor, wait, ALL_COMPLETED, FIRST_COMPLETED 3 | import time 4 | 5 | 6 | # 参数times用来模拟网络请求的时间 7 | def get_html(times): 8 | time.sleep(times) 9 | print("get page {}s finished".format(times)) 10 | return times 11 | 12 | 13 | executor = ThreadPoolExecutor(max_workers=2) 14 | urls = [3, 2, 4] # 并不是真的url 15 | all_task = [executor.submit(get_html, (url)) for url in urls] 16 | wait(all_task, return_when=ALL_COMPLETED) 17 | print("main") -------------------------------------------------------------------------------- /chapter015/chapter_01501.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # 文件名:server.py 3 | import socket 4 | 5 | 6 | # 服务器函数 7 | def server_tcp(): 8 | # 创建 socket 对象 9 | server_socket = socket.socket( 10 | socket.AF_INET, socket.SOCK_STREAM) 11 | # 获取本地主机名 12 | host = socket.gethostname() 13 | port = 9999 14 | # 绑定端口号 15 | server_socket.bind((host, port)) 16 | # 设置最大连接数,超过后排队 17 | server_socket.listen(5) 18 | 19 | while True: 20 | # 建立客户端连接 21 | client_socket, addr = server_socket.accept() 22 | print("连接地址: %s" % str(addr)) 23 | msg = 'Python全栈工程师魔鬼训练营' + "\r\n" 24 | client_socket.send(msg.encode('utf-8')) 25 | client_socket.close() 26 | 27 | 28 | # 主函数 29 | if __name__ == '__main__': 30 | server_tcp() 31 | -------------------------------------------------------------------------------- /chapter015/chapter_01502.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | import socket 3 | 4 | 5 | # 客户端函数: 6 | def client_tcp(): 7 | # 创建 socket 对象 8 | client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 9 | # 获取本地主机名 10 | host = socket.gethostname() 11 | # 设置端口号 12 | port = 9999 13 | # 连接服务,指定主机和端口 14 | client.connect((host, port)) 15 | # 接收小于 1024 字节的数据 16 | msg = client.recv(1024) 17 | client.close() 18 | print(msg.decode('utf-8')) 19 | 20 | 21 | # 主函数 22 | if __name__ == '__main__': 23 | client_tcp() 24 | -------------------------------------------------------------------------------- /chapter015/chapter_01503.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # -*-coding:utf-8 -*-# 3 | # 4 | # 时间同步程序:TCP服务器端 5 | from socket import * 6 | import time 7 | 8 | 9 | # 服务器函数 10 | def server_tcp(): 11 | COD = 'utf-8' 12 | HOST = '127.0.0.1' # 主机ip 13 | PORT = 21566 # 软件端口号 14 | BUFSIZ = 1024 15 | ADDR = (HOST, PORT) 16 | SIZE = 10 17 | tcpS = socket(AF_INET, SOCK_STREAM) # 创建socket对象 18 | tcpS.setsockopt(SOL_SOCKET,SO_REUSEADDR,1) # 加入socket配置,重用ip和端口 19 | tcpS.bind(ADDR) # 绑定ip端口号 20 | tcpS.listen(SIZE) # 设置最大链接数 21 | while True: 22 | print("服务器启动,监听客户端链接") 23 | conn, addr = tcpS.accept() 24 | print("链接的客户端", addr) 25 | while True: 26 | try: 27 | data = conn.recv(BUFSIZ) # 读取已链接客户的发送的消息 28 | except Exception: 29 | print("断开的客户端", addr) 30 | break 31 | print("客户端发送的内容:",data.decode(COD)) 32 | if not data: 33 | break 34 | msg = time.strftime("%Y-%m-%d %X") # 获取结构化事件戳 35 | msg1 = '[%s]:%s' % (msg, data.decode(COD)) 36 | conn.send(msg1.encode(COD)) # 发送消息给已链接客户端 37 | conn.close() # 关闭客户端链接 38 | tcpS.closel() 39 | 40 | 41 | # 主函数 42 | if __name__ == '__main__': 43 | server_tcp() 44 | -------------------------------------------------------------------------------- /chapter015/chapter_01504.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # -*-coding:utf-8 -*- 3 | # 时间同步程序:服务器端 4 | from socket import * 5 | from time import ctime 6 | 7 | 8 | # 客户端函数:TCP 9 | def client_tcp(): 10 | HOST = '127.0.0.1' # 服务端ip 11 | PORT = 21566 # 服务端端口号 12 | BUFSIZ = 1024 13 | ADDR = (HOST, PORT) 14 | tcpCliSock = socket(AF_INET, SOCK_STREAM) # 创建socket对象 15 | tcpCliSock.connect(ADDR) # 连接服务器 16 | while True: 17 | data = input('>>').strip() 18 | if not data: 19 | break 20 | tcpCliSock.send(data.encode('utf-8')) # 发送消息 21 | data = tcpCliSock.recv(BUFSIZ) # 读取消息 22 | if not data: 23 | break 24 | print(data.decode('utf-8')) 25 | tcpCliSock.close() # 关闭客户端 26 | 27 | 28 | # 主函数 29 | if __name__ == '__main__': 30 | client_tcp() -------------------------------------------------------------------------------- /chapter015/chapter_01505.py: -------------------------------------------------------------------------------- 1 | import socket 2 | 3 | 4 | # 服务端程序:UDP 5 | def server_udp(): 6 | BUFSIZE = 1024 7 | ip_port = ('127.0.0.1', 9999) 8 | server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # udp协议 9 | server.bind(ip_port) 10 | while True: 11 | data, client_addr = server.recvfrom(BUFSIZE) 12 | print('server收到的数据', data) 13 | 14 | server.sendto(data.upper(), client_addr) 15 | 16 | server.close() 17 | 18 | 19 | # 主函数 20 | if __name__ == '__main__': 21 | server_udp() 22 | -------------------------------------------------------------------------------- /chapter015/chapter_01506.py: -------------------------------------------------------------------------------- 1 | import socket 2 | 3 | 4 | # 客户端函数:TCP 5 | def client_udp(): 6 | BUFSIZE = 1024 7 | client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 8 | while True: 9 | msg = input(">> ").strip() 10 | ip_port = ('127.0.0.1', 9999) 11 | client.sendto(msg.encode('utf-8'), ip_port) 12 | 13 | data, server_addr = client.recvfrom(BUFSIZE) 14 | print('客户端 Recvfrom:', data, server_addr) 15 | 16 | client.close() 17 | 18 | 19 | # 主函数 20 | if __name__ == '__main__': 21 | client_udp() 22 | -------------------------------------------------------------------------------- /chapter016/ch1601-csvread.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import csv 3 | import sys 4 | filename = 'data//ch1601-data.csv' 5 | 6 | data = [] 7 | try: 8 | with open(filename) as f: 9 | reader = csv.reader(f) 10 | c = 0 11 | for row in reader: 12 | if c == 0: 13 | header = row 14 | else: 15 | data.append(row) 16 | c += 1 17 | except csv.Error as e: 18 | print("Error reading CSV file at line %s: %s" % (reader.line_num, e)) 19 | sys.exit(-1) 20 | #输出文件头 21 | if header: 22 | print(header) 23 | print('==================') 24 | #输出文件行 25 | for datarow in data: 26 | print(datarow) 27 | -------------------------------------------------------------------------------- /chapter016/ch1602-csvwrite.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import csv 4 | import sys 5 | 6 | filename = 'data//ch1602-data-write.csv' 7 | 8 | # we open file with 'b' flag 9 | # for compatibility with non-linux users 10 | try: 11 | with open(filename,'w',newline='') as f: 12 | writer = csv.writer(f) 13 | #写入表头 14 | header = ['id', 'date'] 15 | writer.writerow(header) 16 | #写入文件内容 17 | for row in range(10): 18 | writer.writerow([row + 1, '2019-01-%s' % (19 + row)]) 19 | print("写入行:%s" % row) 20 | except csv.Error as e: 21 | print("Error writing CSV file at line %s: %s" % (row, e)) 22 | sys.exit(-1) -------------------------------------------------------------------------------- /chapter016/ch1603-full.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | import csv 3 | import os 4 | import sys 5 | #读取CSV文件 6 | def CsvReader(): 7 | try: 8 | #csv_reader = csv.reader(open("ch1603-data.csv",'r', encoding='UTF-8')) 9 | with open("data\\ch1603-data.csv",'r') as csvfile: 10 | reader = csv.reader(csvfile) 11 | for row in reader: 12 | #01:读取整行 13 | print(row) 14 | #02:读取单列 15 | length = len(row) #列数data// 16 | column = row[0] #读取第1列 17 | print(length) #打印列数 18 | print(column) #打印第1列 19 | except csv.Error as e: 20 | print("Error reading CSV file at line %s: %s" % (reader.line_num, e)) 21 | sys.exit(-1) 22 | 23 | #写入CSV文件 24 | def CsvWriteCSV(): 25 | current_dir = os.path.abspath('.') 26 | #print(current_dir) 27 | file_name = os.path.join(current_dir, "data\\ch1603-data-write.csv") 28 | #print(file_name) 29 | #csvfile = open(file_name, 'wt',newline='' ,encoding="UTF8") # 30 | try: 31 | with open(file_name, 'wt',newline='') as csvfile1: 32 | header = ['股票代码', '干系人类型'] 33 | writer = csv.writer(csvfile1) 34 | #writer.writerow(header) 35 | with open("data\\ch1603-data.csv",'r') as csvfile: 36 | reader = csv.reader(csvfile) 37 | for row in reader: 38 | print(row) 39 | csvrow1 = [] 40 | csvrow1.append(row[0]) 41 | csvrow1.append(row[1]) 42 | writer.writerow(csvrow1) 43 | except csv.Error as e: 44 | print("Error writing CSV file at line %s" % e) 45 | sys.exit(-1) 46 | 47 | 48 | if __name__=="__main__": 49 | #读取方式1 50 | #CsvReader() 51 | #存储CSV 52 | CsvWriteCSV() 53 | 54 | 55 | -------------------------------------------------------------------------------- /chapter016/ch1604-full.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import xlrd 3 | import xlwt 4 | import sys 5 | 6 | from datetime import date, datetime 7 | def read_excel(): 8 | try: 9 | # 01-打开文件-1.工作薄.2.表sheet.3.行row列col.4.单元格cell 10 | workbook = xlrd.open_workbook("data\\ch1604-data.xlsx") 11 | # 02-获取所有sheet 12 | print(workbook.sheet_names()) # ['Sheet1', 'Sheet2', 'Sheet3'] 13 | sheet_name = workbook.sheet_names()[0] 14 | # 根据sheet索引或者名称获取sheet内容 15 | sheet1 = workbook.sheet_by_index(0) # sheet索引从0开始 16 | sheet2 = workbook.sheet_by_name('Sheet1') 17 | 18 | # sheet的名称,行数,列数 19 | print(sheet2.name, sheet2.nrows, sheet2.ncols) 20 | #03-获取整行和整列的值(数组) 21 | rows = sheet2.row_values(3) # 获取第四行内容 22 | cols = sheet2.col_values(0) # 获取第1列内容 23 | print(rows) 24 | print(cols) 25 | #04-获取单元格内容 26 | print(sheet2.cell(1, 0).value) 27 | print(sheet2.cell_value(1, 0)) 28 | print(sheet2.row(1)[0].value) 29 | # 获取单元格内容的数据类型 30 | print(sheet2.cell(1, 0).ctype) 31 | except xlrd.XLRDError as e: 32 | print("Error reading CSV file : %s" % e) 33 | sys.exit(-1) 34 | ''' 35 | 设置单元格样式 36 | ''' 37 | def set_style(name, height, bold=False): 38 | style = xlwt.XFStyle() # 初始化样式 39 | font = xlwt.Font() # 为样式创建字体 40 | font.name = name # 'Times New Roman' 41 | font.bold = bold 42 | font.color_index = 4 43 | font.height = height 44 | 45 | style.font = font 46 | # style.borders = borders 47 | return style 48 | # 写excel 49 | def write_excel(): 50 | try: 51 | f = xlwt.Workbook(encoding='utf-8', style_compression=0) # 创建工作簿 52 | #创建sheet 53 | sheet1 = f.add_sheet('sheet1', cell_overwrite_ok=True) # 创建sheet 54 | row0 = [u'业务', u'状态', u'北京', u'上海', u'广州', u'深圳', u'状态小计', u'合计'] 55 | column0 = [u'机票', u'船票', u'火车票', u'汽车票', u'其它'] 56 | status = [u'预订', u'出票', u'退票', u'业务小计'] 57 | # 生成第一行 58 | for i in range(0, len(row0)): 59 | sheet1.write(0, i, row0[i], set_style('Times New Roman', 220, True)) 60 | # 生成第一列和最后一列(合并4行) 61 | i, j = 1, 0 62 | while i < 4 * len(column0) and j < len(column0): 63 | sheet1.write_merge(i, i + 3, 0, 0, column0[j], set_style('Arial', 220, True)) # 第一列 64 | sheet1.write_merge(i, i + 3, 7, 7) # 最后一列"合计" 65 | i += 4 66 | j += 1 67 | sheet1.write_merge(21, 21, 0, 1, u'合计', set_style('Times New Roman', 220, True)) 68 | # 生成第二列 69 | i = 0 70 | while i < 4 * len(column0): 71 | for j in range(0, len(status)): 72 | sheet1.write(j + i + 1, 1, status[j]) 73 | i += 4 74 | #xlsx格式不支持 75 | f.save('data\\ch1604-data-write.xls') # 保存文件 76 | 77 | except xlwt.ANTLRException as e: 78 | print("Error writing xls file : %s" % e) 79 | sys.exit(-1) 80 | if __name__ == '__main__': 81 | #read_excel() 82 | write_excel() -------------------------------------------------------------------------------- /chapter016/ch1604-xlsx-read.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import xlrd 3 | import sys 4 | filename = 'data\\ch1604-data.xlsx' 5 | try: 6 | # 01-打开文件-1.工作薄.2.表sheet.3.行row列col.4.单元格cell 7 | workbook = xlrd.open_workbook(filename) 8 | # 02-获取所有sheet 9 | print(workbook.sheet_names()) # ['Sheet1', 'Sheet2', 'Sheet3'] 10 | sheet_name = workbook.sheet_names()[0] 11 | # 根据sheet索引或者名称获取sheet内容 12 | sheet1 = workbook.sheet_by_index(0) # sheet索引从0开始 13 | sheet2 = workbook.sheet_by_name('Sheet1') 14 | 15 | # sheet的名称,行数,列数 16 | print(sheet2.name, sheet2.nrows, sheet2.ncols) 17 | # 03-获取整行和整列的值(数组) 18 | rows = sheet2.row_values(3) # 获取第四行内容 19 | cols = sheet2.col_values(0) # 获取第1列内容 20 | print(rows) 21 | print(cols) 22 | # 04-获取单元格内容 23 | print(sheet2.cell(1, 0).value) 24 | print(sheet2.cell_value(1, 0)) 25 | print(sheet2.row(1)[0].value) 26 | # 获取单元格内容的数据类型 27 | print(sheet2.cell(1, 0).ctype) 28 | except xlrd.XLRDError as e: 29 | print("Error reading CSV file : %s" % e) 30 | sys.exit(-1) 31 | -------------------------------------------------------------------------------- /chapter016/ch1605-xls-write.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import xlwt 4 | import sys 5 | 6 | try: 7 | #01:创建工作薄 8 | f = xlwt.Workbook(encoding='utf-8', style_compression=0) # 创建工作簿 9 | #02:创建sheet 10 | sheet1 = f.add_sheet('sheet1', cell_overwrite_ok=True) # 创建sheet 11 | row0 = [u'业务', u'状态', u'北京', u'上海', u'广州', u'深圳', u'状态小计', u'合计'] 12 | #03:创建表头 13 | for i in range(0, len(row0)): 14 | sheet1.write(0, i, row0[i]) 15 | #04:创建第一列 16 | for i in range(1,100): 17 | sheet1.write(i,0,i) 18 | # xlsx格式不支持 19 | f.save('data\\ch1604-data-write.xls') # 保存文件 20 | print("文件保存成功!") 21 | 22 | except xlwt.ANTLRException as e: 23 | print("Error writing xls file : %s" % e) 24 | sys.exit(-1) -------------------------------------------------------------------------------- /chapter016/data/ReadMe.txt: -------------------------------------------------------------------------------- 1 | https://docs.python.org/3.6/library/csv.html -------------------------------------------------------------------------------- /chapter016/data/ch1601-data.csv: -------------------------------------------------------------------------------- 1 | day,ammount 2 | 2019/0/04,323 3 | 2019/0/04,233 4 | 2019/0/04,433 5 | 2019/0/04,555 6 | 2019/0/04,123 7 | 2019/0/04,12 8 | 2019/0/04,221 9 | -------------------------------------------------------------------------------- /chapter016/data/ch1602-data-write.csv: -------------------------------------------------------------------------------- 1 | id,date 2 | 1,2019-01-19 3 | 2,2019-01-20 4 | 3,2019-01-21 5 | 4,2019-01-22 6 | 5,2019-01-23 7 | 6,2019-01-24 8 | 7,2019-01-25 9 | 8,2019-01-26 10 | 9,2019-01-27 11 | 10,2019-01-28 12 | -------------------------------------------------------------------------------- /chapter016/data/ch1603-data-write.csv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhangziliang04/RoadPython/5a68ed62b987c228b5e56f445d43904223dfe6a9/chapter016/data/ch1603-data-write.csv -------------------------------------------------------------------------------- /chapter016/data/ch1603-data.csv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhangziliang04/RoadPython/5a68ed62b987c228b5e56f445d43904223dfe6a9/chapter016/data/ch1603-data.csv -------------------------------------------------------------------------------- /chapter016/data/ch1604-data-write.xls: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhangziliang04/RoadPython/5a68ed62b987c228b5e56f445d43904223dfe6a9/chapter016/data/ch1604-data-write.xls -------------------------------------------------------------------------------- /chapter016/data/ch1604-data.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhangziliang04/RoadPython/5a68ed62b987c228b5e56f445d43904223dfe6a9/chapter016/data/ch1604-data.xlsx -------------------------------------------------------------------------------- /chapter016/data/ch1604-write.xls: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhangziliang04/RoadPython/5a68ed62b987c228b5e56f445d43904223dfe6a9/chapter016/data/ch1604-write.xls -------------------------------------------------------------------------------- /chapter017/chapter_01701.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhangziliang04/RoadPython/5a68ed62b987c228b5e56f445d43904223dfe6a9/chapter017/chapter_01701.py -------------------------------------------------------------------------------- /chapter018/chapter_01801.py: -------------------------------------------------------------------------------- 1 | # JSON解码:从文件读取 2 | import json 3 | 4 | # 从文件读取 5 | f = open('stu_info.json', encoding='utf-8') 6 | user_dic = json.load(f) 7 | print(user_dic) # 打印字典 8 | print(type(user_dic)) # 打印user_dic类型 9 | print(user_dic.keys()) # 打印字典的所有Key 10 | 11 | -------------------------------------------------------------------------------- /chapter018/chapter_01802.py: -------------------------------------------------------------------------------- 1 | # 解码:从字符串 2 | import json 3 | f = open('stu_info.json', encoding='utf-8') 4 | 5 | # 使用loads()方法,需要先读文件 6 | content = f.read() 7 | user_dic = json.loads(content) 8 | # 输出JSON内容 9 | print(user_dic) # 打印字典 10 | print(type(user_dic)) # 打印user_dic类型 11 | print(user_dic.keys()) # 打印字典的所有Key 12 | -------------------------------------------------------------------------------- /chapter018/chapter_01803.py: -------------------------------------------------------------------------------- 1 | # JSON编码:dumps 2 | import json 3 | 4 | student = {'萧景瑞': '公子榜第二名', '萧景琰': '靖王'} 5 | res2 = json.dumps(student, indent=8, ensure_ascii=False) 6 | print(res2) 7 | 8 | with open('stus1.json', 'w', encoding='utf-8') as f: # 使用.dumps()方法时,要写入 9 | f.write(res2) 10 | -------------------------------------------------------------------------------- /chapter018/chapter_01804.py: -------------------------------------------------------------------------------- 1 | # JSON编码:dump 2 | import json 3 | 4 | student = {'萧景瑞': '公子榜第二名', '萧景琰': '靖王'} 5 | f = open('stus2.json', 'w', encoding='utf-8') 6 | 7 | json.dump(student, f, indent=4, ensure_ascii=False) 8 | f.close() 9 | -------------------------------------------------------------------------------- /chapter018/chapter_01805.py: -------------------------------------------------------------------------------- 1 | # JSON编码 2 | import json 3 | # Python元组 -> JSON列表 4 | s1 = json.dumps(['Michael Jordon', 'Kobe Bryant']) 5 | print(s1) 6 | 7 | # Python字符串 -> JSON string 8 | s2 = json.dumps('Michael Jordon') 9 | print(s2) 10 | 11 | # Python Dict -> JSON object 12 | s4 = json.dumps({"Michael Jordon": 23, "Kobe Bryant": 24}, sort_keys=True) 13 | print(s4) 14 | 15 | # Python列表 -> JSON array 16 | # 并指定JSON分隔符:逗号和冒号之后没有空格(默认有空格) 17 | s5 = json.dumps([1, 2, 3, {'x': 5, 'y': 7}], separators=(',', ':')) 18 | # 输出的JSON字符串中逗号和冒号之后没有空格 19 | print(s5) 20 | 21 | # 格式控制 22 | # 指定indent为4:意味着转换的JSON字符串有缩进 23 | s6 = json.dumps({'Python': 5, 'Java': 7}, sort_keys=True, indent=4) 24 | print(s6) 25 | 26 | # 使用JSONEncoder的encode方法将Python转JSON 27 | s7 = json.JSONEncoder().encode({"names": ("Michael Jordon", "23")}) 28 | print(s7) 29 | f = open('1805.json', 'w') 30 | # 使用dump()函数将转换得到JSON字符串输出到文件 31 | json.dump(['Kotlin', {'Python': 'excellent'}], f) -------------------------------------------------------------------------------- /chapter018/chapter_01806.py: -------------------------------------------------------------------------------- 1 | # JSON解码: 2 | import json 3 | # JSON数组array -> Python列表 4 | result1 = json.loads('["Michael Jordon", "Kobe Bryant"]') 5 | print(result1) 6 | 7 | 8 | # JSON字符串 -> Python字符串 9 | result2 = json.loads('"Michael Jordon"') 10 | print(result2) 11 | 12 | 13 | # 定义一个自定义的转化函数 14 | def as_complex(dct): 15 | if '__complex__' in dct: 16 | return complex(dct['real'], dct['imag']) 17 | return dct 18 | 19 | 20 | # 自定义恢复函数:real数据转成复数的实部,imag转成复数的虚部 21 | result3 = json.loads('{"__complex__": true, "real": 1, "imag": 2}', object_hook=as_complex) 22 | print(result3) 23 | f = open('a.json') 24 | # 从文件流恢复JSON列表 25 | result4 = json.load(f) 26 | print(result4) 27 | -------------------------------------------------------------------------------- /chapter018/stu_info.json: -------------------------------------------------------------------------------- 1 | { 2 | "error_code": 0, 3 | "stu_info": [ 4 | { 5 | "id": 309, 6 | "name": "梅长苏", 7 | "sex": "男", 8 | "age": 15, 9 | "addr": "江左盟", 10 | "grade": "天蝎座", 11 | "phone": "18511112345", 12 | "gold": 100 13 | }, 14 | { 15 | "id": 310, 16 | "name": "飞流", 17 | "sex": "男", 18 | "age": 18, 19 | "addr": "江左盟", 20 | "grade": "天蝎座", 21 | "phone": "18511112346", 22 | "gold": 100 23 | } 24 | ] 25 | } -------------------------------------------------------------------------------- /chapter019/chapter_01901.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhangziliang04/RoadPython/5a68ed62b987c228b5e56f445d43904223dfe6a9/chapter019/chapter_01901.py -------------------------------------------------------------------------------- /chapter019/myapp/db.sqlite3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhangziliang04/RoadPython/5a68ed62b987c228b5e56f445d43904223dfe6a9/chapter019/myapp/db.sqlite3 -------------------------------------------------------------------------------- /chapter019/myapp/manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Django's command-line utility for administrative tasks.""" 3 | import os 4 | import sys 5 | 6 | 7 | def main(): 8 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myapp.settings') 9 | try: 10 | from django.core.management import execute_from_command_line 11 | except ImportError as exc: 12 | raise ImportError( 13 | "Couldn't import Django. Are you sure it's installed and " 14 | "available on your PYTHONPATH environment variable? Did you " 15 | "forget to activate a virtual environment?" 16 | ) from exc 17 | execute_from_command_line(sys.argv) 18 | 19 | 20 | if __name__ == '__main__': 21 | main() 22 | -------------------------------------------------------------------------------- /chapter019/myapp/myapp/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhangziliang04/RoadPython/5a68ed62b987c228b5e56f445d43904223dfe6a9/chapter019/myapp/myapp/__init__.py -------------------------------------------------------------------------------- /chapter019/myapp/myapp/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhangziliang04/RoadPython/5a68ed62b987c228b5e56f445d43904223dfe6a9/chapter019/myapp/myapp/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /chapter019/myapp/myapp/__pycache__/dbhandler.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhangziliang04/RoadPython/5a68ed62b987c228b5e56f445d43904223dfe6a9/chapter019/myapp/myapp/__pycache__/dbhandler.cpython-36.pyc -------------------------------------------------------------------------------- /chapter019/myapp/myapp/__pycache__/search.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhangziliang04/RoadPython/5a68ed62b987c228b5e56f445d43904223dfe6a9/chapter019/myapp/myapp/__pycache__/search.cpython-36.pyc -------------------------------------------------------------------------------- /chapter019/myapp/myapp/__pycache__/settings.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhangziliang04/RoadPython/5a68ed62b987c228b5e56f445d43904223dfe6a9/chapter019/myapp/myapp/__pycache__/settings.cpython-36.pyc -------------------------------------------------------------------------------- /chapter019/myapp/myapp/__pycache__/urls.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhangziliang04/RoadPython/5a68ed62b987c228b5e56f445d43904223dfe6a9/chapter019/myapp/myapp/__pycache__/urls.cpython-36.pyc -------------------------------------------------------------------------------- /chapter019/myapp/myapp/__pycache__/view.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhangziliang04/RoadPython/5a68ed62b987c228b5e56f445d43904223dfe6a9/chapter019/myapp/myapp/__pycache__/view.cpython-36.pyc -------------------------------------------------------------------------------- /chapter019/myapp/myapp/__pycache__/wsgi.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhangziliang04/RoadPython/5a68ed62b987c228b5e56f445d43904223dfe6a9/chapter019/myapp/myapp/__pycache__/wsgi.cpython-36.pyc -------------------------------------------------------------------------------- /chapter019/myapp/myapp/asgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | ASGI config for myapp project. 3 | 4 | It exposes the ASGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.0/howto/deployment/asgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.asgi import get_asgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myapp.settings') 15 | 16 | application = get_asgi_application() 17 | -------------------------------------------------------------------------------- /chapter019/myapp/myapp/dbhandler.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from django.http import HttpResponse 3 | from mymodel.models import UserInfo 4 | 5 | 6 | # 数据添加 7 | def add_db(request): 8 | test1 = UserInfo(name='Python', password='') 9 | test1.save() 10 | return HttpResponse("

数据添加成功!

") 11 | 12 | 13 | # 数据查询 14 | def query_db(request): 15 | # 初始化 16 | response = "" 17 | response1 = "" 18 | 19 | # 通过objects这个模型管理器的all()获得所有数据行,相当于SQL中的SELECT * FROM 20 | list = UserInfo.objects.all() 21 | # 条件过滤 22 | response2 = UserInfo.objects.filter(id=1) 23 | # 获取单个对象 24 | response3 = UserInfo.objects.get(id=1) 25 | # 限制返回的数据 相当于 SQL 中的 OFFSET 0 LIMIT 2; 26 | UserInfo.objects.order_by('name')[0:2] 27 | # 数据排序 28 | UserInfo.objects.order_by("id") 29 | # 组合用法 30 | UserInfo.objects.filter(name="Python").order_by("id") 31 | 32 | # 输出所有数据 33 | for var in list: 34 | response1 += var.name + " " 35 | response = response1 36 | return HttpResponse("

" + response + "

") 37 | 38 | 39 | # 数据更新 40 | def update_db(request): 41 | # 修改其中一个id=1的name字段,再save,相当于SQL中的UPDATE 42 | test1 = UserInfo.objects.get(id=1) 43 | test1.name = 'C++' 44 | test1.save() 45 | 46 | # 另外一种方式 47 | # Test.objects.filter(id=1).update(name='Google') 48 | 49 | # 修改所有的列 50 | # Test.objects.all().update(name='Google') 51 | 52 | return HttpResponse("

修改成功

") 53 | 54 | 55 | # 数据删除 56 | def del_db(request): 57 | # 删除id=1的数据 58 | test1 = UserInfo.objects.get(id=1) 59 | test1.delete() 60 | 61 | # 方法二 62 | # UserInfo.objects.filter(id=1).delete() 63 | 64 | # 删除所有数据 65 | # UserInfo.objects.all().delete() 66 | 67 | return HttpResponse("

删除成功

") 68 | 69 | 70 | # 数据库操作,追加新的用户名 71 | def add_name(var1): 72 | test1 = UserInfo(name=var1, password='') 73 | test1.save() 74 | print("add_name is OK.") 75 | -------------------------------------------------------------------------------- /chapter019/myapp/myapp/search.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from django.http import HttpResponse 3 | from django.shortcuts import render 4 | from . import dbhandler 5 | 6 | 7 | # 表单 8 | def login_form(request): 9 | return render(request, 'name.html') 10 | 11 | 12 | # 接收请求数据 13 | def login(request): 14 | request.encoding = 'utf-8' 15 | if 'Name' in request.GET and request.GET['Name']: 16 | message = '姓名: ' + request.GET['Name'] + '电话:' + request.GET['Tel'] 17 | # 数据模型调用 18 | dbhandler.add_name(request.GET['Name']) 19 | else: 20 | message = '你提交了空表单' 21 | return HttpResponse(message) 22 | 23 | -------------------------------------------------------------------------------- /chapter019/myapp/myapp/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for myapp project. 3 | 4 | Generated by 'django-admin startproject' using Django 3.0.1. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.0/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/3.0/ref/settings/ 11 | """ 12 | 13 | import os 14 | 15 | # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 16 | BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 17 | 18 | 19 | # Quick-start development settings - unsuitable for production 20 | # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ 21 | 22 | # SECURITY WARNING: keep the secret key used in production secret! 23 | SECRET_KEY = '99m0i1h^ws#_=$zhc)b&)xxqet!=fgu4x17atg70v4+s#87+&k' 24 | 25 | # SECURITY WARNING: don't run with debug turned on in production! 26 | DEBUG = True 27 | 28 | ALLOWED_HOSTS = [] 29 | 30 | 31 | # Application definition 32 | 33 | INSTALLED_APPS = [ 34 | 'django.contrib.admin', 35 | 'django.contrib.auth', 36 | 'django.contrib.contenttypes', 37 | 'django.contrib.sessions', 38 | 'django.contrib.messages', 39 | 'django.contrib.staticfiles', 40 | 'mymodel', # 添加应用 41 | ] 42 | 43 | MIDDLEWARE = [ 44 | 'django.middleware.security.SecurityMiddleware', 45 | 'django.contrib.sessions.middleware.SessionMiddleware', 46 | 'django.middleware.common.CommonMiddleware', 47 | 'django.middleware.csrf.CsrfViewMiddleware', 48 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 49 | 'django.contrib.messages.middleware.MessageMiddleware', 50 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 51 | ] 52 | 53 | ROOT_URLCONF = 'myapp.urls' 54 | 55 | TEMPLATES = [ 56 | { 57 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 58 | 'DIRS': [BASE_DIR+"/templates",], 59 | 'APP_DIRS': True, 60 | 'OPTIONS': { 61 | 'context_processors': [ 62 | 'django.template.context_processors.debug', 63 | 'django.template.context_processors.request', 64 | 'django.contrib.auth.context_processors.auth', 65 | 'django.contrib.messages.context_processors.messages', 66 | ], 67 | }, 68 | }, 69 | ] 70 | 71 | WSGI_APPLICATION = 'myapp.wsgi.application' 72 | 73 | 74 | # Database 75 | # https://docs.djangoproject.com/en/3.0/ref/settings/#databases 76 | # 修改默认数据库配置为MySQL 77 | """ 78 | DATABASES = { 79 | 'default': { 80 | 'ENGINE': 'django.db.backends.sqlite3', 81 | 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 82 | } 83 | } 84 | """ 85 | DATABASES = { 86 | 'default': { 87 | 'ENGINE': 'django.db.backends.mysql', # 或者使用 mysql.connector.django 88 | 'NAME': 'my_db', # 数据库名 89 | 'USER': 'root', # 账号 90 | 'PASSWORD': 'zhangzl', # 密码 91 | 'HOST':'localhost', # 数据库服务器地址 92 | 'PORT':'3306', # 数据库服务器端口 93 | } 94 | } 95 | 96 | # Password validation 97 | # https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators 98 | 99 | AUTH_PASSWORD_VALIDATORS = [ 100 | { 101 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 102 | }, 103 | { 104 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 105 | }, 106 | { 107 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 108 | }, 109 | { 110 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 111 | }, 112 | ] 113 | 114 | 115 | # Internationalization 116 | # https://docs.djangoproject.com/en/3.0/topics/i18n/ 117 | 118 | LANGUAGE_CODE = 'en-us' 119 | 120 | TIME_ZONE = 'UTC' 121 | 122 | USE_I18N = True 123 | 124 | USE_L10N = True 125 | 126 | USE_TZ = True 127 | 128 | 129 | # Static files (CSS, JavaScript, Images) 130 | # https://docs.djangoproject.com/en/3.0/howto/static-files/ 131 | 132 | STATIC_URL = '/static/' 133 | -------------------------------------------------------------------------------- /chapter019/myapp/myapp/urls.py: -------------------------------------------------------------------------------- 1 | """myapp URL Configuration 2 | 3 | The `urlpatterns` list routes URLs to views. For more information please see: 4 | https://docs.djangoproject.com/en/3.0/topics/http/urls/ 5 | Examples: 6 | Function views 7 | 1. Add an import: from my_app import views 8 | 2. Add a URL to urlpatterns: path('', views.home, name='home') 9 | Class-based views 10 | 1. Add an import: from other_app.views import Home 11 | 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') 12 | Including another URLconf 13 | 1. Import the include() function: from django.urls import include, path 14 | 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) 15 | """ 16 | """ 17 | from django.contrib import admin 18 | from django.urls import path 19 | 20 | urlpatterns = [ 21 | path('admin/', admin.site.urls), 22 | ] 23 | """ 24 | from django.conf.urls import url 25 | from . import view 26 | from . import search 27 | from . import dbhandler 28 | 29 | 30 | urlpatterns = [ 31 | url(r'^$', view.hello2), 32 | url(r'^hello1$', view.hello1), 33 | url(r'^hello2$', view.hello2), 34 | url(r'^add$', dbhandler.add_db), 35 | url(r'^query$', dbhandler.query_db), 36 | url(r'^edit$', dbhandler.update_db), 37 | url(r'^del$', dbhandler.del_db), 38 | # 39 | url(r'^login$', search.login), 40 | url(r'^login_form$', search.login_form), 41 | 42 | ] 43 | -------------------------------------------------------------------------------- /chapter019/myapp/myapp/view.py: -------------------------------------------------------------------------------- 1 | # 视图 2 | from django.http import HttpResponse 3 | from django.shortcuts import render 4 | 5 | 6 | # 无模板的情况:控制器和内容耦合 7 | def hello1(request): 8 | return HttpResponse("Hello world ! ") 9 | 10 | 11 | # 调用模板的情况:控制器和内容解耦 12 | def hello2(request): 13 | context = {} 14 | context['hello'] = 'Hello World!' 15 | return render(request, 'hello.html', context) -------------------------------------------------------------------------------- /chapter019/myapp/myapp/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for myapp project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myapp.settings') 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /chapter019/myapp/mymodel/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhangziliang04/RoadPython/5a68ed62b987c228b5e56f445d43904223dfe6a9/chapter019/myapp/mymodel/__init__.py -------------------------------------------------------------------------------- /chapter019/myapp/mymodel/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhangziliang04/RoadPython/5a68ed62b987c228b5e56f445d43904223dfe6a9/chapter019/myapp/mymodel/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /chapter019/myapp/mymodel/__pycache__/admin.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhangziliang04/RoadPython/5a68ed62b987c228b5e56f445d43904223dfe6a9/chapter019/myapp/mymodel/__pycache__/admin.cpython-36.pyc -------------------------------------------------------------------------------- /chapter019/myapp/mymodel/__pycache__/models.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhangziliang04/RoadPython/5a68ed62b987c228b5e56f445d43904223dfe6a9/chapter019/myapp/mymodel/__pycache__/models.cpython-36.pyc -------------------------------------------------------------------------------- /chapter019/myapp/mymodel/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | # Register your models here. 4 | -------------------------------------------------------------------------------- /chapter019/myapp/mymodel/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class MymodelConfig(AppConfig): 5 | name = 'mymodel' 6 | -------------------------------------------------------------------------------- /chapter019/myapp/mymodel/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 3.0.1 on 2019-12-19 09:49 2 | 3 | from django.db import migrations, models 4 | 5 | 6 | class Migration(migrations.Migration): 7 | 8 | initial = True 9 | 10 | dependencies = [ 11 | ] 12 | 13 | operations = [ 14 | migrations.CreateModel( 15 | name='UserInfo', 16 | fields=[ 17 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 18 | ('name', models.CharField(max_length=20)), 19 | ('password', models.CharField(max_length=20)), 20 | ], 21 | ), 22 | ] 23 | -------------------------------------------------------------------------------- /chapter019/myapp/mymodel/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhangziliang04/RoadPython/5a68ed62b987c228b5e56f445d43904223dfe6a9/chapter019/myapp/mymodel/migrations/__init__.py -------------------------------------------------------------------------------- /chapter019/myapp/mymodel/migrations/__pycache__/0001_initial.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhangziliang04/RoadPython/5a68ed62b987c228b5e56f445d43904223dfe6a9/chapter019/myapp/mymodel/migrations/__pycache__/0001_initial.cpython-36.pyc -------------------------------------------------------------------------------- /chapter019/myapp/mymodel/migrations/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhangziliang04/RoadPython/5a68ed62b987c228b5e56f445d43904223dfe6a9/chapter019/myapp/mymodel/migrations/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /chapter019/myapp/mymodel/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | # Create your models here. 4 | 5 | 6 | # 用户信息类 7 | class UserInfo(models.Model): 8 | name = models.CharField(max_length=20) 9 | password = models.CharField(max_length=20) 10 | -------------------------------------------------------------------------------- /chapter019/myapp/mymodel/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /chapter019/myapp/mymodel/views.py: -------------------------------------------------------------------------------- 1 | from django.shortcuts import render 2 | 3 | # Create your views here. 4 | -------------------------------------------------------------------------------- /chapter019/myapp/run.bat: -------------------------------------------------------------------------------- 1 | python manage.py runserver 127.0.0.1:8000 2 | -------------------------------------------------------------------------------- /chapter019/myapp/templates/hello.html: -------------------------------------------------------------------------------- 1 |

{{ hello }}

2 | -------------------------------------------------------------------------------- /chapter019/myapp/templates/name.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Python Django Web编程完整实例 6 | 7 | 8 |
9 |
10 |


11 |
12 |
13 |
14 |
15 |    
16 |
17 |
18 | 19 | --------------------------------------------------------------------------------