python学习笔记
参照地址: http://www.cnblogs.com/wupeiqi/articles/5237704.html 1、格式化输出 name=input("name") age =int( input("age: ") ) job=input("job") salary = input("salary: ") info = ''' --------------------- info of --------------------------- name = %s age = %d job = %s salary = %s ''' %(name, age,job, salary) print(info) name=input("name") age =int( input("age: ") ) job=input("job") salary = input("salary: ") info2 = ''' -----------------info of _name -------------- name = {_name} age = (_age) job = {_salary} salary = {_job} '''.format(_name=name, _age=age, _salary=job, _job=salary) print(info2) 2、if语句 age = 45 guest_age=int(input("guest_age1:")) if guest_age > age: print ("guest smaller") elif guest_age == age: print("right") else: print("guest bigger") 3、while: count=0 while True: if count==3: break age = 45 guest_age=int(input("guest_age1:")) if guest_age > age: print ("guest smaller") elif guest_age == age: print("right") break else: print("guest bigger") count+=1 count=0 while count<3: age = 45 guest_age=int(input("guest_age1:")) if guest_age > age: print ("guest smaller") elif guest_age == age: print("right") break else: print("guest bigger") count+=1 else: print("you have try too many times") 4、for 循环 count=0 for i in range(3): age = 45 guest_age=int(input("guest_age1:")) if guest_age > age: print ("guest smaller") elif guest_age == age: print("right") break else: print("guest bigger") else: print("you have try too many times") count=0 while count<3: age = 45 guest_age=int(input("guest_age1:")) if guest_age > age: print ("guest smaller") elif guest_age == age: print("right") break else: print("guest bigger") count+=1 if count == 3: continue_count=input("if you wang to contue:") if continue_count != "n": count=0 else: print("you have try too many times") 5、continue: for i in range(0,6): if i < 3 : print("i:",i) else: continue print("ni hao") 6、模块 import sys print (sys.path) 7、三元运算 a=1 b=2 c=3 d=a if a>b else c print(d) 8、列表使用 增 删 改 减 a=[('digit',2),('fruit','apple')] print(a) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py [('digit', 2), ('fruit', 'apple')] xing=["li","zhu","song","he","#"] number=["1","2","3"] print(xing) print(xing[2]) print(xing[2:]) print(xing[-3:-1]) xing.insert(1,"zhao") xing.extend(number) del xing[1] xing.reverse() xing2=xing.copy() print(xing,xing2) xing=["li","zhu","song","he","#"] xing[1]="zhao" print(xing) xing=["li","zhu","song",["sun","hong"],"he","#"] xing2=xing.copy() xing[3][0]="zhao" print(xing) print(xing2) xing=["li","zhu","song",["sun","hong"],"he","#"] xing2=xing.copy() xing[3]="zhao" print(xing) print(xing2) xing=["li","zhu","song",["sun","hong"],"he","#"] xing2=xing.copy() xing2[3][0]="zhao" print(xing) print(xing2) import copy xing=["li","zhu","song",["sun","hong"],"he","#"] xing2=copy.deepcopy(xing) xing[3][0]="zhao" print(xing) print(xing2) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py ['li', 'zhu', 'song', ['zhao', 'hong'], 'he', '#'] ['li', 'zhu', 'song', ['sun', 'hong'], 'he', '#'] Process finished with exit code 0 9、复制: import copy xing=["li","zhu","song",["sun","hong"],"he","#"] xing2=copy.deepcopy(xing) xing[3][0]="zhao" for i in xing: print(i) import copy xing=["li","zhu","song",["sun","hong"],"he","#"] xing2=copy.deepcopy(xing) xing[3][0]="zhao" list=xing[0:-1:2] for i in list: print(i) import copy xing=["li","zhu","song",["sun","hong"],"he","#"] xing2=copy.deepcopy(xing) xing[3][0]="zhao" list=xing[::2] for i in list: print(i) import copy xing=["li","zhu","song",["sun","hong"],"he","#"] xing2=copy.deepcopy(xing) xing[3][0]="zhao" print(xing[::2]) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py ['li', 'song', 'he'] Process finished with exit code 0 import copy xing=["li","zhu","song",["sun","hong"],"he","#"] xing2=copy.deepcopy(xing) xing[3][0]="zhao" print(xing[:]) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py ['li', 'zhu', 'song', ['zhao', 'hong'], 'he', '#'] Process finished with exit code 0 import copy xing=["li","zhu","song",["sun","hong"],"he","#"] xing2=copy.deepcopy(xing) xing[3][0]="zhao" print(xing[:-1]) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py ['li', 'zhu', 'song', ['zhao', 'hong'], 'he', '#'] Process finished with exit code 0 import copy xing=["li","zhu","song",["sun","hong"],"he","#"] xing2=copy.deepcopy(xing) xing[3][0]="zhao" print(xing[0:3]) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py ['li', 'zhu', 'song'] Process finished with exit code 0 import copy xing=["li","zhu","song",["sun","hong"],"he","#"] xing2=copy.deepcopy(xing) xing[3][0]="zhao" print(xing[:3]) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py ['li', 'zhu', 'song'] Process finished with exit code 0 浅copy的作用 :使用于夫妻存款、取款等 import copy person=["name",["alice",100]] a1=copy.copy(person) a2=person[:] a3=list(person) print(a1) print(a2) print(a3) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py ['name', ['alice', 100]] ['name', ['alice', 100]] ['name', ['alice', 100]] import copy person=["alice",["saving",100]] a1=copy.copy(person) person[0]="feng jie" person[1][1]=50 print(person) print(a1) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py ['feng jie', ['saving', 50]] ['alice', ['saving', 50]] Process finished with exit code 0 10、购物车 product_list=[("apple",100),("banana",50),("fone",600)] salary=input("please input your salary:") shoping_list=[] if salary.isdigit(): salary=int(salary) while True: for index,item in enumerate(product_list): print(index,item) user_choice=input("your choice:") if user_choice.isdigit(): user_choice=int(user_choice) if user_choice < len(product_list) and user_choice > 0: p_item=product_list[user_choice] if p_item[1] < salary: shoping_list.append(p_item) salary-=p_item[1] print("%s has been add your shoping_list,your salary_list is \033[31;1m%s\033[0m" % (p_item,salary)) else : print ("\033[31;1mmoney is just %s ,not to buy\033[0m" % salary ) elif user_choice == "q": print("-----------shoping_list_______") for p in shoping_list: print(p) print("%s dollars is lift" % salary) exit() else: print("your choice is worng") 11、字符串 str="my name is stone" print(str[str.find("name"):]) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py name is stone Process finished with exit code 0 str="my name is {name},my hometown is {it} " print(str.format(name="stone",it="hebei")) print(str.format_map( {'name':'stone','it':'hebei'} )) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py my name is stone,my hometown is hebei my name is stone,my hometown is hebei Process finished with exit code 0 print('-'.join(['1','2','3'])) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py 1-2-3 Process finished with exit code 0 12、字典 列表转换字典 元组()里面可以包含多个列表, 列表里面也可以包含多个元组 a=dict.fromkeys([1],[3]) print(a) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py {1: [3]} a=dict.fromkeys([1,2],[3,{'name':'alice'}]) print(a) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py {1: [3, {'name': 'alice'}], 2: [3, {'name': 'alice'}]} 字典转换成列表 str={1:'zhu',2:'li',3:'song'} print(str.items()) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py dict_items([(1, 'zhu'), (2, 'li'), (3, 'song')]) 删除 info={ 1:'zhu', 2:'li', 3:'song' } del info[1] print(info) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py {2: 'li', 3: 'song'} 随机删除 info={ 1:'zhu', 2:'li', 3:'song' } info.popitem() print(info) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py {2: 'li', 3: 'song'} 修改 info={ 1:'zhu', 2:'li', 3:'song' } info[1]="sun" print(info) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py {1: 'sun', 2: 'li', 3: 'song'} 增加 info={ 1:'zhu', 2:'li', 3:'song' } info[4]="sun" print(info) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py {1: 'zhu', 2: 'li', 3: 'song', 4: 'sun'} 查找 info={ 1:'zhu', 2:'li', 3:'song' } print(info.get(1)) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py zhu 多级嵌套 info={ "china":["name","xiao hua"], "France":["name","xiao gang"] } print(info) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py {'china': ['name', 'xiao hua'], 'France': ['name', 'xiao gang']} 修改 info={ "china": { "shang hai":["name","xiao hua"] }, "France": { "bei jing":["name","xiao gang"] } } info["china"]["shang hai"][1]= "xiao li" print(info) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py {'France': {'bei jing': ['name', 'xiao gang']}, 'china': {'shang hai': ['name', 'xiao li']}} 重新赋值 info={ "china": { "shang hai":["name","xiao hua"] }, "France": { "bei jing":["name","xiao gang"] } } print(info) info.setdefault("american",{"bai gong":["name","bob"]}) print(info) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py {'France': {'bei jing': ['name', 'xiao gang']}, 'china': {'shang hai': ['name', 'xiao hua']}} {'France': {'bei jing': ['name', 'xiao gang']}, 'american': {'bai gong': ['name', 'bob']}, 'china': {'shang hai': ['name', 'xiao hua']}} info={ "china": { "shang hai":["name","xiao hua"] }, "France": { "bei jing":["name","xiao gang"] } } print(info) info.setdefault("china",{"bai gong":["name","bob"]}) print(info) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py {'china': {'shang hai': ['name', 'xiao hua']}, 'France': {'bei jing': ['name', 'xiao gang']}} {'china': {'shang hai': ['name', 'xiao hua']}, 'France': {'bei jing': ['name', 'xiao gang']}} 更新 info={ "china": { "shang hai":["name","xiao hua"] }, "France": { "bei jing":["name","xiao gang"] } } fruit={"china":"red", "banana":"yellow" } print(info) info.update(fruit) print(info) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py {'France': {'bei jing': ['name', 'xiao gang']}, 'china': {'shang hai': ['name', 'xiao hua']}} {'France': {'bei jing': ['name', 'xiao gang']}, 'banana': 'yellow', 'china': 'red'} 字典转换列表 info={ "china": { "shang hai":["name","xiao hua"] }, "France": { "bei jing":["name","xiao gang"] } } fruit={"china":"red", "banana":"yellow" } print(info) print(info.items()) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py {'France': {'bei jing': ['name', 'xiao gang']}, 'china': {'shang hai': ['name', 'xiao hua']}} dict_items([('France', {'bei jing': ['name', 'xiao gang']}), ('china', {'shang hai': ['name', 'xiao hua']})]) 初始化 info={ "china": { "shang hai":["name","xiao hua"] }, "France": { "bei jing":["name","xiao gang"] } } fruit={"china":"red", "banana":"yellow" } print(info) a=dict.fromkeys([1,2,3],"students") print(a) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py {'china': {'shang hai': ['name', 'xiao hua']}, 'France': {'bei jing': ['name', 'xiao gang']}} {1: 'students', 2: 'students', 3: 'students'} info={ "china": { "shang hai":["name","xiao hua"] }, "France": { "bei jing":["name","xiao gang"] } } print(info) a=dict.fromkeys([1,2,3],["students",{"math class teachet":"li ming"}]) print(a) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py {'France': {'bei jing': ['name', 'xiao gang']}, 'china': {'shang hai': ['name', 'xiao hua']}} {1: ['students', {'math class teachet': 'li ming'}], 2: ['students', {'math class teachet': 'li ming'}], 3: ['students', {'math class teachet': 'li ming'}]} 跟超链接一样 info={ "china": { "shang hai":["name","xiao hua"] }, "France": { "bei jing":["name","xiao gang"] } } a=dict.fromkeys([1,2,3],[88,{"math class teachet":"li ming"},555]) print(a) a[2][1]['math class teachet'] = "li feng" print(a) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py {1: [88, {'math class teachet': 'li ming'}, 555], 2: [88, {'math class teachet': 'li ming'}, 555], 3: [88, {'math class teachet': 'li ming'}, 555]} {1: [88, {'math class teachet': 'li feng'}, 555], 2: [88, {'math class teachet': 'li feng'}, 555], 3: [88, {'math class teachet': 'li feng'}, 555]} 13、集合 去重: list=[1,3,5,6,5,] list1=set(list) print(list1,type(list)) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py {1, 3, 5, 6} <class 'list'> 取交集 list1=[1,3,5,6,5,] list2=set(list1) list3=set([1,3,9]) print( list2.intersection(list3)) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py {1, 3} 取并集 list1=[1,3,5,6,5,] list2=set(list1) list3=set([1,3,9]) print( list2.union(list3)) ist1=[1,3,5,6,5,] list2=set(list1) list3=set([1,3,7,8]) print( list3 | list2) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py {1, 3, 5, 6, 9} 差集 list1=[1,3,5,6,5,] list2=set(list1) list3=set([1,3,9]) print( list2.difference(list3)) list1=[1,3,5,6,5,] list2=set(list1) list3=set([1,3,7,8]) print( list3 & list2) list1=[1,3,5,6,5,] list2=set(list1) list3=set([1,3,7,8]) print( list2 - list3) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py {5, 6} 子集 list1=[1,3,5,6,5,] list2=set(list1) list3=set([1,3,5]) print( list3.issubset(list2)) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py True 父集 list1=[1,3,5,6,5,] list2=set(list1) list3=set([1,3,5]) print( list3.issuperset(list2)) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py False 对称差集 list1=[1,3,5,6,5,] list2=set(list1) list3=set([1,3,7,8]) print( list3.symmetric_difference(list2)) list1=[1,3,5,6,5,] list2=set(list1) list3=set([1,3,7,8]) print( list2 ^ list3) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py {5, 6, 7, 8} 集合添加 list1=[1,3,5,6,5,] list2=set(list1) list3=set([1,3,7,8]) list2.add(9) print(list2) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py {1, 9, 3, 5, 6} list1=[1,3,5,6,5,] list2=set(list1) list3=set([1,3,7,8]) list2.update([9,0,8]) print(list2) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py {0, 1, 3, 5, 6, 8, 9} 14 文件编辑 打开文件、 data=open("zabbix.txt",encoding="utg-8").read() print(data) 读文件: f=open("zabbix.txt",'r',encoding="utg-8") data=f.read() print(data) 写文件:会覆盖 f=open("zabbix.txt",'w',encoding="utf-8") f.write("good moring") f.write("hello boy") 追加 f=open("zabbix.txt",'a',encoding="utf-8") f.write("\ngood moring\n") f.write("hello boy") f.close() 读前5行 f=open("zabbix.txt",'r',encoding="utf-8") for i in range(5): print(f.readline()) 正规打印循环打印每一行 --列表 -删除空格 f=open("zabbix.txt",'r',encoding="utf-8") for line in f print(line) 不要用下面的方式 到第10行不打印 ---这种readline容易把内存卡爆,用下面的循环,往内存里面读一行,删除一行。 f=open("zabbix.txt",'r',encoding="utf-8") for index,line in enumerate(f.readline()): if index==10: print("-------wait a minute----") continue print(line.strip()) 正规打印循环打印每一行 f=open("zabbix.txt",'r',encoding="utf-8") for line in f print(line) f=open("zabbix.txt",'r',encoding="utf-8") count=0 for line in f: if count==9: print("-------wait a minute----") continue print(line) count+=1 读新旧文件往新文件里面写:---推荐这种适合3个G的大文件。不占内存。 f=open("zabbix.txt",'r',encoding="utf-8") f_new=open("zabbix2.txt",'w',encoding="utf-8") for line in f: if "good moring" in line: line=line.replace("good moring","good moring") f_new.write(line) f.close() 经典写入格式: with open('zabbix.txt','a') as f: f.write("hello world") 15 函数: 函数与面向过程其实没啥区别, 函数返回值: def func(): print("hello word") return 0 a=func() print(a) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py hello word 0 返回元组 def func(): print("hello word") return 'a',[33],{'c':'66'} a=func() print(a) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py hello word ('a', [33], {'c': '66'}) 没有返回值 def func(): print("hello word") a=func() print(a) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py hello word None 传递参数 位置参数 def func(a,b): print(a) print(b) func(1,2) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py 1 2 关键字参数 def func(a,b): print(a) print(b) func(a=1,b=2) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py 1 2 def func(a,b): print(a) print(b) x=1 y=2 func(a=x,b=y) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py 1 2 def func(a,b): print(a) print(b) func(b=2,a=1) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py 1 2 def func(a,b,c): print(a) print(b) print(c) func(1,c=3,b=2) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py 1 2 3 默认参数 def func(a,b,c=3): print(a) print(b) print(c) func(a=1,b=2) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py 1 2 3 def func(a,b,c=3): print(a) print(b) print(c) func(a=1,b=2,c=5) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py 1 2 5 *args def func(a,*args): print(a) print(args) func(1) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py 1 () def func(a,*args): print(a) print(args) func(1,3,4,5) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py 1 (3, 4, 5) **kwargs def func(a,**kwargs): print(a) print(kwargs) func(1,name='bob') C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py 1 {'name': 'bob'} def func(a,*args,**kwargs): print(a) print(args) print(kwargs) func(1,name='bob') C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py 1 () {'name': 'bob'} def func(a,*args,**kwargs): print(a) print(args) print(kwargs) func(1,3,name='bob') C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py 1 (3,) {'name': 'bob'} def func(a,*args,**kwargs): print(a) print(args) print(kwargs) func(1,*[1,2,3,4,]) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py 1 (1, 2, 3, 4) {} 16 局部变量: 变量只在函数里面生效 def func(a,*args,**kwargs): print(a) print(args) print(kwargs) cpu("%53") def cpu(value): print("the cup is %s" % value) func(1,*[1,2,3,4,]) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py 1 (1, 2, 3, 4) {} the cup is %53 def func(a,*args,**kwargs): print(a) print(args) print(kwargs) cpu("%53") func(1,*[1,2,3,4,]) def cpu(value): print("the cup is %s" % value) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py 1 Traceback (most recent call last): File "C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py", line 7, in <module> func(1,*[1,2,3,4,]) File "C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py", line 5, in func cpu("%53") NameError: name 'cpu' is not defined (1, 2, 3, 4) {} def change_data(data): print("before data",data) data=55 print("last data",data) data=22 change_data(data) print(data) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py before data 22 last data 55 22 全局变量 color="green" def change_data(data): print("before data",data,color) data=55 print("last data",data) data=22 change_data(data) print(data) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py before data 22 green last data 55 22 color="green" def change_data(data): color="blue" print("before data",data,color) data=55 print("last data",data) data=22 change_data(data) print(data) print(color) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py before data 22 blue last data 55 22 green 下面这种情况 global 最好不要这么写, C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py before data 22 blue last data 55 22 color is blue 递归 :在函数里面调用本次函数,必须要有个结束语;每次递归都要比上一次的数减小,否则就会成为死循环 def count(n): print(n) if int(n)>0: return count(int(n/2)) print(n) count(10) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py 10 5 2 1 0 匿名函数: calc=lambda x:x*5 print(calc(3)) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py 15 高阶函数 :参数里面换成函数 字符串转换成函数:eval() 17、装饰器 解释:是用来为其他函数添加附加功能的函数 原则: 1、不能动原来的函数代码 2、不能动原来函数的调用方式 函数就是变量 3、高阶函数+嵌套函数=装饰器 import time def timmer(func): def warpper(): start_time=time.time() func() stop_time=time.time() print("in the func is %s" % (stop_time-start_time)) return warpper def test(): time.sleep(3) print("welcome to bejing") test=timmer(test) test() import time def timmer(func): def warpper(*args,**kwargs): start_time=time.time() func() stop_time=time.time() print("in the func is %s" % (stop_time-start_time)) return warpper @timmer def test(): time.sleep(3) print("welcome to bejing") test() C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py welcome to bejing the actual run time is 3.0001721382141113 不动原来的函数代码 写两个函数,一个在上面 一个在下面 下面的函数调用上面的即可,但是动了函数的调用方式 不动原来函数的调用方式 import time def bar(): time.sleep(3) print("in the bar") def test2(func): #print(func) return func bar=test2(bar) bar() C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py <function bar at 0x0067B198> in the bar 函数嵌套: def foo(): print("in the foo") def bar(): print("in the bar") bar() foo() C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py in the foo in the bar 下面改变了函数调用方式 import time def deco(func): start_time=time.time() func() stop_time=time.time() print("in the func run is %s" % (stop_time-start_time)) return deco def test1(): time.sleep(3) print("in the test1") def test2(): time.sleep(3) print("in the test2") deco(test1) deco(test2) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py in the test1 in the func run is 3.000171184539795 in the test2 in the func run is 3.0001718997955322 下面报错 import time def deco(func): start_time=time.time() func() stop_time=time.time() print("in the func run is %s" % (stop_time-start_time)) return deco def test1(): time.sleep(3) print("in the test1") def test2(): time.sleep(3) print("in the test2") test1=deco(test1) test1() test2=deco(test2) test2() C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py in the test1 in the func run is 3.000170946121216 Traceback (most recent call last): File "C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py", line 16, in <module> test1() TypeError: deco() missing 1 required positional argument: 'func' 下面没有改变函数调用方式 但是没有添加功能 import time def deco(func): start_time=time.time() return func stop_time=time.time() print("in the func run is %s" % (stop_time-start_time)) return deco def test1(): time.sleep(3) print("in the test1") def test2(): time.sleep(3) print("in the test2") test1=deco(test1) test1() test2=deco(test2) test2() C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py in the test1 in the test2 完整的装饰器: import time def timmer(func): def deco(): start_time=time.time() func() stop_time=time.time() print("in the func run is %s" % (stop_time-start_time)) return deco @timmer #test1=timmer(test1) def test1(): time.sleep(3) print("in the test1") @timmer #=test2=timmer(test2) def test2(): time.sleep(3) print("in the test2") test1() test2() C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py in the test1 in the func run is 3.0001721382141113 in the test2 in the func run is 3.00017094612121 自己编写的完整的装饰器 # -*- coding:UTF-8 -*- import time def timmer(func): def deco(): func() print("welcome to beijing") return deco @timmer #test1=timmer(test1) def test1(): time.sleep(3) print("in the test1") @timmer #=test2=timmer(test2) def test2(): time.sleep(3) print("in the test2") test1() test2() ssh://root@192.168.0.75:22/usr/bin/python -u /app/py_code/test3.py in the test1 welcome to beijing in the test2 welcome to beijing 传参数 import time def timmer(func): def deco(name): start_time=time.time() func(name) stop_time=time.time() print("in the func run is %s" % (stop_time-start_time)) return deco #@timmer #=test1=timmer(test1) def test1(): time.sleep(3) #print("in the test1") @timmer #=test2=timmer(test2) def test2(name): time.sleep(3) print("in the test2",name) test1() test2("bob") C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py in the test2 bob in the func run is 3.000170946121216 import time def timmer(func): def deco(arg1,arg2): start_time=time.time() func(arg1,arg2) stop_time=time.time() print("in the func run is %s" % (stop_time-start_time)) return deco #@timmer #=test1=timmer(test1) def test1(): time.sleep(3) #print("in the test1") @timmer #=test2=timmer(test2) def test2(name,age): time.sleep(3) print("in the test2",name,age) test1() test2("bob",25) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py in the test2 bob 25 in the func run is 3.000170946121216 通用型传递参数的装饰器 import time def timmer(func): def deco(*args,**kwargs): start_time=time.time() func(*args,**kwargs) stop_time=time.time() print("in the func run is %s" % (stop_time-start_time)) return deco #@timmer #=test1=timmer(test1) def test1(): time.sleep(3) #print("in the test1") @timmer #=test2=timmer(test2) def test2(name,age,high): time.sleep(3) print("in the test2",name,age,high) test1() test2("bob",25,170) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py in the test2 bob 25 170 in the func run is 3.0001721382141113 https://www.cnblogs.com/cicaday/p/python-decorator.html 基于类实现的装饰器: 装饰器要求接受一个callable对象,并返回一个callable对象(不太严谨,详见后文)。那么用类来实现也是也可以的。我们可以让类的构造函数__init__()接受一个函数,然后重载__call__()并返回一个函数,也可以达到装饰器函数的效果。 class logging(object): def __init__(self, func): self.func = func def __call__(self, *args, **kwargs): print ("[DEBUG]: enter function {func}()".format( func=self.func.__name__)) return self.func(*args, **kwargs) @logging def say(something): print ("say {}!".format(something)) say('hello') E:\python\python.exe E:/django工程/第20章/app01/cehi3.py [DEBUG]: enter function say() say hello! 自己改编的基于类实现的装饰器 # -*- coding:UTF-8 -*- class logging(object): def __init__(self, func): self.func = func def __call__(self, *args, **kwargs): print ("[DEBUG]: enter function") return self.func(*args, **kwargs) @logging def say(something): print ("say",something) say('hello') ssh://root@192.168.0.75:22/usr/bin/python -u /app/py_code/test3.py [DEBUG]: enter function say hello 带参数的类装饰器 如果需要通过类形式实现带参数的装饰器,那么会比前面的例子稍微复杂一点。那么在构造函数里接受的就不是一个函数,而是传入的参数。通过类把这些参数保存起来。然后在重载__call__方法是就需要接受一个函数并返回一个函数。 class logging(object): def __init__(self, level='INFO'): self.level = level def __call__(self, func): # 接受函数 def wrapper(*args, **kwargs): print "[{level}]: enter function {func}()".format( level=self.level, func=func.__name__) func(*args, **kwargs) return wrapper #返回函数 @logging(level='INFO') def say(something): print "say {}!".format(something) E:\python\python.exe E:/django工程/第20章/app01/cehi3.py [INFO]: enter function say() say hello! 带参数的类装饰器--自己改编的 # -*- coding:UTF-8 -*- class logging(object): def __init__(self, level='INFO'): self.level = level def __call__(self, func): # 接受函数 def wrapper(*args, **kwargs): print ("[{level}]: enter function") func(*args, **kwargs) return wrapper #返回函数 @logging(level='INFO') def say(something): print ("say",something) say('hello') Python3学习(24)--内置装饰器 python中@property装饰器的用法 https://blog.csdn.net/wzqnls/article/details/53587049 不使用@property实现类 class Boy(object): def __init__(self, name): self.name = name def get_name(self): return self.name def set_name(self, new_name): self.name = new_name def del_name(self): del self.name boy = Boy('Tom') print(boy.get_name()) E:\python\python.exe E:/django工程/第20章/app01/cehi3.py Tom Alice 使用@property实现上述类 class Boy(object): def __init__(self, name): self._name = name @property def name(self): return self._name # 下面这个装饰器是由上面的@property衍生出来的装饰器 @name.setter def name(self,new_name): self._name = new_name @name.deleter def name(self): del self._name boy = Boy('Tom') boy.name = 'white dog' print(boy.name) del boy.name 实例二: class Animal(object): def __init__(self, name, age): self._name = name self._age = age self._color = 'Black' @property def name(self): return self._name @name.setter def name(self, value): self._name = value @property def age(self): return self._age @age.setter def age(self, value): if value > 0 and value < 100: self._age = value else: self._age = 0 # print 'invalid age value.' @property def color(self): return self._color @color.setter def color(self, style): self._color = style a = Animal('black dog', 3) a.name = 'white dog' a.age = 300 print ('Name:', a.name) print ('Age:', a.age) 18、迭代器与生成器 生成器: 只记录当前的位置,不能向前 也不能后退 只有一个a.__next__ 下面就是生成器; 打印的时候才有数据 不打印 没有数据 >>> a=(i*2 for i in range(10)) >>> a <generator object <genexpr> at 0x01FA3800> 斐波拉契数列 除第一个和第二个之外 所有的数都是由前两个数相加之和。 def fib(max): n,a,b=0,0,1 while n<max: print(b) a,b,=b,a+b n=n+1 return 'done' fib(10) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py 1 1 2 3 5 8 13 21 34 55 Process finished with exit code 0 解释; >>> a,b=1,2 >>> a 1 >>> b 2 >>> t=(b,a+b) >>> t (2, 3) 生成器: def fib(max): n,a,b=0,0,1 while n<max: yield b a,b,=b,a+b n=n+1 return 'done' print(fib(100)) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py <generator object fib at 0x0178E4B8> def fib(max): n,a,b=0,0,1 while n<max: yield b a,b,=b,a+b n=n+1 return 'done' f=(fib(10)) print(f.__next__()) print(f.__next__()) print(f.__next__()) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py 1 1 2 def fib(max): n,a,b=0,0,1 while n<max: yield b a,b,=b,a+b n=n+1 return 'done' f=(fib(10)) print(f.__next__()) print(f.__next__()) print(f.__next__()) print(f.__next__()) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py 1 1 2 3 这样可以不等把10个都打印完 就可以打印其他东西 def fib(max): n,a,b=0,0,1 while n<max: yield b a,b,=b,a+b n=n+1 return 'done' f=(fib(10)) print(f.__next__()) print("----------------------") print(f.__next__()) print("+++++++++++++++++++++++") print(f.__next__()) print(f.__next__()) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py 1 ---------------------- 1 +++++++++++++++++++++++ 2 3 相当于算法 def fib(max): n,a,b=0,0,1 while n<max: yield b a,b,=b,a+b n=n+1 return 'done' f=(fib(10)) print(f.__next__()) print("----------------------") print(f.__next__()) print("+++++++++++++++++++++++") print(f.__next__()) print(f.__next__()) print("-----------------for i in =-------------") for i in f: print(i) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py 1 ---------------------- 1 +++++++++++++++++++++++ 2 3 -----------------for i in =------------- 5 8 13 21 34 55 def fib(max): n,a,b=0,0,1 while n<max: yield b a,b,=b,a+b n=n+1 return 'done' f=(fib(10)) print(f.__next__()) print("----------------------") print(f.__next__()) print("+++++++++++++++++++++++") print(f.__next__()) print(f.__next__()) print("-----------------for i in =-------------") print(f.__next__()) print(f.__next__()) print(f.__next__()) print(f.__next__()) print(f.__next__()) print(f.__next__()) print(f.__next__()) 打印超过10个报错:异常处理 C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py 1 ---------------------- 1 +++++++++++++++++++++++ 2 3 -----------------for i in =------------- 5 8 13 21 34 55 Traceback (most recent call last): File "C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py", line 22, in <module> print(f.__next__()) StopIteration: done Process finished with exit code 1 def fib(max): n,a,b=0,0,1 while n<max: yield b a,b,=b,a+b n=n+1 return "done" f=fib(10) while True: try: x = next(f) print('f', x) except StopIteration as e: print("generator return value",e.value) break C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py f 1 f 1 f 2 f 3 f 5 f 8 f 13 f 21 f 34 f 55 generator return value done import time def consumer(name): print("%s 准备吃饭"%name) while True: chifan=yield print("饭%s好了,被%s吃了"% (chifan,name)) c=consumer("xiao ming") c.__next__() b="西红柿鸡蛋盖饭" c.send(b) c.__next__() C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py xiao ming 准备吃饭 饭西红柿鸡蛋盖饭好了,被xiao ming吃了 饭None好了,被xiao ming吃了 携程 单线程并行效果 :多个任务进程同时运行 --异步IO的雏形 import time def consumer(name): print("%s 准备吃饭"%name) while True: chifan=yield print("饭%s好了,被%s吃了"% (chifan,name)) def producer(name): a1=consumer('C') a2=consumer('D') a1.__next__() a2.__next__() print("厨师开始做饭") for i in range(10): time.sleep(1) print("做好了两份饭") a1.send(i) a2.send(i) producer("bob") C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py C 准备吃饭 D 准备吃饭 厨师开始做饭 做好了两份饭 饭0好了,被C吃了 饭0好了,被D吃了 做好了两份饭 饭1好了,被C吃了 饭1好了,被D吃了 做好了两份饭 饭2好了,被C吃了 饭2好了,被D吃了 做好了两份饭 饭3好了,被C吃了 饭3好了,被D吃了 做好了两份饭 饭4好了,被C吃了 饭4好了,被D吃了 做好了两份饭 饭5好了,被C吃了 饭5好了,被D吃了 做好了两份饭 饭6好了,被C吃了 饭6好了,被D吃了 做好了两份饭 饭7好了,被C吃了 饭7好了,被D吃了 做好了两份饭 饭8好了,被C吃了 饭8好了,被D吃了 做好了两份饭 饭9好了,被C吃了 饭9好了,被D吃了 Process finished with exit code 0 迭代器 迭代对象(Iterabale):可迭代对象:可循环的对象,包括:list dict tuple set(集合) str generator 迭代器(Iterator):可以被next()函数调用 并不断返回下个值的对象成为迭代器 迭代器和迭代对象的区别 迭代器是表示数据流,迭代器的计算的惰性的,只有在需要返回下一个值的时候才计算,而列表是提前计算好的,可以表示一个无限大的数据流,列表是有开始和结束值,是有限的 19 内置方法 all() print(all([0,1,-1])) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py False print(any([0,1,-1])) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py True bin() :把数字转换成二进制 >>> bin(55) '0b110111' exec() 把字符串转成能够调用的对象 code=""" def fib(max): n,a,b=0,0,1 while n<max: yield b a,b,=b,a+b n=n+1 return "done" f=fib(10) while True: try: x = next(f) print('f', x) except StopIteration as e: print("generator return value",e.value) break """ exec(code) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py f 1 f 1 f 2 f 3 f 5 f 8 f 13 f 21 f 34 f 55 generator return value done Process finished with exit code 0 dir() >>> a=[] >>> dir(a) ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'] 匿名函数:只能简单运算 calc=lambda n:print(n) calc(5) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py 5 filter() t=filter(lambda n:n>5,range(10)) for i in t: print(i) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py 6 7 8 9 map() t=map(lambda n:n*n,range(10)) for i in t: print(i) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py 0 1 4 9 16 25 36 49 64 81 reduce() import functools t=functools.reduce(lambda x,y:x+y,range(10)) print(t) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py 45 frozenset 不可变列表 a=frozenset([900]) globals() :打印全局变量 print(globals()) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py {'__spec__': None, '__doc__': None, '__loader__': <_frozen_importlib.SourceFileLoader object at 0x01714710>, '__name__': '__main__', '__builtins__': <module 'builtins' (built-in)>, '__file__': 'C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py', '__cached__': None, '__package__': None} hash() :一种算法,它有很多算法 思想:假如有5000个数字,要从里面取出特定的数字,如果要一个个的循环找 非常慢,如果用hash隔半去找 非常的快, >>> hash(1) 1 >>> hash(555) 555 >>> hash(rtyyuyu) Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> hash(rtyyuyu) NameError: name 'rtyyuyu' is not defined >>> hash(坎坎坷坷) Traceback (most recent call last): File "<pyshell#3>", line 1, in <module> hash(坎坎坷坷) NameError: name '坎坎坷坷' is not defined >>> hash('ffkfkkgf') -2073949958 hex():10进制转换成16进制 >>> hex(260) '0x104' >>> hex(320) '0x140' >>> hex(480) '0x1e0' >>> hex(1600) '0x640' >>> hex(3600) '0xe10' sorted() a={1:9,2:8,3:7,4:6} print(sorted(a)) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py [1, 2, 3, 4] a={1:9,2:8,3:7,4:6} print(sorted(a.items())) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py [(1, 9), (2, 8), (3, 7), (4, 6)] a={1:9,2:8,3:7,4:6} print(sorted(a.items(),key=lambda x:x[1])) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py [(4, 6), (3, 7), (2, 8), (1, 9)] zip() 拉链 合成一快 a=[1,2,3,4] b=['a','b','c','d'] for i in zip(a,b): print(i) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py (1, 'a') (2, 'b') (3, 'c') (4, 'd') 20 Json与Picle 的数据序列化 Json的数据序列化 :游戏挂起 import json info={ "name":"bob", "age":"18" } f=open("file.txt2","w") f.write(json.dumps(info)) f.close() C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py Process finished with exit code 0 Json的数据反序列化 游戏重新加载 import json f=open("file.txt2",'r') data=json.loads(f.read()) print(data["age"]) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py 18 Process finished with exit code 0 pickle import pickle def neicun(name): print("hello",name) info={ "name":"bob", "age":"18", "func":neicun } f=open("file.txt2","wb") f.write(pickle.dumps(info)) f.close() C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py Process finished with exit code 0 import pickle def neicun(name): print("hello",name) info={ "name":"bob", "age":"18", "func":neicun } f=open("file.txt2","wb") pickle.dump(info,f) f.close() C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py Process finished with exit code 0 pickle 反序列化 import pickle def neicun(name): print("hello",name) info={ "name":"bob", "age":"18", "func":neicun } def neicun(name): print("hello",name) f=open("file.txt2","rb") data=pickle.loads(f.read()) print(data) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py {'name': 'bob', 'age': '18', 'func': <function neicun at 0x00771C00>} import pickle def neicun(name): print("hello",name) info={ "name":"bob", "age":"18", "func":neicun } def neicun(name): print("hello",name) f=open("file.txt2","rb") data=pickle.loads(f.read()) print(data["func"]("name")) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py hello name None import pickle def neicun(name): #print("hello",name) print("hello2",name) info={ "name":"bob", "age":"18", "func":neicun } f=open("file.txt2","rb") data=pickle.loads(f.read()) print(data["func"]("neicun")) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py hello2 neicun None import pickle def neicun(name): #print("hello",name) print("hello2",name) info={ "name":"bob", "age":"18", "func":neicun } f=open("file.txt2","rb") data=pickle.load(f) print(data["func"]("neicun")) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/lianxi.py hello2 neicun None 21 软件目录结构规范 :就是调用 import os import sys dir_namae=os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(dir_namae) from file3 import file3 file3 C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/dir/file2/file2.py hello 第五章 第九节 shelve 模块:全部依次到处 再全部依次导入 xml模块 <data> <country name="Liechtenstein"> <rank updated="yes">2</rank> <year>2008</year> <gdppc>141100</gdppc> <neighbor name="Austria" direction="E"/> <neighbor name="Switzerland" direction="W"/> </country> <country name="Singapore"> <rank updated="yes">5</rank> <year>2011</year> <gdppc>59900</gdppc> <neighbor name="Malaysia" direction="N"/> </country> <country name="Panama"> <rank updated="yes">69</rank> <year>2011</year> <gdppc>13600</gdppc> <neighbor name="Costa Rica" direction="W"/> <sex/> <mail>mail</mail> <neighbor name="Colombia" direction="E"/> </country> </data> import xml import xml.etree.ElementTree as ET tree=ET.parse("xml.test.xml") root=tree.getroot() for child in root: print(child.tag, child.attrib) for i in child: print(i.tag,i.text,i.attrib) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/dir/file2/333.py country {'name': 'Liechtenstein'} rank 2 {'updated': 'yes'} year 2008 {} gdppc 141100 {} neighbor None {'name': 'Austria', 'direction': 'E'} neighbor None {'name': 'Switzerland', 'direction': 'W'} country {'name': 'Singapore'} rank 5 {'updated': 'yes'} year 2011 {} gdppc 59900 {} neighbor None {'name': 'Malaysia', 'direction': 'N'} country {'name': 'Panama'} rank 69 {'updated': 'yes'} year 2011 {} gdppc 13600 {} neighbor None {'name': 'Costa Rica', 'direction': 'W'} sex None {} mail mail {} neighbor None {'name': 'Colombia', 'direction': 'E'} Process finished with exit code 0 import xml import xml.etree.ElementTree as ET tree=ET.parse("xml.test.xml") root=tree.getroot() for node in root.iter('year'): print(node.tag,node.text) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/dir/file2/333.py year 2008 year 2011 year 2011 第五周第十三章 sha、md5 两种加密 sha更安全 import hashlib m=hashlib.md5() m.update(b"bob") print(m.hexdigest()) m.update(b"jon") print(m.hexdigest()) m2=hashlib.md5() m2.update(b"bobjon") print(m.hexdigest()) s2=hashlib.sha1() s2.update(b"bobjon") print(s2.hexdigest()) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/dir/file2/333.py 9f9d51bc70ef21ca5c14f307980a29d8 2a017499db12fd36c76b797a8410f0f4 2a017499db12fd36c76b797a8410f0f4 ff9ab5becac0a97f1c395a692057669219bfe44c 消息加密 加密更长 更安全 import hmac h=hmac.new(b"bob55","Im here".encode(encoding="utf-8")) print(h.digest()) print(h.hexdigest()) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/dir/file2/333.py b'\xed\xc2\x0f\x13\x00\x98\xc2l\xf4\xcdo\x0c\xf12c\xfe' edc20f130098c26cf4cd6f0cf13263fe Process finished with exit code 0 第六周 第四章 类-opp编程 class Role(object): n=123 def __init__(self,name,role,weapon,life_value=100,money=15000): self.name = name self.role = role self.weapon = weapon self.life_value = life_value self.money = money def shot(self): print("shooting...") def got_shot(self): print("ah...,I got shot...") def buy_gun(self,gun_name): print("%s just bought %s" % (self.name,gun_name) ) r1 = Role('Alex','police',"AK47") #生成一个角色 r2 = Role('Jack','terrorist','B22') #生成一个角色 r1.buy_gun("ak47") r2.got_shot() C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/dir/file2/333.py Alex just bought ak47 ah...,I got shot... class Role(object): n=123 #类变量 def __init__(self,name,role,weapon,life_value=100,money=15000): self.name = name self.role = role self.weapon = weapon self.life_value = life_value self.money = money def shot(self): print("shooting...") def got_shot(self): print("ah...,I got shot...") def buy_gun(self,gun_name): print("%s just bought %s" % (self.name,gun_name) ) print(Role.n) r1 = Role('Alex','police',"AK47") #生成一个角色 print(r1.n,r1.name) r2 = Role('Jack','terrorist','B22') #生成一个角色 print(r2.n,r2.name) #r1.buy_gun("ak47") #r2.got_shot() C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/dir/file2/333.py 123 123 Alex 123 Jack 增加属性 class Role(object): n=123 #类变量 name="我是类name" def __init__(self,name,role,weapon,life_value=100,money=15000): self.name = name self.role = role self.weapon = weapon self.life_value = life_value self.money = money def shot(self): print("shooting...") def got_shot(self): print("ah...,I got shot...") def buy_gun(self,gun_name): print("%s just bought %s" % (self.name,gun_name) ) print(Role.n) r1 = Role('Alex','police',"AK47") #生成一个角色 r1.name="bob" r1.bullet_prove="true" print(r1.n,r1.name,r1.bullet_prove) r2 = Role('jack','terrorist','B22') #生成一个角色 r2.name="cat" print(r2.n,r2.name) #r1.buy_gun("ak47") #r2.got_shot() C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/dir/file2/333.py 123 123 bob true 123 cat 删除属性 class Role(object): n=123 #类变量 name="我是类name" def __init__(self,name,role,weapon,life_value=100,money=15000): self.name = name self.role = role self.weapon = weapon self.life_value = life_value self.money = money def shot(self): print("shooting...") def got_shot(self): print("ah...,I got shot...") def buy_gun(self,gun_name): print("%s just bought %s" % (self.name,gun_name) ) print(Role.n) r1 = Role('Alex','police',"AK47") #生成一个角色 r1.name="bob" r1.bullet_prove="true" print (r1.weapon) del r1.weapon print(r1.n,r1.name,r1.bullet_prove,r1.weapon) r2 = Role('jack','terrorist','B22') #生成一个角色 r2.name="cat" print(r2.n,r2.name) #r1.buy_gun("ak47") #r2.got_shot() C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/dir/file2/333.py 123 AK47 Traceback (most recent call last): File "C:/Users/Administrator/PycharmProjects/untitled25/dir/file2/333.py", line 28, in <module> print(r1.n,r1.name,r1.bullet_prove,r1.weapon) AttributeError: 'Role' object has no attribute 'weapon 改类变量 :其实是在实例变量里面添加了一个实例变量 跟类变量没关系 class Role(object): n="改类变量前" #类变量 name="我是类name" def __init__(self,name,role,weapon,life_value=100,money=15000): self.name = name self.role = role self.weapon = weapon self.life_value = life_value self.money = money def shot(self): print("shooting...") def got_shot(self): print("ah...,I got shot...") def buy_gun(self,gun_name): print("%s just bought %s" % (self.name,gun_name) ) print(Role.n) r1 = Role('Alex','police',"AK47") #生成一个角色 r1.name="bob" r1.bullet_prove="true" r1.n="改类变量后" print (r1.n) print(r1.n,r1.name,r1.bullet_prove,r1.weapon) r2 = Role('jack','terrorist','B22') #生成一个角色 r2.name="cat" print(r2.n,r2.name) #r1.buy_gun("ak47") #r2.got_shot() C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/dir/file2/333.py 改类变量前 改类变量后 改类变量后 bob true AK47 改类变量前 cat Process finished with exit code 0 class Role(object): n=123 #类变量 name="dog" def __init__(self,name,role,weapon,life_value=100,money=15000): self.name = name self.role = role self.weapon = weapon self.life_value = life_value self.money = money def shot(self): print("shooting...") def got_shot(self): print("ah...,I got shot...") def buy_gun(self,gun_name): print("%s just bought %s" % (self.name,gun_name) ) r1 = Role('Alex','police',"AK47") #生成一个角色 r1.name="bob" r1.bullet_prove="true" r1.n="beet" print(Role.n) r2 = Role('jack','terrorist','B22') #生成一个角色 r2.name="cat" Role.n="abc" print(Role.n) #r1.buy_gun("ak47") #r2.got_shot() C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/dir/file2/333.py 123 abc class Role(object): n=123 #类变量 name="我是类name" list=[] def __init__(self,name,role,weapon,life_value=100,money=15000): self.name = name self.role = role self.weapon = weapon self.life_value = life_value self.money = money def shot(self): print("shooting...") def got_shot(self): print("ah...,I got shot...") def buy_gun(self,gun_name): print("%s just bought %s" % (self.name,gun_name) ) print(Role.n) r1 = Role('Alex','police',"AK47") #生成一个角色 r1.name="bob" r1.bullet_prove="true" r1.n="beet" r1.list.append("china") print (r1.n) print(r1.n,r1.name,r1.bullet_prove,r1.weapon,r1.list) r2 = Role('jack','terrorist','B22') #生成一个角色 r2.name="cat" Role.n="abc" print(r1.n,r2.n,r1.list) #r1.buy_gun("ak47") #r2.got_shot() C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/dir/file2/333.py 123 beet beet bob true AK47 ['china'] beet abc ['china'] 第六周 第六章 1、构造函数: def __init__(self,name,role,weapon,life_value=100,money=15000): self.name = name self.role = role self.weapon = weapon self.life_value = life_value self.money = money 类变量的作用 ----节省内存,如果放在实例变量里面 每次实例化的时候都会增加一个内存。 2、析构函数:在实例释放、销毁的时候执行的,通常用于做一些收尾工作,比如关闭一些数据库连接、打开的临时文件。 class Role(object): n=123 #类变量 name="dog" def __init__(self,name,role,weapon,life_value=100,money=15000): self.name = name self.role = role self.weapon = weapon self.life_value = life_value self.money = money def __del__(self): print("%s is dead " % self.name) def shot(self): print("shooting...") def got_shot(self): print("ah...,I got shot...") def buy_gun(self,gun_name): print("%s just bought %s" % (self.name,gun_name) ) r1 = Role('Alex','police',"AK47") #生成一个角色 C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py Alex is dead class Role(object): n=123 #类变量 name="dog" def __init__(self,name,role,weapon,life_value=100,money=15000): self.name = name self.role = role self.weapon = weapon self.life_value = life_value self.money = money def __del__(self): print("%s is dead " % self.name) def shot(self): print("shooting...") def got_shot(self): print("ah...,I got shot...") def buy_gun(self,gun_name): print("%s just bought %s" % (self.name,gun_name) ) r1 = Role('Alex','police',"AK47") #生成一个角色 r1.buy_gun("AK47") r1.got_shot() r2 = Role('jack','terrorist','B22') r2.got_shot() C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py Alex just bought AK47 ah...,I got shot... ah...,I got shot... jack is dead Alex is dead 3、私有方法、私有属性 属性:静态属性、动态属性 静态属性:就是变量 动态属性:就是方法 一般属性就是变量 方法就是方法 私有:别人访问不了, 如果别人能访问 就可以改动 ,所以规定只能在中枪后减小血量,别人能看到还剩多少血量, 例如: r1.life_value="0" 私有属性: class Role(object): n=123 #类变量 name="dog" def __init__(self,name,role,weapon,life_value=100,money=15000): self.name = name self.role = role self.weapon = weapon self.__life_value = life_value self.money = money def shot(self): print("shooting...") def got_shot(self): print("ah...,I got shot...") def buy_gun(self,gun_name): print("%s just bought %s" % (self.name,gun_name) ) r1 = Role('Alex','police',"AK47") #生成一个角色 r1.buy_gun("AK47") r1.got_shot() print(r1.__life_value) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py Traceback (most recent call last): File "C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py", line 25, in <module> print(r1.life_value) AttributeError: 'Role' object has no attribute 'life_value' Alex just bought AK47 ah...,I got shot... 别人怎么看还剩多少血量 class Role(object): n=123 #类变量 name="dog" def __init__(self,name,role,weapon,life_value=100,money=15000): self.name = name self.role = role self.weapon = weapon self.__life_value = life_value self.money = money def show_data(self): print("name:%s weapon:%s life_value:%s" % (self.name,self.weapon,self.__life_value)) def shot(self): print("shooting...") def got_shot(self): print("ah...,I got shot...") def buy_gun(self,gun_name): print("%s just bought %s" % (self.name,gun_name) ) r1 = Role('Alex','police',"AK47") #生成一个角色 r1.buy_gun("AK47") r1.show_data() C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py Alex just bought AK47 name:Alex weapon:AK47 life_value:100 在内部也可以访问: class Role(object): n=123 #类变量 name="dog" def __init__(self,name,role,weapon,life_value=100,money=15000): self.name = name self.role = role self.weapon = weapon self.__life_value = life_value self.money = money def show_data(self): print("name:%s weapon:%s life_value:%s" % (self.name,self.weapon,self.__life_value)) def shot(self): print("shooting...") def got_shot(self): self.__life_value -= 50 print("ah...,I got shot...") def buy_gun(self,gun_name): print("%s just bought %s" % (self.name,gun_name) ) r1 = Role('Alex','police',"AK47") #生成一个角色 r1.buy_gun("AK47") r1.got_shot() r1.show_data() C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py Alex just bought AK47 ah...,I got shot... name:Alex weapon:AK47 life_value:50 私有方法: def got_shot(self): 外部无法访问 class Role(object): n=123 #类变量 name="dog" def __init__(self,name,role,weapon,life_value=100,money=15000): self.name = name self.role = role self.weapon = weapon self.__life_value = life_value self.money = money def show_data(self): print("name:%s weapon:%s life_value:%s" % (self.name,self.weapon,self.__life_value)) def __shot(self): print("shooting...") def got_shot(self): self.__life_value -= 50 print("ah...,I got shot...") def buy_gun(self,gun_name): print("%s just bought %s" % (self.name,gun_name) ) r1 = Role('Alex','police',"AK47") #生成一个角色 r1.buy_gun("AK47") r1.__got_shot() C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py Traceback (most recent call last): File "C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py", line 25, in <module> r1.__got_shot() AttributeError: 'Role' object has no attribute '__got_shot' Alex just bought AK47 第六周 第七章 类的继承 面向对象的特性 :封装 继承 多态 类的继承: class People: def __init__(self,name,age): self.name=name self.age=age def eat(self): print("%s is eating.." % self.name) def talk(self): print("%s is sleeping" % self.name) def sleep(self): print("%s is sleeping" % self.name) class Man(People): pass m1=Man("bob",25) m1.eat() C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py bob is eating.. 子类定义方法: class People: def __init__(self,name,age): self.name=name self.age=age def eat(self): print("%s is eating.." % self.name) def talk(self): print("%s is sleeping" % self.name) def sleep(self): print("%s is sleeping" % self.name) class Man(People): def write(self): print("%s is writting" % self.name) m1=Man("bob",25) m1.write() C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py bob is writting 重构父类方法: class People: def __init__(self,name,age): self.name=name self.age=age def eat(self): print("%s is eating.." % self.name) def talk(self): print("%s is sleeping" % self.name) def sleep(self): print("%s is sleeping" % self.name) class Man(People): def write(self): print("%s is writting" % self.name) def sleep(self): People.sleep(self) print("man is sleeping") m1=Man("bob",25) m1.write() m1.sleep() C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py bob is writting bob is sleeping man is sleeping class People: def __init__(self,name,age): self.name=name self.age=age def eat(self): print("%s is eating.." % self.name) def talk(self): print("%s is sleeping" % self.name) def sleep(self): print("%s is sleeping" % self.name) class Man(People): def write(self): print("%s is writting" % self.name) def sleep(self): People.sleep(self) print("man is sleeping") class Woman(People): def get_birth(self): print("%s is get_birth" % self.name) m1=Man("bob",25) m1.write() w1=Woman("Jon",35) w1.get_birth() C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py bob is writting Jon is get_birth 第六周 第八章: 对构造函数进行重构: class People: def __init__(self,name,age): self.name=name self.age=age def eat(self): print("%s is eating.." % self.name) def talk(self): print("%s is sleeping" % self.name) def sleep(self): print("%s is sleeping" % self.name) class Man(People): def __init__(self,name,age,money): People.__init__(self,name,age) self.money=money print("%s birth is have %s dollor" % (self.name,self.money)) def write(self): print("%s is writting" % self.name) def sleep(self): People.sleep(self) print("man is sleeping") class Woman(People): def get_birth(self): print("%s is get_birth" % self.name) m1=Man("bob",25,10) m1.write() w1=Woman("Jon",35) w1.get_birth() C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py bob birth is have 10 dollor bob is writting Jon is get_birth 多个子类重构用下面这个: class People: def __init__(self,name,age): self.name=name self.age=age def eat(self): print("%s is eating.." % self.name) def talk(self): print("%s is sleeping" % self.name) def sleep(self): print("%s is sleeping" % self.name) class Man(People): def __init__(self,name,age,money): #People.__init__(self,name,age) super(Man,self).__init__(name,age) self.money=money print("%s birth is have %s dollor" % (self.name,self.money)) def write(self): print("%s is writting" % self.name) def sleep(self): People.sleep(self) print("man is sleeping") class Woman(People): def get_birth(self): print("%s is get_birth" % self.name) m1=Man("bob",25,10) m1.write() w1=Woman("Jon",35) w1.get_birth() C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py bob birth is have 10 dollor bob is writting Jon is get_birth 经典类和新式类的区别主要体现在类的继承上 新式类:class People(object): 多继承 class People(object): def __init__(self,name,age): self.name=name self.age=age def eat(self): print("%s is eating.." % self.name) def talk(self): print("%s is sleeping" % self.name) def sleep(self): print("%s is sleeping" % self.name) class Relation(object): def make_friends(self,obj): print("%s is make friends with %s" % (self.name,obj.name)) class Man(People,Relation): def __init__(self,name,age,money): #People.__init__(self,name,age) super(Man,self).__init__(name,age) #新式类写法 self.money=money print("%s birth is have %s dollor" % (self.name,self.money)) def write(self): print("%s is writting" % self.name) def sleep(self): People.sleep(self) print("man is sleeping") class Woman(People): def get_birth(self): print("%s is get_birth" % self.name) m1=Man("bob",25,10) w1=Woman("Jon",35) m1.make_friends(w1) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py bob birth is have 10 dollor bob is make friends with Jon 第八章 类的继承2 多继承 class People(object): def __init__(self,name,age): self.name=name self.age=age def eat(self): print("%s is eating.." % self.name) def talk(self): print("%s is sleeping" % self.name) def sleep(self): print("%s is sleeping" % self.name) class Relation(object): def make_friends(self,obj): print("%s is make friends with %s" % (self.name,obj.name)) class Man(People,Relation): def __init__(self,name,age,money): super(Man,self).__init__(name,age) self.money=money print("%s birth is have %s dollor" % (self.name,self.money)) def write(self): print("%s is writting" % self.name) def sleep(self): People.sleep(self) print("man is sleeping") class Woman(People,Relation): def get_birth(self): print("%s is get_birth" % self.name) m1=Man("bob",25,10) w1=Woman("Jon",35) m1.make_friends(w1) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py bob birth is have 10 dollor bob is make friends with Jon 下面第一种方式正确,第二种方式错误 必须是 self.friends.append(obj)
下面第一种方式解释:
类People定义构造函数, 类Relation故意不定义构造函数,注意Relation里面可以使用People的self.friends=[] 如果不写,后面报错, Man继承People 、Relation。Woman继承People 、Relation
1、第一种
1.1 正确
class People(object):
def __init__(self,name,age): self.name=name self.age=age self.friends=[] # 这句话表明把self.name=name 里面的name写到列表里面 def eat(self): print("%s is eating.." % self.name) def talk(self): print("%s is sleeping" % self.name) def sleep(self): print("%s is sleeping" % self.name) class Relation(object): def make_friends(self,obj): print("%s is make friends with %s" % (self.name,obj.name)) #显示灰色正常 self.friends.append(obj) # 这一步对应 m1.make_friends(w1),obj是一个实例等价于Woman("Jon",35)这个整体类,可以使用obj.name=Woman.name,就相当于调用类People里面的self.name即People.name,这就是类的继承 class Man(People,Relation): def __init__(self,name,age,money): super(Man,self).__init__(name,age) self.money=money print("%s birth is have %s dollor" % (self.name,self.money)) def write(self): print("%s is writting" % self.name) def sleep(self): People.sleep(self) print("man is sleeping") class Woman(People,Relation): def get_birth(self): print("%s is get_birth" % self.name) m1=Man("bob",25,10) w1=Woman("Jon",35) # 这一步把这两个参数传递给下一步 m1.make_freiends(w1)里面 m1.make_friends(w1) # 这一步会把w1里面的 Jon,35这两个参数通过make_friends函数写到self.friends[]列表里面 w1.name="klog" # 这一步是把w1=Woman("Jon,35")里面的Jon重新赋值成klog,然后重新执行m1.make_friends(w1)而不是清空列表,所以下一步打印出来的结果示klog,如果注释掉这句话,就会打印出来上一步列表里面的Jon print(m1.friends[0].name) # C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py bob birth is have 10 dollor bob is make friends with Jon klog
1.2 自己改动的
class People(object): def __init__(self,name,age): self.name=name self.age=age self.friends=[] def eat(self): print("%s is eating.." % self.name) def talk(self): print("%s is sleeping" % self.name) def sleep(self): print("%s is sleeping" % self.name) class Relation(object): def make_friends(self,obj): print("%s is make friends with %s" % (self.name,obj.name)) self.friends.append(obj) class Man(People,Relation): def __init__(self,name,age,money): super(Man,self).__init__(name,age) self.money=money print("%s birth is have %s dollor" % (self.name,self.money)) def write(self): print("%s is writting" % self.name) def sleep(self): People.sleep(self) print("man is sleeping") class Woman(People,Relation): def get_birth(self): print("%s is get_birth" % self.name) m1=Man("bob",25,10) w1=Woman("Jon",35) m1.make_friends(w1) w1.name="klog" print(m1.friends[0].name) m1.make_friends(w1) print(m1.friends[1].name) bob birth is have 10 dollor bob is make friends with Jon klog bob is make friends with klog klog
2、第二种 错误的方式
class People(object): def __init__(self,name,age): self.name=name self.age=age self.friends=[] def eat(self): print("%s is eating.." % self.name) def talk(self): print("%s is sleeping" % self.name) def sleep(self): print("%s is sleeping" % self.name) class Relation(object): def make_friends(self,obj): print("%s is make friends with %s" % (self.name,obj.name)) self.friends.append(obj.name) # 这句话表明添加完对象后就写进了People类里面的self.friends列表里面,只添加 name class Man(People,Relation): # Man类继承了People类和Relation类 def __init__(self,name,age,money): super(Man,self).__init__(name,age) # 这句话把People类里面的 name、age参数 重写了一遍 self.money=money print("%s birth is have %s dollor" % (self.name,self.money)) def write(self): print("%s is writting" % self.name) def sleep(self): People.sleep(self) print("man is sleeping") class Woman(People,Relation): # 这个Woman类继承了 People类和Relation类 def get_birth(self): print("%s is get_birth" % self.name) m1=Man("bob",25,10) w1=Woman("Jon",35) m1.make_friends(w1) # 这句话表明把w1里面的两个参数看成一个整体obj对象传给了make_friends函数 w1.name="klog" # 这句话把Jon替换成了klog又重新执行了一遍make_friends,看下面2.2 打印的结果 print(m1.friends[0]) # 这句话表明只打印w1元组里面的第一个数值 'Jon' C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py bob birth is have 10 dollor bob is make friends with Jon Jon
第六章 经典类与新式类 先走Relation super(Man,self).__init__(name,age) 按照继承顺序来继承 继承的先后顺序 前提是man 里面没有构造函数的时候 先走Relation class People(object): def __init__(self,name,age): self.name=name self.age=age self.friends=[] print("get the people way") def eat(self): print("%s is eating.." % self.name) def talk(self): print("%s is sleeping" % self.name) def sleep(self): print("%s is sleeping" % self.name) class Relation(object): def __init__(self,n1,n2): print("get the Relation way") def make_friends(self,obj): print("%s is make friends with %s" % (self.name,obj.name)) self.friends.append(obj.name) class Man(Relation,People): def write(self): print("%s is writting" % self.name) def sleep(self): People.sleep(self) print("man is sleeping") class Woman(People,Relation): def get_birth(self): print("%s is get_birth" % self.name) m1=Man("bob",25) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py get the Relation way man里面有People构造函的时候,先走people class People(object): def __init__(self,name,age): self.name=name self.age=age self.friends=[] print("get the people way") def eat(self): print("%s is eating.." % self.name) def talk(self): print("%s is sleeping" % self.name) def sleep(self): print("%s is sleeping" % self.name) class Relation(object): def __init__(self,n1,n2): print("get the Relation way") def make_friends(self,obj): print("%s is make friends with %s" % (self.name,obj.name)) self.friends.append(obj.name) class Man(Relation,People): def __init__(self,name,age,money): People.__init__(self,name,age) def write(self): print("%s is writting" % self.name) def sleep(self): People.sleep(self) print("man is sleeping") class Woman(People,Relation): def get_birth(self): print("%s is get_birth" % self.name) m1=Man("bob",25,10) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py get the people way man里面如果是 super构造函数的时候,自动按照优先顺序 先走Relation class People(object): def __init__(self,name,age): self.name=name self.age=age self.friends=[] print("get the people way") def eat(self): print("%s is eating.." % self.name) def talk(self): print("%s is sleeping" % self.name) def sleep(self): print("%s is sleeping" % self.name) class Relation(object): def __init__(self,n1,n2): print("get the Relation way") def make_friends(self,obj): print("%s is make friends with %s" % (self.name,obj.name)) self.friends.append(obj.name) class Man(Relation,People): def __init__(self,name,age): super(Man,self).__init__(name,age) def write(self): print("%s is writting" % self.name) def sleep(self): People.sleep(self) print("man is sleeping") class Woman(People,Relation): def get_birth(self): print("%s is get_birth" % self.name) m1=Man("bob",25) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py get the Relation way 类的继承先后顺序 python2里面的经典类和新式类都是深度优先策略,python3里面的经典类和新式类都是广义优先。 广义优先的查询路径:D-B-C-A 深度优先的查询路径:D-B-A class A: def __init__(self): print("A") class B(A): pass class C(A): pass class D(B,C): def __init__(self): print("D") D() C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py D class A(object): def __init__(self): print("A") class B(A): pass class C(A): pass class D(B,C): def __init__(self): print("D") D() C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py D class A: def __init__(self): print("A") class B(A): def __init__(self): print("B") class C(A): def __init__(self): print("C") class D(B,C): pass D() C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py B class A: def __init__(self): print("A") class B(A): pass class C(A): def __init__(self): print("C") class D(B,C): pass D() C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py C class A: def __init__(self): print("A") class B(A): pass class C(A): pass class D(B,C): pass D() C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py A 第六周 第十章 继承类实例讲解
class school(object): def __init__(self,name,addr): self.name=name self.addr=addr #self.students=[] #self.teacher=[] def enroll(self,stu_obj): print("为学员%s办理注册手续" % stu_obj.name) #self.students.append(stu_obj) class schoolnumber(object): def __init__(self,name,age,sex): self.name=name self.age=age self.sex=sex def tell(self): pass class teacher(schoolnumber): def __init__(self,name,age,sex,salary,course): super(teacher,self).__init__(name,age,sex) self.salary=salary self.course=course def tell(self): print(''' ---------info of teacher:%s---- name:%s age:%s sex:%s salary:%s course:%s '''% (self.name,self.name,self.age,self.sex,self.salary,self.course)) def teach(self): print("%s is teaching course %s" % (self.name,self.course)) class students(schoolnumber): def __init__(self,name,age,sex,stu_id,grade): super(students,self).__init__(name,age,sex) self.stu_id=stu_id self.grade=grade def tell(self): print(''' ---------info of teacher:%s---- name:%s age:%s sex:%s stu_id:%s grade:%s '''% (self.name,self.name,self.age,self.sex,self.stu_id,self.grade)) def pay_for(self,amount): print("%s is pay for %s dollars" % (self.name,amount)) school=school("河北工大","天津") t1=teacher("bob",33,"man",5000,"math") students=students("jack",22,"man",101880,"linux") school.enroll(students)
C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py
为学员jack办理注册手续
实例2:
class school(object): def __init__(self,name,addr): self.name=name self.addr=addr self.students_number=[] self.staffs_number=[] def enroll(self,stu_obj): #self.students.append(stu_obj) print("为学员%s办理注册手续" % stu_obj.name) self.students_number.append(stu_obj) def hire(self,staff_obj): print("%s is hired" % staff_obj.name) self.staffs_number.append(staff_obj) class schoolnumber(object): def __init__(self,name,age,sex): self.name=name self.age=age self.sex=sex def tell(self): pass class teacher(schoolnumber): def __init__(self,name,age,sex,salary,course): super(teacher,self).__init__(name,age,sex) self.salary=salary self.course=course def tell(self): print(''' ---------info of teacher:%s---- name:%s age:%s sex:%s salary:%s course:%s '''% (self.name,self.name,self.age,self.sex,self.salary,self.course)) def teach(self): print("%s is teaching course %s" % (self.name,self.course)) class students(schoolnumber): def __init__(self,name,age,sex,stu_id,grade): super(students,self).__init__(name,age,sex) self.stu_id=stu_id self.grade=grade def tell(self): print(''' ---------info of teacher:%s---- name:%s age:%s sex:%s stu_id:%s grade:%s '''% (self.name,self.name,self.age,self.sex,self.stu_id,self.grade)) def pay_for(self,amount): print("%s is pay for %s dollars" % (self.name,amount)) institution=school("河北工大","天津") s1=students("bob",33,"man",5000,"math") s2=students("cat",35,"man",6000,"scientist") t1=teacher("hing_teacher",33,"man",5000,"math") t2=teacher("jack_teacher",22,"man",101880,"linux") #t1.teach() institution.enroll(s1) institution.enroll(s2) institution.hire(t1) institution.hire(t2) print(institution.students_number) print(institution.staffs_number) #institution.staffs[0].teach() for str in institution.students_number: str.pay_for(5000) ssh://root@192.168.0.204:22/usr/bin/python -u /home/progect/app/py_code/test1.py 为学员bob办理注册手续 为学员cat办理注册手续 hing_teacher is hired jack_teacher is hired [<__main__.students object at 0x7f8d30dc0e10>, <__main__.students object at 0x7f8d30dc0e48>] [<__main__.teacher object at 0x7f8d30dc0e80>, <__main__.teacher object at 0x7f8d30dc0eb8>] bob is pay for 5000 dollars cat is pay for 5000 dollars
第六周 第十一章 多态实例讲解 意思:同一种接口,多种实现。 class Animal(object): def __init__(self,name): self.name=name def talk(self): pass class Dog(Animal): def talk(self): print("wang wangw wang") class Cat(Animal): def talk(self): print("miao miao miao") def animal_talk(obj): obj.talk() a=Dog("bob") b=Cat("jack") animal_talk(a) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py wang wangw wang class Animal(object): def __init__(self,name): self.name=name def talk(self): pass @classmethod def animal_talk(self,obj): obj.talk() class Dog(Animal): def talk(self): print("wang wangw wang") class Cat(Animal): def talk(self): print("miao miao miao") a=Dog("bob") b=Cat("jack") Animal.animal_talk(a) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py wang wangw wang 第七周 第三章 静态方法 类方法 属性方法 静态方法 只是名义上上归类管理,实例上在静态方法里访问不了类和实例中的任何属性 类方法 没啥用,只能访问类变量,不能访问实例变量 属性方法 有用,作用:把一个方法变成一个静态属性 1、静态方法 :只是名义上上归类管理,实例上在静态方法里访问不了类和实例中的任何属性 没啥用 类似于os.mkdir 等分离的工具包 class Dog(object): def __init__(self,name): self.name=name @staticmethod #这个的意思是底下的函数和类没什么关系 def eat(): print("%s is eating %s" % ("cat","馒头")) d=Dog("bob") d.eat() C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py cat is eating 馒头 class Dog(object): def __init__(self,name): self.name=name @staticmethod #这个的意思是底下的函数和类没什么关系 def eat(self): print("%s is eating %s" % (self.name,"馒头")) d=Dog("bob") d.eat(d) #传的是实例d C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py bob is eating 馒头 class Dog(object): def __init__(self,name): self.name=name @staticmethod #这个的意思是底下的函数和类没什么关系 def eat(self): print("%s is eating %s" % (self.name,"馒头")) def talk(self): print("%s is talking" % self.name) d=Dog("bob") d.eat(d) #传的是实例d d.talk() C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py bob is eating 馒头 bob is talking 2、类方法 没啥用 只能访问类变量,不能访问实例变量 class Dog(object): n=555 def __init__(self,name): self.name=name @classmethod #这个的意思是底下的函数和类没什么关系 def eat(self): print("%s is eating %s" % (self.n,"馒头")) def talk(self): print("%s is talking" % self.name) d=Dog("bob") d.eat() C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py 555 is eating 馒头 class Dog(object): name="jack" def __init__(self,name): self.name=name @classmethod #这个的意思是底下的函数和类没什么关系 def eat(self): print("%s is eating %s" % (self.name,"馒头")) def talk(self): print("%s is talking" % self.name) d=Dog("bob") d.eat() C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py jack is eating 馒头 3、属性方法 :有用 作用:把一个方法变成一个静态属性 class Dog(object): def __init__(self,name): self.name=name @property #这个的意思是底下的函数和类没什么关系 def eat(self): print("%s is eating %s" % (self.name,"馒头")) def talk(self): print("%s is talking" % self.name) d=Dog("bob") d.eat() C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py bob is eating 馒头 Traceback (most recent call last): File "C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py", line 13, in <module> d.eat() TypeError: 'NoneType' object is not callable class Dog(object): def __init__(self,name): self.name=name @property #这个的意思是底下的函数和类没什么关系 def eat(self): print("%s is eating %s" % (self.name,"馒头")) def talk(self): print("%s is talking" % self.name) d=Dog("bob") d.eat C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py bob is eating 馒头 class Dog(object): def __init__(self,name): self.name=name @property #这个的意思是底下的函数和类没什么关系 def eat(self,food): print("%s is eating %s" % (self.name,food)) def talk(self): print("%s is talking" % self.name) d=Dog("bob") d.eat("bao zi") C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py Traceback (most recent call last): File "C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py", line 13, in <module> d.eat("bao zi") TypeError: eat() missing 1 required positional argument: 'food' class Dog(object): def __init__(self,name): self.name=name @property #这个的意思是底下的函数和类没什么关系 def eat(self): print("%s is eating %s" % (self.name,"馒头")) def talk(self): print("%s is talking" % self.name) d=Dog("bob") d.eat="bao zi" Traceback (most recent call last): File "C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py", line 13, in <module> d.eat="bao zi" AttributeError: can't set attribute 正确的写法: class Dog(object): def __init__(self,name): self.name=name @property #这个的意思是底下的函数和类没什么关系 def eat(self): print("%s is eating %s" % (self.name,"馒头")) @eat.setter def eat(self,food): print("set to food:",food) def talk(self): print("%s is talking" % self.name) d=Dog("bob") d.eat="bao zi" C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py set to food bao zi 错误: class Dog(object): def __init__(self,name): self.name=name @property #这个的意思是底下的函数和类没什么关系 def eat(self): print("%s is eating %s" % (self.name,"馒头")) @eat.setter def eat(self,food): print("set to food:",food) def talk(self): print("%s is talking" % self.name) d=Dog("bob") d.eat d.eat="bao zi" d.eat C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py bob is eating 馒头 set to food: bao zi bob is eating 馒头 正确:把一个方法变成一个属性;隐藏过程,给用户直接的结果 class Dog(object): def __init__(self,name): self.name=name self.food=None @property def eat(self): print("%s is eating %s" % (self.name,self.food)) @eat.setter def eat(self,food): self.food=food print("set to food:",food) #self.food=food def talk(self): print("%s is talking" % self.name) d=Dog("bob") d.eat d.eat="bao zi" d.eat C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py bob is eating None set to food: bao zi bob is eating bao zi 删除属性: class Dog(object): def __init__(self,name): self.name=name self.food=None @property def eat(self): print("%s is eating %s" % (self.name,self.food)) @eat.setter def eat(self,food): self.food=food print("set to food:",food) #self.food=food def talk(self): print("%s is talking" % self.name) d=Dog("bob") del d.name print(d.name) d.eat C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py Traceback (most recent call last): File "C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py", line 21, in <module> print(d.name) AttributeError: 'Dog' object has no attribute 'name' 删除属性方法: class Dog(object): def __init__(self,name): self.name=name self.food=None @property def eat(self): print("%s is eating %s" % (self.name,self.food)) @eat.setter def eat(self,food): self.food=food print("set to food:",food) #self.food=food @eat.deleter def eat(self): del self.food print("删除完毕") def talk(self): print("%s is talking" % self.name) d=Dog("bob") d.eat="bao zi" del d.eat d.eat C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py Traceback (most recent call last): File "C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py", line 25, in <module> d.eat File "C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py", line 8, in eat print("%s is eating %s" % (self.name,self.food)) AttributeError: 'Dog' object has no attribute 'food' set to food: bao zi 删除完毕 属性方法的实用实例 class Flight(object): def __init__(self,name): self.flight_name = name def checking_status(self): print("checking flight %s status " % self.flight_name) return 1 @property def flight_status(self): status = self.checking_status() if status == 0 : print("flight got canceled...") elif status == 1 : print("flight is arrived...") elif status == 2: print("flight has departured already...") else: print("cannot confirm the flight status...,please check later") f = Flight("CA980") f.flight_status C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py checking flight CA980 status flight is arrived... class Flight(object): def __init__(self,name): self.flight_name = name def checking_status(self): print("checking flight %s status " % self.flight_name) return 1 @property def flight_status(self): status = self.checking_status() if status == 0 : print("flight got canceled...") elif status == 1 : print("flight is arrived...") elif status == 2: print("flight has departured already...") else: print("cannot confirm the flight status...,please check later") @flight_status.setter def flight_status(self,status): print("the %s status is %s" % (self.flight_name,status)) f = Flight("CA980") f.flight_status=2 f.flight_status C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py the CA980 status is 2 checking flight CA980 status flight is arrived... 第七周 第五章 深入讲解类的特殊成员方法 属于高级方法 不用也可以 第七周 第七章 反射 hasatrr(obj,name_str) : 判断一个对象里是否有对应的字符串的方法。 gerattr(obj,name_str) :根据字符串去获取obj对象里的方法的内存地址 setattr(obj,'y',z), 设置属性 delattr(obj,'y',z) 删除属性 class Dog(object): def __init__(self,name): self.name=name def eat(self,food): print("%s is eating %s" % (self.name,food)) d=Dog("bob") choice=input(">>:").strip() if hasattr(d,choice): func=getattr(d,choice) func("food") C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py >>:eat bob is eating food def bulk(self): print("%s is yelling" % self.name) class Dog(object): def __init__(self,name): self.name=name def eat(self,food): print("%s is eating %s" % (self.name,food)) d=Dog("bob") choice=input(">>:").strip() if hasattr(d,choice): func=getattr(d,choice) func("food") else: setattr(d,choice,bulk) d.talk(d) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py >>:talk bob is yelling 动态把字符串转换成属性 def bulk(self): print("%s is yelling" % self.name) class Dog(object): def __init__(self,name): self.name=name def eat(self,food): print("%s is eating %s" % (self.name,food)) d=Dog("bob") choice=input(">>:").strip() if hasattr(d,choice): func=getattr(d,choice) func("food") else: setattr(d,choice,22) print(getattr(d,choice)) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py >>:age 22 调已有的变量会报错 def bulk(self): print("%s is yelling" % self.name) class Dog(object): def __init__(self,name): self.name=name def eat(self,food): print("%s is eating %s" % (self.name,food)) d=Dog("bob") choice=input(">>:").strip() if hasattr(d,choice): func=getattr(d,choice) func("food") else: setattr(d,choice,22) print(getattr(d,choice)) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py >>:name Traceback (most recent call last): File "C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py", line 16, in <module> func("food") TypeError: 'str' object is not callable 如果不存在,新建一个属性 def bulk(self): print("%s is yelling" % self.name) class Dog(object): def __init__(self,name): self.name=name def eat(self,food): print("%s is eating %s" % (self.name,food)) d=Dog("bob") choice=input(">>:").strip() if hasattr(d,choice): attr=getattr(d,choice) print(attr) else: setattr(d,choice,22) print(getattr(d,choice)) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py >>:name bob 如果存在属性,进行修改。 def bulk(self): print("%s is yelling" % self.name) class Dog(object): def __init__(self,name,age): self.name=name #self.age=age def eat(self,food): print("%s is eating %s" % (self.name,food)) d=Dog("bob",24) choice=input(">>:").strip() if hasattr(d,choice): setattr(d,choice,"jack") print(getattr(d,choice)) else: setattr(d,choice,22) print(getattr(d,choice)) #print(d.name) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py >>:name jack 如果存在属性 进行删除 def bulk(self): print("%s is yelling" % self.name) class Dog(object): def __init__(self,name,age): self.name=name #self.age=age def eat(self,food): print("%s is eating %s" % (self.name,food)) d=Dog("bob",24) choice=input(">>:").strip() if hasattr(d,choice): delattr(d,choice) else: setattr(d,choice,22) print(getattr(d,choice)) print(d.name) Traceback (most recent call last): File "C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py", line 22, in <module> print(d.name) AttributeError: 'Dog' object has no attribute 'name' 第七周 第九章 异常处理 data={} try: data["name"] except KeyError as e: print("没有这个key",e) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py 没有这个key 'name' name=["bob","cat"] data={} #name[3] try: name[3] data["hot"] except KeyError as e: print("没有这个key",e) except IndexError as e: print("列表超出范围",e) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py 列表超出范围 list index out of range 抓所有 不要用 name=["bob","cat"] data={} #name[3] try: name[3] data["hot"] name[778] except Exception as e: print("出错",e) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py 出错 list index out of range name=["bob","cat"] data={} #name[3] try: #name[3] #data["hot"] open("texe") except IndexError as e: print("出错",e) except KeyError as e: print("列表超出范围",e) except Exception as e: print("未知出错",e) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py 未知出错 [Errno 2] No such file or directory: 'texe' name=["bob","cat"] data={} #name[3] try: #name[3] #data["hot"] #open("texe") a=3 print(a) except IndexError as e: print("出错",e) except KeyError as e: print("列表超出范围",e) except Exception as e: print("未知出错",e) else: print("一切正常") C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py 3 一切正常 name=["bob","cat"] data={} #name[3] try: #name[3] #data["hot"] #open("texe") a=3 print(a) except IndexError as e: print("出错",e) except KeyError as e: print("列表超出范围",e) except Exception as e: print("未知出错",e) else: print("一切正常") finally: print("不管有错没错都执行") C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py 3 一切正常 不管有错没错都执行 name=["bob","cat"] data={} #name[3] try: #name[3] data["hot"] #open("texe") #a=3 #print(a) except IndexError as e: print("出错",e) except KeyError as e: print("列表超出范围",e) except Exception as e: print("未知出错",e) else: print("一切正常") finally: print("不管有错没错都执行") C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py 列表超出范围 'hot' 不管有错没错都执行 自定义异常处理: class AlexException(Exception): def __init__(self,msg): self.message=msg def __str__(self): return self.message try: raise AlexException("数据库连不上") except AlexException as e: print(e) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py 数据库连不上 class AlexException(Exception): def __init__(self,msg): self.message=msg def __str__(self): return "lklj" try: raise AlexException("数据库连不上") except AlexException as e: print(e) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py lklj 定义的IndexError 不能和自带的异常冲突,下面的定义错误 class IndexError(Exception): def __init__(self,msg): self.message=msg def __str__(self): return "lklj" try: name=[] name[3] raise IndexError("数据库连不上") except IndexError as e: print(e) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py Traceback (most recent call last): File "C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py", line 8, in <module> name[3] IndexError: list index out of range try: name=[] name[3] #raise IndexError("数据库连不上") except IndexError as e: print(e) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py list index out of range 第七周 第10章 网络编程 socket 意思:发数据 接受数据 第七周 第11章 网络编程 socket 第七周 第12章 网络编程 socket案例 消息发送与接受 server 端 import socket server =socket.socket() server.bind(("localhost",6800)) server.listen(600) print("我要开始接听电话") conn,addr=server.accept() print("电话来了") data=conn.recv(1024) print("receive:",data) conn.send(data.upper()) server.close() C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py 我要开始接听电话 客户端 import socket client=socket.socket() client.connect(("localhost",6800)) client.send(b"hello") data=client.recv(1024) print("receive:",data) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/file3/clients.py receive: b'HELLO' 第七周 第十三章节 服务端 import socket server =socket.socket() server.bind(('localhost',6600)) server.listen(1) #最大多少个连接,就是可以打开几个窗口 print("我要开始接听电话") conn,addr=server.accept() print(conn,addr) print("电话来了") data=conn.recv(1024) print("receive:",data) conn.send(data.upper()) server.close() C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py 我要开始接听电话 <socket.socket fd=292, family=AddressFamily.AF_INET, type=SocketType.SOCK_STREAM, proto=0, laddr=('127.0.0.1', 6600), raddr=('127.0.0.1', 58933)> ('127.0.0.1', 58933) 电话来了 receive: b'\xe6\x88\x91\xe8\xa6\x81\xe4\xb8\x8b\xe8\xbd\xbd\xe7\x94\xb5\xe5\xbd\xb1high' 客户端: import socket client=socket.socket() client.connect(("localhost",6600)) client.send("我要下载电影high".encode('utf-8')) data=client.recv(1024) print("receive:",data.decode()) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/file3/clients.py receive: 我要下载电影HIGH 同时跟一个人往复说话 服务端 import socket server =socket.socket() server.bind(('localhost',6600)) server.listen(1) print("我要开始接听电话") conn,addr=server.accept() #等电话打过来 print(conn,addr) print("电话来了") while True: data=conn.recv(1024) print("receive:",data) conn.send(data.upper()) server.close() C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/file3/file3.py 我要开始接听电话 <socket.socket fd=292, family=AddressFamily.AF_INET, type=SocketType.SOCK_STREAM, proto=0, laddr=('127.0.0.1', 6600), raddr=('127.0.0.1', 60899)> ('127.0.0.1', 60899) 电话来了 receive: b'j' receive: b'yh' 客户端 import socket client=socket.socket() client.connect(("localhost",6600)) while True: inputing=input("please input:") client.send(inputing.encode('utf-8')) data=client.recv(1024) print("receive:",data.decode()) C:\Python34\python.exe C:/Users/Administrator/PycharmProjects/untitled25/file3/clients.py please input:j receive: J please input:yh receive: YH please input: 挂起连接: 一个clients断开后,就马上和另一个clilents会话 注意:在linux中操作。 服务端 import socket server =socket.socket() server.bind(('localhost',6600)) server.listen(1) print("我要开始接听电话") while True: conn,addr=server.accept() #等电话打过来 print(conn,addr) print("电话来了") while True: data=conn.recv(1024) print("receive:",data) if not data: print("clients has closed") conn.send(data.upper()) server.close() 客户端 import socket client=socket.socket() client.connect(("localhost",6600)) while True: msg=input("please input:") if len(msg) == 0:continue client.send(msg.encode('utf-8')) data=client.recv(1024) print("receive:",data.decode()) 传递Linuc命令:linux上操作 服务端 import socket import os server =socket.socket() server.bind(('localhost',6600)) server.listen(1) #最大多少个连接,就是可以打开几个窗口 print("我要开始接听电话") while True: conn,addr=server.accept() #等电话打过来 print(conn,addr) print("电话来了") while True: data=conn.recv(1024) print(data) if not data: print("clients has closed") res=os.popen(data).read() conn.send(res) server.close() 客户端: import socket client=socket.socket() client.connect(("localhost",6600)) while True: msg=input("please input:") if len(msg) == 0:continue client.send(msg.encode('utf-8')) data=client.recv(1024000) print("receive:",data.decode()) 第八周 第四节 socket实现简单ssh的服务 服务端: import socket import os server =socket.socket() server.bind(('localhost',6600)) server.listen(1) #最大多少个连接,就是可以打开几个窗口 print("等待命令输入:") while True: conn,addr=server.accept() #等电话打过来 print(addr) while True: print("等待新指令") data=conn.recv(1024) if not data: print("clients has closed") break print("执行命令:",data) cmd_res=os.popen(data.decode()).read() #接受字符串 执行结果也是字符串 print("before send",len(cmd_res)) if len(cmd_res)==0: cmd_res="cmd has not output" conn.send(str(len(cmd_res.encode())).encode("utf-8")) conn.send(cmd_res.encode("utf-8")) print("sent done") server.close() 客户端: import socket client=socket.socket() client.connect(("localhost",6600)) while True: cmd=input("please input:") if len(cmd) == 0:continue client.send(cmd.encode('utf-8')) cmd_res_seize=client.recv(1024) #接受命令结果的长度 print("命令结果大小",cmd_res_seize) received_size=0 while received_size < int(cmd_res_seize.decode()): #receieced_seze=0 data=client.recv(1024) received_size +=len(data) print(data.decode()) else: print("received done",received_size) #cmd_res=client.recv(1024) #print(cmd_res.decode()) client.close() 第八周 第六节 命令分开-黏包 服务端: import socket import os server =socket.socket() server.bind(('localhost',6600)) server.listen(1) #最大多少个连接,就是可以打开几个窗口 print("等待命令输入:") while True: conn,addr=server.accept() #等电话打过来 print(addr) while True: print("等待新指令") data=conn.recv(1024) if not data: print("clients has closed") break print("执行命令:",data) cmd_res=os.popen(data.decode()).read() #接受字符串 执行结果也是字符串 print("before send",len(cmd_res)) if len(cmd_res)==0: cmd_res="cmd has not output" conn.send(str(len(cmd_res.encode())).encode("utf-8")) client_ack=conn.recv(1024) conn.send(cmd_res.encode("utf-8")) print("sent done") server.close() 客户端: import socket client=socket.socket() client.connect(("localhost",6600)) while True: cmd=input("please input:") if len(cmd) == 0:continue client.send(cmd.encode('utf-8')) cmd_res_seize=client.recv(1024) #接受命令结果的长度 print("命令结果大小",cmd_res_seize) client.send("准备好接受".encode("utf-8")) received_size=0 while received_size < int(cmd_res_seize.decode()): #receieced_seze=0 data=client.recv(1024) received_size +=len(data) print(data.decode()) else: print("received done",received_size) #cmd_res=client.recv(1024) #print(cmd_res.decode()) client.close() 第十周 第十五章节 Select 解析socket 通讯2 socket 服务端: import select import socket import queue server=socket.socket() server.bind(('localhost',6700)) server.listen(900) server.setblocking(False) inputs=[server,] #inputs=[server,conn,conn1,conn2] outputs=[] while True: readable,writeable,exceptional=select.select(inputs,outputs,inputs) print(readable,writeable,exceptional) for r in readable: if r is server: conn,addr=server.accept() inputs.append(conn) print("来了新连接",addr) else: data=r.recv(1024) print("收到数据",data) r.send(data) print("sent done") socket 客户端1: import socket HOST='localhost' PORT=6700 s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.connect((HOST,PORT)) while True: msg=bytes(input("please input:"),encoding="utf-8") s.send(msg) #data=s.recv(1024) #print("receive",data) s.close() socket 客户端2: import socket HOST='localhost' PORT=6700 s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.connect((HOST,PORT)) while True: msg=bytes(input("please input:"),encoding="utf-8") s.send(msg) data=s.recv(1024) 第9周 第五章: 进程与线程 进程 Python多进程multiprocessing使用示例 http://outofmemory.cn/code-snippet/2267/Python-duojincheng-multiprocessing-usage-example mutilprocess简介 像线程一样管理进程,这个是mutilprocess的核心,他与threading很是相像,对多核CPU的利用率会比threading好的多。 简单的创建进程 import multiprocessing def worker(num): """thread worker function""" print ('Worker:', num) return if __name__ == '__main__': jobs = [] for i in range(5): p = multiprocessing.Process(target=worker, args=(i,)) #i 就相当于传递了参数,和其他的函数不一样, jobs.append(p) p.start() E:\python\python.exe E:/django工程/第20章/app01/cehi3.py Worker: 0 Worker: 3 Worker: 2 Worker: 1 Worker: 4 线程: Python3入门之线程实例常用方法及属性设置 https://www.cnblogs.com/chengd/articles/7766735.html 什么是线程 线程是CPU分配资源的基本单位。但一个程序开始运行,这个程序就变成了一个进程,而一个进程相当于一个或者多个线程。当没有多线程编程时,一个进程也是一个主线程,但有多线程编程时,一个进程包含多个线程,包括主线程。使用线程可以实现程序的并发。 python3中线程模块 python3对多线程支持的是 threading 模块,应用这个模块可以创建多线程程序,并且在多线程间进行同步和通信。在python3 中,可以通过两种方法来创建线程(下面列子将以直接在线程中运行函数为主): 1.用 threading.Thread 直接在线程中运行函数 import time import threading def thread_run(name): print("%s's first thread!!!"% name) time.sleep(5) mike = threading.Thread(target=thread_run, args=('Mike', )) jone = threading.Thread(target=thread_run, args=('jone', )) mike.start() jone.start() E:\python\python.exe E:/django工程/第20章/app01/cehi3.py Mike's first thread!!! jone's first thread!!! 单线程: 好些年前的MS-DOS时代,操作系统处理问题都是单任务的,我想做听音乐和看电影两件事儿,那么一定要先排一下顺序。 (好吧!我们不纠结在DOS时代是否有听音乐和看影的应用。^_^) https://www.cnblogs.com/fnng/p/3670789.html from time import ctime,sleep def music(): for i in range(2): print ("I was listening to music. %s" %ctime()) sleep(1) def move(): for i in range(2): print ("I was at the movies! %s" %ctime()) sleep(5) if __name__ == '__main__': music() move() print ("all over %s" %ctime()) E:\python\python.exe E:/django工程/第20章/app01/cehi56.py I was listening to music. Sun May 6 10:29:29 2018 I was listening to music. Sun May 6 10:29:30 2018 I was at the movies! Sun May 6 10:29:31 2018 I was at the movies! Sun May 6 10:29:36 2018 all over Sun May 6 10:29:41 2018 我们先听了一首音乐,通过for循环来控制音乐的播放了两次,每首音乐播放需要1秒钟,sleep()来控制音乐播放的时长。接着我们又看了一场电影, 每一场电影需要5秒钟,因为太好看了,所以我也通过for循环看两遍。在整个休闲娱乐活动结束后,我通过 print "all over %s" %ctime() 看了一下当前时间,差不多该睡觉了。 其实,music()和move()更应该被看作是音乐和视频播放器,至于要播放什么歌曲和视频应该由我们使用时决定。所以,我们对上面代码做了改造: #coding=utf-8 import threading from time import ctime,sleep def music(func): for i in range(2): print ("I was listening to %s. %s" %(func,ctime())) sleep(1) def move(func): for i in range(2): print ("I was at the %s! %s" %(func,ctime())) sleep(5) if __name__ == '__main__': music(u'爱情买卖') move(u'阿凡达') print ("all over %s" %ctime()) E:\python\python.exe E:/django工程/第20章/app01/cehi56.py I was listening to 爱情买卖. Sun May 6 10:38:18 2018 I was listening to 爱情买卖. Sun May 6 10:38:19 2018 I was at the 阿凡达! Sun May 6 10:38:20 2018 I was at the 阿凡达! Sun May 6 10:38:25 2018 all over Sun May 6 10:38:30 2018 对music()和move()进行了传参处理。体验中国经典歌曲和欧美大片文化。 多线程 科技在发展,时代在进步,我们的CPU也越来越快,CPU抱怨,P大点事儿占了我一定的时间,其实我同时干多个活都没问题的;于是,操作系统就进入了多任务时代。我们听着音乐吃着火锅的不在是梦想。 python提供了两个模块来实现多线程thread 和threading ,thread 有一些缺点,在threading 得到了弥补,为了不浪费你和时间,所以我们直接学习threading 就可以了。 继续对上面的例子进行改造,引入threadring来同时播放音乐和视频: #coding=utf-8 import threading from time import ctime,sleep def music(func): for i in range(2): print ("I was listening to %s. %s" %(func,ctime())) sleep(1) def move(func): for i in range(2): print ("I was at the %s! %s" %(func,ctime())) sleep(5) threads = [] t1 = threading.Thread(target=music,args=(u'爱情买卖',)) threads.append(t1) t2 = threading.Thread(target=move,args=(u'阿凡达',)) threads.append(t2) if __name__ == '__main__': for t in threads: t.setDaemon(True) t.start() print ("all over %s" %ctime()) 运行结果: E:\python\python.exe E:/django工程/第20章/app01/cehi56.py I was listening to 爱情买卖. Sun May 6 11:13:42 2018 I was at the 阿凡达! Sun May 6 11:13:42 2018all over Sun May 6 11:13:42 2018 Process finished with exit code 0 import threading 首先导入threading 模块,这是使用多线程的前提。 threads = [] t1 = threading.Thread(target=music,args=(u'爱情买卖',)) threads.append(t1) 创建了threads数组,创建线程t1,使用threading.Thread()方法,在这个方法中调用music方法target=music,args方法对music进行传参。 把创建好的线程t1装到threads数组中。 接着以同样的方式创建线程t2,并把t2也装到threads数组。 for t in threads: t.setDaemon(True) t.start() 最后通过for循环遍历数组。(数组被装载了t1和t2两个线程) setDaemon() setDaemon(True)将线程声明为守护线程,必须在start() 方法调用之前设置,如果不设置为守护线程程序会被无限挂起。子线程启动后,父线程也继续执行下去,当父线程执行完最后一条语句print "all over %s" %ctime()后,没有等待子线程,直接就退出了,同时子线程也一同结束。 start() 开始线程活动。 从执行结果来看,子线程(muisc 、move )和主线程(print "all over %s" %ctime())都是同一时间启动,但由于主线程执行完结束,所以导致子线程也终止。 继续调整程序: #coding=utf-8 import threading from time import ctime,sleep def music(func): for i in range(2): print ("I was listening to %s. %s" %(func,ctime())) sleep(1) def move(func): for i in range(2): print ("I was at the %s! %s" %(func,ctime())) sleep(5) threads = [] t1 = threading.Thread(target=music,args=(u'爱情买卖',)) threads.append(t1) t2 = threading.Thread(target=move,args=(u'阿凡达',)) threads.append(t2) if __name__ == '__main__': for t in threads: t.setDaemon(True) t.start() t.join() print ("all over %s" %ctime()) 运行结果: I was listening to 爱情买卖. Sun May 6 11:26:12 2018 I was at the 阿凡达! Sun May 6 11:26:12 2018 I was listening to 爱情买卖. Sun May 6 11:26:13 2018 I was at the 阿凡达! Sun May 6 11:26:17 2018 all over Sun May 6 11:26:22 2018 Process finished with exit code 0 我们只对上面的程序加了个join()方法,用于等待线程终止。join()的作用是,在子线程完成运行之前,这个子线程的父线程将一直被阻塞。 注意: join()方法的位置是在for循环外的,也就是说必须等待for循环里的两个进程都结束后,才去执行主进程。 从执行结果可看到,music 和move 是同时启动的。 开始时间4分11秒,直到调用主进程为4分22秒,总耗时为10秒。从单线程时减少了2秒,我们可以把music的sleep()的时间调整为4秒。 #coding=utf-8 import threading from time import ctime,sleep def music(func): for i in range(2): print ("I was listening to %s. %s" %(func,ctime())) sleep(4) def move(func): for i in range(2): print ("I was at the %s! %s" %(func,ctime())) sleep(5) threads = [] t1 = threading.Thread(target=music,args=(u'爱情买卖',)) threads.append(t1) t2 = threading.Thread(target=move,args=(u'阿凡达',)) threads.append(t2) if __name__ == '__main__': for t in threads: t.setDaemon(True) t.start() t.join() print ("all over %s" %ctime()) 运行结果: I was listening to 爱情买卖. Sun May 6 11:24:44 2018 I was at the 阿凡达! Sun May 6 11:24:44 2018 I was listening to 爱情买卖. Sun May 6 11:24:48 2018 I was at the 阿凡达! Sun May 6 11:24:49 2018 all over Sun May 6 11:24:54 2018 子线程启动11分27秒,主线程运行11分37秒。 虽然music每首歌曲从1秒延长到了4 ,但通多程线的方式运行脚本,总的时间没变化。 第十周 第十六章节:Select 解析socket 通信3 socket 服务端: import select import socket import queue server=socket.socket() server.bind(('localhost',6700)) server.listen(900) server.setblocking(False) msg_dic = {} inputs=[server,] #inputs=[server,conn,conn1,conn2] outputs=[] while True: readable,writeable,exceptional=select.select(inputs,outputs,inputs) print(readable,writeable,exceptional) for r in readable: if r is server: conn,addr=server.accept() inputs.append(conn) print("来了新连接",addr) msg_dic[conn]=queue.Queue() #初始化一个队列 else: data=r.recv(1024) print("收到数据",data) msg_dic[r].put(data) #放入返回的连接队列 outputs.append(r) for w in writeable: #要返回给客户的连接列表 data_to_clients=msg_dic[w].get() w.send(data_to_clients) #返回个客户源数据 outputs.remove(w) for e in exceptional: if e in outputs: outputs.remove(e) else: inputs.remove(e) del msg_dic[e] socket 客户端: import socket HOST='localhost' PORT=6700 s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.connect((HOST,PORT)) while True: msg=bytes(input("please input:"),encoding="utf-8") s.sendall(msg) data=s.recv(1024) print("receive:",data) s.close() 第十一周 第三章 RabbitMQ基本操作 生产者: import pika connection = pika.BlockingConnection(pika.ConnectionParameters(host='127.0.0.1')) channel = connection.channel() channel.queue_declare(queue='hello') channel.basic_publish(exchange='', routing_key='hello', body='hello word') print("[x]sent hello word") connection.close() 消费者: import pika connection=pika.BlockingConnection(pika.ConnectionParameters('localhost')) channel=connection.channel() channel.queue_declare(queue='hello') def callback(ch,method,propreties,body): print("-->",ch,method,propreties) print("[x] recieved %r" % body) channel.basic_consume(callback,queue='hello',no_ack=True) print('[*] watting fir messages, To exit press CTRL+C') channel.start_consuming() 第十四周 第七章: html的内部标签 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <!--<div></div>--> <a href="http://oldboyedu.com">老男孩</a> </body> </html> 第十四周 第八章 html的body内部标签 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <!--<div></div>--> <p>klkklkkllkkkkkkk<br />kkkkkkkkkkkkkkklklk</p> <p>555555555</p> <p>8888888888</p> <h1>8888</h1> <h2>8888</h2> <h3>8888</h3> <h4>8888</h4> <h5>8888</h5> <h6>8888</h6> <span>66666</span> <span>66666</span> <span>66666</span> <a href="http://oldboyedu.com">老男孩 <a>公园</a> </body> </html> 第十四周 第八章 chrome 查看html的基本样式 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>hello</title> </head> <body> come on <div> <div id="i1">hello</div> </div> <a href="http://oldboyedu.com">自然 <a>公园</a> </body> </html> 第十四周 第十章 html的body内标签input系列 服务端: import tornado.ioloop import tornado.web import tornado.ioloop import tornado.web class MainHandler(tornado.web.RequestHandler): def get(self): print(111) u=self.get_argument('user') e=self.get_argument("email") p=self.get_argument("pwd") if u == 'bob' and e == 'bob@123.com' and p == '123': self.write('ok') else: self.write('输入错误') self.write("GET") def post(self,*args,**kwargs): print(222) self.write("POST") application = tornado.web.Application([ (r"/index", MainHandler), ]) if __name__ == "__main__": application.listen(8888) tornado.ioloop.IOLoop.instance().start() 客户端: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="http://localhost:8888/index" method="post"> <input type="text" name="user" /> <input type="text" name="email" /> <input type="password" name="pwd"/> <input type="button" value="登陆1" /> <input type="submit" value="登陆2" /> <!--{'user':'用户输入的用户','email':'xx','pwd':'xx'}--> </form> <br> <form> <input type="text" /> <input type="password" /> <input type="button" value="登陆" /> <input type="submit" value="登陆" /> </form> </body> </html> 第十四周 第十一章 html的body内标签input系列 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form enctype="multipart/form-data"> <div> <p>请选择性别:</p> 男:<input type="radio" name="gender" value="1"/> 女:<input type="radio" name="gender" value="2"/> <p>爱好:</p> 篮球:<input type="checkbox" name="favor" value="1" checked="checked"/> 足球:<input type="checkbox" name="favor" value="2"/> 拍球:<input type="checkbox" name="favor" value="3" /> 棒球:<input type="checkbox" name="favor" value="4"/> <p>技能</p> 唱歌:<input type="checkbox" name="skill"/> 跳舞:<input type="checkbox" name="skill"/> <p>上传文件</p> <input type="file" name="fname"/> <br> <!--<span>rttttttt</span>--> </div> <input type="submit" value="提交" /> <input type="reset" value="重置" /> </form> </body> </html> 第十四周 第十二章 html的body内标签多行文本以及下拉框 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form enctype="multipart/form-data"> <select name="city" size="10" multiple="multiple"> <option value="1">北京</option> <option value="2">上海</option> <option value="3" selected="selected">广州</option> </select> <div> <p>请选择性别:</p> 男:<input type="radio" name="gender" value="1"/> 女:<input type="radio" name="gender" value="2"/> <p>爱好:</p> 篮球:<input type="checkbox" name="favor" value="1" checked="checked"/> 足球:<input type="checkbox" name="favor" value="2"/> 拍球:<input type="checkbox" name="favor" value="3" /> 棒球:<input type="checkbox" name="favor" value="4"/> <p>技能</p> 唱歌:<input type="checkbox" name="skill"/> 跳舞:<input type="checkbox" name="skill"/> <p>上传文件</p> <input type="file" name="fname"/> <br> <!--<span>rttttttt</span>--> </div> <textarea name="menber">hhhh</textarea> <input type="submit" value="提交" /> <input type="reset" value="重置" /> </form> </body> </html> 第十四周 第十三章 html的body内标签超链接 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <a href="#i1">第一章</a> <a href="#i2">第二章</a> <a href="#i3">第三章</a> <a href="#i4">第四章</a> <div id="i1" style="height:600px">第一章的内容</div> <div id="i2" style="height:600px">第二章的内容</div> <div id="i3" style="height:600px">第三章的内容</div> <div id="i4" style="height:600px" >第四章的内容</div> </body> </html> 第十四周 第十四章 html的body内标图片及表格 标准格式按照十五章 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <a href="http://www.baidu.com"> <img src="0.jpg" title="美女" style="height: 200px; width: 200px;" alt="美女"> </a> <ul> <li>yyyy</li> <li>yyyy</li> <li>yyyy</li> <li>yyyy</li> </ul> <ol> <li>xxx</li> <li>xxx</li> <li>xxx</li> <li>xxx</li> </ol> <dl> <dt>kkk</dt> <dd>uuu</dd> <dd>uuu</dd> <dd>uuu</dd> <dd>uuu</dd> <dt>kkk</dt> <dd>uuu</dd> <dd>uuu</dd> <dd>uuu</dd> <dd>uuu</dd> </dl> </body> </html> 表格: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <table border="1"> <tr> <td>主机名</td> <td>端口</td> <td>操作</td> </tr> <tr> <td>0.0.0.0</td> <td>8080</td> <td> <a href="https://www.baidu.com">查看信息</a> <a href="https://www.baidu.com">修改</a> </td> </tr> <tr> <td>0.0.0.0</td> <td>8080</td> <td>第二行,第3列</td> </tr> </table> </body> </html> 第十四周 第十五章 html的body内标图片及表格 标准格式按照这个 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <table border="1"> <thead> <tr> <th>表头1</th> <th>表头1</th> <th>表头1</th> <th>表头1</th> </tr> </thead> <tbody> <tr> <th>1</th> <th colspan="2">1</th> <th>1</th> <!--<th>1</th>--> </tr> <tr> <th rowspan="2">1</th> <th>1</th> <th>1</th> <th>1</th> </tr> <tr> <th>1</th> <th>1</th> <th>1</th> <!--<th>1</th>--> </tr> <tr> <th>1</th> <th>1</th> <th>1</th> <th>1</th> </tr> <tr> <th>1</th> <th>1</th> <th>1</th> <th>1</th> </tr> </tbody> </table> </body> </html> 第十四周 第十六章 html的body的fildest标签和lable标签 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <label for="username">用户名:</label> <input id="username" type="text" name="user"/> </body> </html> 底下情况基本不用 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <fieldset> <legend>登录</legend> <label for="username">用户名:</label> <input id="username" type="text" name="user"/> <br> <label for="pwd">密码: </label> <input id="pwd" type="text" name="user"/> </fieldset> </body> </html> 第十四周 第十八章 css选择器: id选择器:不常用 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> #i1{ background-color: brown; height: 58px } #i2{ background-color: #32CD32; height: 58px } #i3{ background-color: #27408B; height: 58px } </style> </head> <div id="i1">fff</div> <div id="i2">2</div> <div id="i3" >2</div> <body> </body> </html> class选择器:最常用的方式: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> #i1{ background-color: brown; height: 58px } #i2{ background-color: #32CD32; height: 58px } #i3{ background-color: #27408B; height: 58px } .c1{ background-color: #B8860B; height: 20px; } </style> </head> <div class="c1">fff</div> <div class="c1">2</div> <div class="c1" >2</div> <body> </body> </html> 标签选择器: 注释:/*background-color: brown;*/ <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> div{ background-color: #B8860B; color: red; } </style> </head> <div class="c1">fff</div> <span class="c1">2 <div>hhhhh</div> </span> <div class="c1" >2</div> <body> </body> </html> 层级选择器: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .c1 div{ background-color: #B8860B; color: red; } </style> </head> <div class="c1">fff</div> <span class="c1">2 <div id="c2">hhhhh</div> </span> <div class="c1" >2</div> <body> </body> </html> 组合选择器: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> #i1,#i2,#i3{ background-color: #B8860B; color: red; } </style> </head> <body> <div id="i1">fff</div> <div id="i2">hhhhh</div> <div id="i3" >2</div> </body> </html> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .i1,.i2,.i3{ background-color: #B8860B; color: red; } </style> </head> <body> <div class="i1">fff</div> <div class="i2">hhhhh</div> <div class="i3" >2</div> </body> </html> 属性选择器: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> input[type="text"]{background-color: #B8860B; color: red;} </style> </head> <body> <input type="text"/> <input type="password"/> </body> </html> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .c1[name="job"]{background-color: #B8860B;width: 80px;height: 100px; color: red;} </style> </head> <body> <input class="c1" type="text" name="job"/> <input type="password"/> </body> </html> 第十四周 第十九章 css存在样式、优先级 叠加 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .c1{background-color:yellow; color: yellow;} .c1{font-size: 60px; } </style> </head> <body> <div class="c1 c2">hhhhhhh</div> </body> </html> 优先级: style 最优先 然后最下面的 然后最上面的 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .c1{background-color:yellow; color: yellow;} .c1{font-size: 60px; color: black; } </style> </head> <body> <div class="c1 c2" style="color: deeppink">hhhhhhh</div> </body> </html> css样式也可以写在单独文件中: 1.1 先写个 css文件: .c1 { background-color: yellow; color: yellow; } .c1 { font-size: 60px; color: black; } 1.2 再导入: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="daoru.css" /> </head> <body> <div class="c1 c2" style="color: deeppink">hhhhhhh</div> <div class="c1 c2" style="color: deeppink">hhhhhhh</div> <div class="c1 c2" style="color: deeppink">hhhhhhh</div> </body> </html> 第十四周 第二十章:css边框以及其他常用样式: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div style="border: 1px solid red"> hhhhhh </div> <div style="height: 50px;width: 50%;border: 1px solid red;font-size: 18px;text-align: center;line-height: 50px;font-weight: bolder"> kkkkkk </div> </body> </html> 第十四周 第二十一章节:css的float样式 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .pg-header{ height: 50px; background-color: aqua; line-height: 50px; } </style> </head> <body style="margin: 0 auto"> <div class="pg-header"> <div style="float: left">收藏本站</div> <div style="float: right"> <a>登录</a> <a>注册</a> </div> </div> <br> <div style="width: 300px;border:1px solid red;"> <div style="width: 96px;height: 30px;border:1px solid green;float: left"></div> <div style="width: 96px;height: 30px;border:1px solid green;float: left"></div> <div style="width: 96px;height: 30px;border:1px solid green;float: left"></div> <div style="width: 96px;height: 30px;border:1px solid green;float: left"></div> <div style="width: 96px;height: 30px;border:1px solid green;float: left"></div> <div style="width: 96px;height: 30px;border:1px solid green;float: left"></div> <div style="width: 96px;height: 30px;border:1px solid green;float: left"></div> <div style="clear: both"></div> </div> </body> </html> 第十五周 第三章 css内容 position <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div onclick="GoTop();" style="height: 50px;width: 50px;background-color: red;color: black;position: fixed; bottom: 20px; right: 20px; ">返回顶部 </div> <div style="height:5000px;background-color: green"></div> <script> function GoTop() { document.body.scrollTop = 0; } </script> </body> </html> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .pg-header{ height: 50px; background-color: red; color: aqua; position: fixed; top: 0; left: 0; right: 0; } </style> <style> .pg-body{ height: 5000px; background-color: green; color: blue; margin-top: 50px; } </style> </head> <body> <div class="pg-header">头部</div> <div class="pg-body">内容</div> </body> </html> 第十五周 第四章 css内容 position <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div style="width: 50px;height: 50px;background-color: black;position: absolute;right: 0;bottom: 0"> kkkkk </div> <div style="height: 5000px;background-color: aqua"> hhhh </div> </body> </html> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div style="position: relative;width: 300px;height: 100px;border: 1px solid red;margin: 0 auto"> <div style="height: 50px;width: 50px;position: absolute;right: 0;bottom: 0;background-color: black"></div> </div> <div style="position: relative;width: 300px;height: 100px;border: 1px solid red;margin: 0 auto"> <div style="height: 50px;width: 50px;position: absolute;left: -70px;bottom: 0;background-color: black"></div> </div> <div style="position: relative;width: 300px;height: 100px;border: 1px solid red;margin: 0 auto"></div> </body> </html> 第十五周 第五章 css内容 position 多层堆叠 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div style="z-index:10;position: fixed;background-color: white;height: 200px;width: 300px;top: 50%;left: 50%;margin-left: -150px;margin-top: -100px"></div> <div style="z-index:9;position: fixed;background-color: black;top: 0;bottom: 0;left: 0;right: 0;opacity: 0.6"></div> <div style="height: 5000px;background-color: green"></div> </body> </html> 第十五周 第六章 css内容 overflow <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div style="height: 200px;width: 300px;overflow: hidden"> <img src="0.jpg"> </div> <div style="height: 200px;width: 300px;overflow: auto"> <img src="0.jpg"> </div> </body> </html> 第十五周 第七章 css内容 hover: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .pg-header{ position: fixed; top: 0; left: 0; right: 0; height: 50px; background-color: blue; line-height: 50px; } .pg-body{ margin-top: 55px; } .w{ width: 980px; margin: 0 auto; } .pg-header .menue{ display: inline-block; padding: 0 10px 0 10px; color: white; } .pg-header .menue:hover{ background-color: blue; } </style> </head> <body> <div class="pg-header"> <div class="w"> <a class="logo"></a> <a class="menue">全部</a> <a class="menue">42区</a> <a class="menue">段子</a> <a class="menue">1024</a> </div> </div> <div class="pg-body"> <div class="w">hhh</div> </div> </body> </html> 第十五周 第八章 css内容 backgroud; 点赞图标上下移动 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div style="height: 100px"></div> <div style="background-image: url(1..png);height: 20px;width:20px;border:1px solid red;background-repeat: no-repeat;background-position-x: 0px;background-position-y: -10px"></div> </body> </html> 第十五周 第九章 css内容 backgroud; 登录框放个图标 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div style="height: 38px;width: 400px;position: relative"> <input type="text" style="height: 38px;width: 350px;padding-right: 50px" /> <span style="background-image: url(u=3520327743,3495362103&fm=200&gp=0.jpg);display: inline-block;height: 30px;width: 30px;position: absolute;right: 0;top: 5px"></span> </div> </body> </html> 第十五周 第十一章节 javascript代码存在形式 1、直接写 2、从远程导入 3、要写在body的最后面 4、注释: 单行 // 多行: /* */ <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <script src=""></script> <script> </script> </body> </html> 第十五周 第十三章节:javascript字符串操作以及跑马灯实例 一串文字一直循环 1、 a="alex" a.charAt(2) "e" a.charAt(0) "a" 2、 substring :获取全部内容 a.substring(1,3) "le" a="bob" "bob" 3、 a.length 3 定时器: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <script> setInterval("alert(123)",5000) </script> </body> </html> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <script> function fun1(){ console.log(2) } setInterval("fun1();",5000); </script> </body> </html> 一串文字一直循环 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div id="i1">欢迎顾客前来购买</div> <script> function func2(){ var tag=document.getElementById('i1'); var content=tag.innerText; var f=content.charAt(0); var k=content.substring(1,content.length); var new_content=k+f; tag.innerText=new_content } setInterval('func2();',200); </script> </body> </html> 第十五周 第十四章节 javascript的数组、字典、for循环 第十五周 第十五章节 javascript的条件语句: if(){ }else if(条件){ }else if(条件){ }else{ } if(1==1){ } if(1!==1){ } 值相等就行 1=="1" true 值和类型都要相等 1==="1" false if(1==1 && 2==2) if(1==1 || 2==2) 第十五周 第十六章节 javascript的函数定义: function func1(a,b,c){ } 调用:函数名(1,2,3) 第十五周 第十七章节 DOM 选择器: 1、查找标签: 获取单个元素:document.getElementById('i1') 获取多个元素(列表):document.getElementsByTagName('div') 获取多个元素(列表):document.getElementsByClassName('c1') a、直接找: document.getElementById 根据ID获取一个标签 document.getElementsByTagName 根据name属性获取标签集合 document.getElementsByClassName 根据class属性获取标签集合 document.getElementsByTagName 根据签名获取标签属性 b、间接 parentElement 父亲节点标签 children 所有子标签 firstElementCild 第一个子标签 lastElementChild 最后一个子标签 nextElementSibling 下一个兄弟标签 previousElementSibling 上一个兄弟标签 2、操作标签: a、innerText 获取标签里面的内容 标签.innerText 对标签的内部内容进行重新赋值: 标签.innerText="" b、classname tag.classname 整体操作 tag.classList.add() 添加 tag.classList.remove() 删除 实例: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div id="i1">我的中国心</div> <a>hhh</a> <a>kkkk</a> <a>tttt</a> </body> </html> 运行: for(var i=1;i<tags.length;i++){tags[i].innerText='zzz'} "zzz" 第十五周 第十八章节 DOM间 选择器 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div></div> <div></div> <div> a1 </div> <div> <div></div> <div id="i1"> a2 </div> </div> <div> <div></div> <div> a3 </div> </div> </body> </html> tag=document.getElementById('i1') <div id=?"i1">? a2 ?</div>? tag.className='c1'; "c1" tag <div id=?"i1" class=?"c1">? a2 ?</div>? tag.classList ["c1", value: "c1"] tag.classList.add('c5') undefined tag <div id=?"i1" class=?"c1 c5">? a2 ?</div>? tag.classList.remove('c5') undefined tag <div id=?"i1" class=?"c1">? a2 ?</div>? <div onclick="fun();">点我</div> <script> function func(){ } </script> 第十五周 第十九章节 模态对话框 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .hide { display: none; } .c1 { position: fixed; top: 0; bottom: 0; left: 0; right: 0; background-color: black; opacity: 0.6; z-index: 9; } .c2 { width: 500px; height: 400px; background-color: white; position: fixed; left: 50%; top: 50%; margin-left: -250px; margin-top: -200px; z-index: 10; } </style> </head> <body style="margin: 0"> <div> <input type="button" value="添加" onclick="ShowMode()"/> <table> <thead> <tr> <th>主机名</th> <th>端口</th> </tr> </thead> <tbody> <tr> <td>192.168.1</td> <td>4231</td> </tr> <tr> <td>192.168.2</td> <td>4232</td> </tr> <tr> <td>192.168.3</td> <td>4233</td> </tr> </tbody> </table> </div> <!--遮挡层开始--> <div id="i1" class=" c1 hide"> <!--遮挡层结束--> </div> <!--弹出框开始--> <div id="i2" class="c2 hide"> <p><input type="text"></p> <p><input type="text"></p> <p> <input type="button" value="确定"/> <input type="button" value="取消" onclick="HideMode1()"/> </p> </div> <!--弹出框结束--> <script> function ShowMode() { document.getElementById('i1').classList.remove('hide') document.getElementById('i2').classList.remove('hide') } function HideMode1() { document.getElementById('i1').classList.add('hide') document.getElementById('i2').classList.add('hide') } </script> </body> </html> 第十五周 第二十章节 全选、反选、取消 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .hide { display: none; } .c1 { position: fixed; top: 0; bottom: 0; left: 0; right: 0; background-color: black; opacity: 0.6; z-index: 9; } .c2 { width: 500px; height: 400px; background-color: white; position: fixed; left: 50%; top: 50%; margin-left: -250px; margin-top: -200px; z-index: 10; } </style> </head> <body style="margin: 0"> <div> <input type="button" value="添加" onclick="ShowMode()"/> <input type="button" value="全选" onclick="Chooseall()"/> <input type="button" value="取消" onclick="Cancall()"/> <input type="button" value="反选" onclick="Reverseall()"/> <table> <thead> <tr> <th>选择</th> <th>主机名</th> <th>端口</th> </tr> </thead> <tbody id="tb"> <tr> <td><input type="checkbox"/></td> <td>192.168.1</td> <td>4231</td> </tr> <tr> <td><input type="checkbox"/></td> <td>192.168.2</td> <td>4232</td> </tr> <tr> <td><input type="checkbox"/></td> <td>192.168.3</td> <td>4233</td> </tr> </tbody> </table> </div> <!--遮挡层开始--> <div id="i1" class=" c1 hide"> <!--遮挡层结束--> </div> <!--弹出框开始--> <div id="i2" class="c2 hide"> <p><input type="text"></p> <p><input type="text"></p> <p> <input type="button" value="确定"/> <input type="button" value="取消" onclick="HideMode1()"/> </p> </div> <!--弹出框结束--> <script> function ShowMode() { document.getElementById('i1').classList.remove('hide'); document.getElementById('i2').classList.remove('hide') } function HideMode1() { document.getElementById('i1').classList.add('hide'); document.getElementById('i2').classList.add('hide') } function Chooseall() { var tbody = document.getElementById('tb'); var tb_list = tbody.children; for(var i = 0; i < tb_list.length; i++){ var td_children=tb_list[i]; var check_box = td_children.children[0].children[0]; check_box.checked = true; } } function Cancall() { var tbody = document.getElementById('tb'); var tb_list = tbody.children; for(var i = 0; i < tb_list.length; i++){ var td_children=tb_list[i]; var check_box = td_children.children[0].children[0]; check_box.checked = false; } } function Reverseall() { var tbody = document.getElementById('tb'); var tb_list = tbody.children; for(var i = 0; i < tb_list.length; i++){ var td_children=tb_list[i]; var check_box = td_children.children[0].children[0]; if(check_box.checked){ check_box.checked = false; }else { check_box.checked = true; } } } </script> </body> </html> 第十五周 第二十一章节 javascript 必须加分号 第十五周 第二十二章节 后台左侧菜单: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .hide{ display: none; } .item .header{ height: 38px; background-color: green; color: black; line-height: 38px; } </style> </head> <body> <div style="height: 48px"></div> <div style="width: 300px;"> <div class="item"> <div id="i1" class="header" onclick="changemenue('i1');">菜单1</div> <div class="content hide"> <div>内容1</div> <div>内容2</div> <div>内容3</div> </div> </div> <div class="item"> <div id="i2" class="header" onclick="changemenue('i2');">菜单2</div> <div class="content hide"> <div>内容2</div> <div>内容2</div> <div>内容2</div> </div> </div> <div class="item"> <div id="i3" class="header " onclick="changemenue('i3');">菜单3</div> <div class="content hide"> <div>内容3</div> <div>内容3</div> <div>内容3</div> </div> </div> <div class="item"> <div id="i4" class="header " onclick="changemenue('i4');">菜单4</div> <div class="content hide"> <div>内容4</div> <div>内容4</div> <div>内容4</div> </div> </div> </div> <script> function changemenue(nid){ var current_header=document.getElementById(nid); var item_list=current_header.parentElement.parentElement.children; for(var i=0;i<item_list.length;i++){ var item_current = item_list[i]; item_current.children[1].classList.add('hide'); } current_header.nextElementSibling.classList.remove('hide'); } </script> </body> </html> 第十六周 第三章 css内容补充、后台管理页面 第十六周 第十七章 鼠标拿走在框里显示 请输入内容 第十六周 第十九章 创建标签,在标签下面再创建标签 第 十七周 03章节 jquery常用的就是讲的这些,其他的可以不会 jquery和dom之间转换 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div id="i1">123</div> <script src="jquery-3.3.1.js"></script> </body> </html> $("#i1") jQuery.fn.init?[div#i1] document.getElementById('i1') <div id="i1">123</div> jquery转dom $("#i1")[0] <div id="i1">123</div> dom转jquery d=document.getElementById('i1') <div id="i1">123</div> $(d) jQuery.fn.init?[div#i1] 第17周 04章节 多选 反选 取消 1、组合选择标签: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <script src="jquery-3.3.1.js"></script> <div id="i10" class="c1"> <a>f</a> <a>f</a> </div> <div class="c1"> <a>f</a> </div> <div class="c1"> <div class="c2"></div> </div> </body> </html> $('a,.c2,#i10') jQuery.fn.init(5)?[div#i10.c1, a, a, a, div.c2, prevObject: jQuery.fn.init(1)] 2、层级:选多个子标签 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <script src="jquery-3.3.1.js"></script> <div id="i10" class="c1"> <div> <a>hhhh</a> </div> <a>f</a> <a>f</a> </div> <div class="c1"> <a>f</a> </div> <div class="c1"> <div class="c2"></div> </div> </body> </html> $('#i10 a') jQuery.fn.init(3)?[a, a, a, prevObject: jQuery.fn.init(1)] $('#i10>a') jQuery.fn.init(2)?[a, a, prevObject: jQuery.fn.init(1)] $('#i10 a:eq(0)') jQuery.fn.init?[a, prevObject: jQuery.fn.init(1)] 3、属性选择器: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <script src="jquery-3.3.1.js"></script> <div id="i10" class="c1"> <div> <a>hhhh</a> </div> <a bob="123">f</a> <a bob="456">f</a> </div> <div class="c1"> <a>f</a> </div> <div class="c1"> <div class="c2"></div> </div> </body> </html> $('[bob]') jQuery.fn.init(2)?[a, a, prevObject: jQuery.fn.init(1)] $('[bob="123"]') jQuery.fn.init?[a, prevObject: jQuery.fn.init(1)] 第17周 05章节 多选 反选 取消 删选器以及Tab菜单示例 $(this).prop('checked'); 获取值 $(this).prop('checked',v); 设置值 jQuery内置循环:(this).prop('checked')each({}) 三元运算:var v=$(this).prop('checked')?false:true; <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <input type="button" value="全选" onclick="checkAll();"> <input type="button" value="取消" onclick="cancelAll();"> <input type="button" value="反选" onclick="reverseAll();"> <table border="1"> <thead> <tr> <th>选项</th> <th>ip</th> <th>端口</th> </tr> </thead> <tbody > <tr> <td><input type="checkbox"></td> <td>1.1.1.1</td> <td>80</td> </tr> <tr> <td><input type="checkbox"></td> <td>1.1.1.1</td> <td>80</td> </tr> <tr> <td><input type="checkbox"></td> <td>1.1.1.1</td> <td>80</td> </tr> <tr> <td><input type="checkbox"></td> <td>1.1.1.1</td> <td>80</td> </tr> </tbody> </table> <script src="jquery-3.3.1.js"></script> <script> function checkAll(){ $(":checkbox").prop('checked',true); } function cancelAll(){ $(":checkbox").prop('checked',false); } function reverseAll(){ $(':checkbox').each(function(k){ /* if ($(this).prop('checked')){ $(this).prop('checked', false) } else { $(this).prop('checked', true) } */ var v=$(this).prop('checked')?false:true; $(this).prop('checked',v); }) } </script> </body> </html> 第17周 06章节 删选器2 点击后展开 绑定事件 兄弟标签 父标签 children标签 next()标签 preve()标签 find() 链式编程 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .header{ background: black; color: wheat; } .content{ height: 50px; } .hide{ display: none; } </style> </head> <body> <div style="height: 400px;width: 200px;border: 1px solid red"> <div class="item"> <div class="header" >标题1</div> <div class="content hide">内容</div> </div> <div class="item"> <div class="header">标题2</div> <div class="content hide">内容</div> </div> <div class="item"> <div class="header">标题3</div> <div class="content hide">内容</div> </div> </div> <script src="jquery-3.3.1.js"></script> <script> $('.header').click(function(){ $(this).next().removeClass('hide').parent().siblings().find('.content').addClass('hide'); }) </script> </body> </html> 第17周 07章节 模态编程框(1) parents([expr]) parentsUntil([e|e][,f]) children([expr]) find(e|o|e) next([expr]) nextAll([expr]) nextUntil([e|e][,f]) prev([expr]) prevAll([expr]) prevUntil([e|e][,f]) siblings([expr]) <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <table border="1"> <tr> <td>1.1.1.1</td> <td>80</td> <td> <a>编辑</a> <a>删除</a> </td> </tr> <tr> <td>1.1.1.1</td> <td>80</td> <td> <a>编辑</a> <a>删除</a> </td> </tr> <tr> <td>1.1.1.1</td> <td>80</td> <td> <a>编辑</a> <a>删除</a> </td> </tr> <tr> <td>1.1.1.1</td> <td>80</td> <td> <a>编辑</a> <a>删除</a> </td> </tr> </table> </body> </html> 第17周 08章节 模态编程框(2)--弹出对话框 下一节完善 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .hide{ display: none; } .model{ position: fixed; top:50%; left: 50%; width: 500px; height: 500px; margin-left: -250px; margin-top: -250px; background: silver; z-index: 10; } .shadow{ position: fixed; top: 0; left: 0; right: 0; bottom: 0; opacity: 0.6; background: black; z-index: 9; } </style> </head> <body> <a onclick="addEliment()">添加</a> <table border="1"> <tr> <td>1.1.1.1</td> <td>80</td> <td> <a class="adit">编辑</a> <a>删除</a> </td> </tr> <tr> <td>1.1.1.2</td> <td>80</td> <td> <a class="adit">编辑</a> <a>删除</a> </td> </tr> <tr> <td>1.1.1.3</td> <td>80</td> <td> <a class="adit">编辑</a> <a>删除</a> </td> </tr> <tr> <td>1.1.1.4</td> <td>80</td> <td> <a class="adit">编辑</a> <a>删除</a> </td> </tr> </table> <dev> <div class="model hide"> <input name="hostname" type="text"> <input name="port" type="text"> <div > <input type="button" value="取消" onclick="cancelModl()"> </div> </div> <div class="shadow hide"></div> </dev> <script src="jquery-3.3.1.js"></script> <script> function addEliment(){ $('.model,.shadow').removeClass('hide'); } function cancelModl(){ $('.model,.shadow').addClass('hide'); } $('edit').click(function(){ }); </script> </body> </html> 第17周 09章节 jquery样式及属性操作 --弹出对话框并且赋值 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div id="i1">hhhhh<a>oooooo</a>uuuuu</div> <script src="jquery-3.3.1.js"></script> </body> </html> $('#i1').html("<p>kkkkk</p>") 解析标签 $('#i1').text("<p>llllll</p>") 不解析标签 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div id="i1">hhhhh<a>oooooo</a>uuuuu</div> <input id="i2" type="text"> <script src="jquery-3.3.1.js"></script> </body> </html> $('#i2').val() $('#i2').val('999') <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .hide{ display: none; } .model{ position: fixed; top:50%; left: 50%; width: 500px; height: 500px; margin-left: -250px; margin-top: -250px; background: silver; z-index: 10; } .shadow{ position: fixed; top: 0; left: 0; right: 0; bottom: 0; opacity: 0.6; background: black; z-index: 9; } </style> </head> <body> <a onclick="addEliment()">添加</a> <table border="1"> <tr> <td>1.1.1.1</td> <td>80</td> <td> <a class="adit">编辑</a> <a>删除</a> </td> </tr> <tr> <td>1.1.1.2</td> <td>80</td> <td> <a class="adit">编辑</a> <a>删除</a> </td> </tr> <tr> <td>1.1.1.3</td> <td>80</td> <td> <a class="adit">编辑</a> <a>删除</a> </td> </tr> <tr> <td>1.1.1.4</td> <td>80</td> <td> <a class="adit">编辑</a> <a>删除</a> </td> </tr> </table> <dev> <div class="model hide"> <input name="hostname" type="text"> <input name="port" type="text"> <div > <input type="button" value="取消" onclick="cancelModl()"> </div> </div> <div class="shadow hide"></div> </dev> <script src="jquery-3.3.1.js"></script> <script> function addEliment(){ $('.model,.shadow').removeClass('hide'); } function cancelModl(){ $('.model,.shadow').addClass('hide'); $('.model input[type=text]').val(""); } $('.adit').click(function(){ $('.model,.shadow').removeClass('hide'); var tds=$(this).parent().prevAll(); //this:获取内容 var port=$(tds[0]).text(); var host=$(tds[1]).text(); $('.model input[name="hostname"]').val(host); $('.model input[name=port]').val(port); }); </script> </body> </html> 第17周 10章节 模态编程 开关 属性操作: $('#i1').attr('type') $('#i1').removeAttr('name') $()prop $('#i2').prop('checked',true); <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .hide{ display: none; } </style> </head> <body> <input id="i1" type="button" value="开关"> <div class="c1 hide">hhhhhhhhhh</div> <script src="jquery-3.3.1.js"></script> <script> $('#i1').click(function(){ $('.c1').toggleClass('hide'); }) </script> </body> </html> $('#i1').attr('type') "button" $('#i1').attr('name','bob') $('#i1')[0] <input id="i1" type="button" value="开关"> $('#i1').removeAttr('name') <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .hide{ display: none; } </style> </head> <body> <input type="checkbox" id="i2"/> <input id="i1" type="button" value="开关"/> <div class="c1 hide">hhhhhhhhhh</div> <script src="jquery-3.3.1.js"></script> <script> $('#i1').click(function(){ $('.c1').toggleClass('hide'); }) </script> </body> </html> $('#i2').prop('checked',true); jQuery.fn.init?[input#i2] $('#i2').prop('checked',false); jQuery.fn.init?[input#i2] 第17周 11章节 tab菜单切换 添加ip 在中间添加一行 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .hide{ display: none; } .model{ position: fixed; top:50%; left: 50%; width: 500px; height: 500px; margin-left: -250px; margin-top: -250px; background: silver; z-index: 10; } .shadow{ position: fixed; top: 0; left: 0; right: 0; bottom: 0; opacity: 0.6; background: black; z-index: 9; } </style> </head> <body> <a onclick="addEliment()">添加</a> <table border="1"> <tr> <td target="hostname">1.1.1.1</td> <td target="port">80</td> <td target="网段">1.1.1.0</td> <td> <a class="adit">编辑</a> <a>删除</a> </td> </tr> <tr> <td target="hostname">1.1.1.2</td> <td target="port">80</td> <td target="网段">1.1.1.0</td> <td> <a class="adit">编辑</a> <a>删除</a> </td> </tr> <tr> <td target="hostname">1.1.1.3</td> <td target="port">80</td> <td target="网段">1.1.1.0</td> <td> <a class="adit">编辑</a> <a>删除</a> </td> </tr> <tr> <td target="hostname">1.1.1.4</td> <td target="port">80</td> <td target="网段">1.1.1.0</td> <td> <a class="adit">编辑</a> <a>删除</a> </td> </tr> </table> <dev> <div class="model hide"> <input name="hostname" type="text"> <input name="port" type="text"> <input name="网段" type="text"> <div > <input type="button" value="取消" onclick="cancelModl()"> </div> </div> <div class="shadow hide"></div> </dev> <script src="jquery-3.3.1.js"></script> <script> function addEliment(){ $('.model,.shadow').removeClass('hide'); } function cancelModl(){ $('.model,.shadow').addClass('hide'); $('.model input[type=text]').val(""); } $('.adit').click(function(){ $('.model,.shadow').removeClass('hide'); var tds=$(this).parent().prevAll(); tds.each(function(){ var n=$(this).attr('target'); var text=$(this).text(); var a1='.model input[name="'; var a2='"]'; var temp=a1+n+a2; $(temp).val(text); }); //this:获取内容 // var port=$(tds[0]).text(); // var host=$(tds[1]).text(); // $('.model input[name="hostname"]').val(host); // $('.model input[name=port]').val(port); }); </script> </body> </html> 第17周 12章节 jquery内容操作 没写全 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .hide{ display: none; } .menue{ height: 38px; background-color: antiquewhite; } .menue .menue-item{ float: left; border-right: 1px solid red; line-height: 38px; padding: 0 5px; cursor: pointer; } .content{ min-height: 50px; border: 1px solid gainsboro; } .active{ background-color: aqua; } </style> </head> <body> <div style="width: 700px;margin: 0 auto"> <div class="menue"> <div class="menue-item active" a="1">菜单1</div> <div class="menue-item" a="2">菜单2</div> <div class="menue-item">菜单3</div> </div> <div class="content"> <div b="1">内容1</div> <div class="hide" b="2">内容2</div> <div class="hide" b="3">内容3</div> </div> </div> <script src="jquery-3.3.1.js"></script> <script> $('.menue-item').click(function(){ $(this).addClass('active').siblings().removeClass('active'); var target=$(this).attr('a'); }) </script> </body> </html> 第18周 07章节 Django web框架 第18周 08章节 Django工程创建 1、安装django 创建:django-admin ststtproject +文件名 访问:python manage.py runserver 127.0.0.1:8001 新建ceshi.py from django.shortcuts import HttpResponse def index(request): return HttpResponse("ok") urls.py: """ceshi URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from ceshi3 import s1 urlpatterns = [ path('admin/', admin.site.urls), path('index/', s1.index), ] 访问:http://127.0.0.1:8001/hhhhh/ 第18周 09章节 django目录 urls.py: """ceshi URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from django.shortcuts import HttpResponse def home(request): return HttpResponse('<h1>hello</h1>') urlpatterns = [ path('admin/', admin.site.urls), path('index.html', home), ] 第18周 10章 django创建App 第18周 11章 django app里面的各个组件介绍 第18周 12章 django 实现用户登录 view.py from django.shortcuts import render # Create your views here. from django.shortcuts import HttpResponse def login(request): f=open('template/login.html','r',encoding='utf-8') data=f.read() f.close() return HttpResponse(data) urls.py """ceshi URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from cmdb import views urlpatterns = [ path('admin/', admin.site.urls), path('login', views.login), ] login.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> label{ width: 80px; text-align: right; } </style> </head> <body> <form action="/login/" method="post"> <p> <label for="uesrname">用户名</label> <input id="uesrname" type="text"> </p> <p> <label for="uesrname">密码</label> <input id="uesrname" type="text"> <input type="submit" value="提交"> </p> </form> </body> </html> 正确访问:http://127.0.0.1:8008/login 错误访问:http://127.0.0.1:8008/login/ 第18周 13章 django 实现用户登录2 配置static文件 1、新建static目录 2、static目录里面放入css、js 文件 3、去settings 文件里设置 : DIRS': [os.path.join(BASE_DIR,'templates')], 这里要写模板位置 commons.css body{ background-color: antiquewhite; } views.py from django.shortcuts import render def login(request): return render(request,'login.html') settings.py """ Django settings for ceshi project. Generated by 'django-admin startproject' using Django 2.0.3. For more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '+0_2hjpsfembktg6zi&q$y+1ma^b7o*mlxyv!b-c0(q#*1xw1m' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', #'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'ceshi.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'ceshi.wsgi.application' # Database # https://docs.djangoproject.com/en/2.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.0/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS=( os.path.join(BASE_DIR,'static'), ) login.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="/static/commons.css"> <style> label{ width: 80px; text-align: right; } </style> </head> <body> <form action="/login/" method="post"> <p> <label for="uesrname">用户名</label> <input id="uesrname" type="text"> </p> <p> <label for="uesrname">密码</label> <input id="uesrname" type="text"> <input type="submit" value="提交"> </p> </form> </body> </html> urls.py """ceshi URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from cmdb import views urlpatterns = [ path('admin/', admin.site.urls), path('login', views.login), ] 第18周 14章 django实现用户登录与前端交互 urls.py """ceshi URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from cmdb import views urlpatterns = [ path('admin/', admin.site.urls), path('login/', views.login), ] login.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="/static/commons.css"> <style> label{ width: 80px; text-align: right; } </style> </head> <body> <form action="/login/" method="post"> <p> <label for="uesrname" >用户名</label> <input id="uesrname" name="user" type="text"> </p> <p> <label for="uesrname">密码</label> <input id="uesrname" name="pwd" type="password"> <input type="submit" value="提交"> <span style="color: red;">{{ error_msg }}</span> </p> </form> <script src="jquery-3.2.1.js"></script> </body> </html> settings.py """ Django settings for ceshi project. Generated by 'django-admin startproject' using Django 2.0.3. For more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '+0_2hjpsfembktg6zi&q$y+1ma^b7o*mlxyv!b-c0(q#*1xw1m' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', #'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'ceshi.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'template')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'ceshi.wsgi.application' # Database # https://docs.djangoproject.com/en/2.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.0/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS=( os.path.join(BASE_DIR,'static'), ) commons.css body{ background-color: antiquewhite; } views.py from django.shortcuts import render from django.shortcuts import redirect def login(request): error_msg="" if request.method == "POST": user=request.POST.get('user',None) pwd=request.POST.get('pwd',None) if user == 'root' and pwd == "123": return redirect('http://www.baidu.com/') else: error_msg="用户名密码错误" return render(request,'login.html',{'error_msg':error_msg}) 第18周第15章节 用户和前端交互2 1、添加表单 urls.py """ceshi URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from cmdb import views urlpatterns = [ path('admin/', admin.site.urls), path('login/', views.login), path('home/', views.home), ] login.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="/static/commons.css"> <style> label{ width: 80px; text-align: right; } </style> </head> <body> <form action="/login/" method="post"> <p> <label for="uesrname" >用户名</label> <input id="uesrname" name="user" type="text"> </p> <p> <label for="uesrname">密码</label> <input id="uesrname" name="pwd" type="password"> <input type="submit" value="提交"> <span style="color: red;">{{ error_msg }}</span> </p> </form> <script src="jquery-3.2.1.js"></script> </body> </html> home.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body style="margin: 0"> <div style="height: 48px;background-color: aqua"></div> <div> <form action="/home/" method="post"> <input type="text" name="username" placeholder="用户名"> <input type="text" name="email" placeholder="邮箱"> <input type="text" name="gender" placeholder="性别"> <input type="submit" value="添加"> </form> <table> {% for row in user_list %} <tr> <td>{{ row.username }}</td> <td>{{ row.gender }}</td> <td>{{ row.email }}</td> </tr> {% endfor %} </table> </div> </body> </html> settings.py """ Django settings for ceshi project. Generated by 'django-admin startproject' using Django 2.0.3. For more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '+0_2hjpsfembktg6zi&q$y+1ma^b7o*mlxyv!b-c0(q#*1xw1m' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', #'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'ceshi.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'template')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'ceshi.wsgi.application' # Database # https://docs.djangoproject.com/en/2.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.0/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS=( os.path.join(BASE_DIR,'static'), ) views.py from django.shortcuts import render from django.shortcuts import redirect def login(request): error_msg="" if request.method == "POST": user=request.POST.get('user',None) pwd=request.POST.get('pwd',None) if user == 'root' and pwd == "123": return redirect('/home') else: error_msg="用户名密码错误" return render(request,'login.html',{'error_msg':error_msg}) USER_LIST=[{'username':'jack','email':'145.com','gender':'男'}] for index in range(20): temp={'username':'jack'+str(index),'email':'145.com','gender':'男'} USER_LIST.append(temp) def home(request): if request.method=='POST': u=request.POST.get('username') e=request.POST.get('email') g=request.POST.get('gender') temp={'username':u+str(index),'email':e,'gender':g} USER_LIST.append(temp) return render(request,'home.html',{'user_list':USER_LIST}) 第18周 16章 django 路由简介 第18周 17章 知识总结 第19章 第三章 django工程创建 1、先用pychcarm 创建一个工程:19章 2、创建 app 在pycharm 的终端输入: on manage.py startapp app01 3、创建static文件: 在总的工程下创建 4、修改19章 里面 setting文件 注释掉 csrf 那一行 查看是否添加模板路径:'DIRS': [os.path.join(BASE_DIR, 'templates')] 添加 静态文件路径; STATIC_URL = '/static/' STATICFILES_DIRS=( os.path.join(BASE_DIR, 'static'), ------注意:一定要加逗号,否则报错 ) 注册app01: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app01', ] 5、在总的工程下创建 templates文件 第19章 第4章 打开多个数据和上传文件 打开多个数据: request.POST.getlist() 上传文件: obj=request.FILES.get('send') print(obj,type(obj),obj.name) import os file_path=os.path.join('upload',obj.name) f=open(file_path,mode="wb") for i in obj.chunks(): f.write(i) f.close() settings.py """ Django settings for 第19章 project. Generated by 'django-admin startproject' using Django 2.0.3. For more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'z7w5!-=vwuu$#$6i2yr05unkjvn*td@#qxc#0=-^d_ra4b-e+)' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', #'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = '第19章.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = '第19章.wsgi.application' # Database # https://docs.djangoproject.com/en/2.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.0/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIR=( os.path.join(BASE_DIR,'static'), ) urls.py """第19章 URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from app01 import views urlpatterns = [ path('admin/', admin.site.urls), path('index/', views.index), path('login/', views.login), ] views.py from django.shortcuts import render from django.shortcuts import HttpResponse from django.shortcuts import redirect # Create your views here. def index(request): return HttpResponse('ok') def login(request): if request.method=="GET": return render(request,'login.html') elif request.method=="POST": obj=request.FILES.get('send') print(obj,type(obj),obj.name) import os file_path=os.path.join('upload',obj.name) f=open(file_path,mode="wb") for i in obj.chunks(): f.write(i) f.close() from django.core.files.uploadedfile import InMemoryUploadedFile return render(request,'login.html') else: return redirect('/index/') login.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body > <form action="/login/" method="POST" enctype="multipart/form-data"> <p> <input type="text" name="user" placeholder="用户名"> </p> <p> <input type="password" name="pwd" placeholder="密码"> </p> <p> 男:<input type="radio" name="gender" value="1"/> 女:<input type="radio" name="gender" value="2"/> 小李:<input type="radio" name="gender" value="3"/> </p> <p> 男:<input type="checkbox" name="favor" value="11"/> 女:<input type="checkbox" name="favor" value="22"/> 小李:<input type="checkbox" name="favor" value="33"/> </p> <p> <select name="city" multiple> <option value="sh">上海</option> <option value="bj">北京</option> <option value="tj">天津</option> </select> </p> <p> <input type="file" name="send"> </p> <p> <input type="submit" value="提交"> </p> </form> </body> </html> 第19章 05节 django 的CBV 和 FBV FBV function base view 就是view里面写的函数 CBV 类 base view 就是view里面写的类 CBV 代码 settings """ Django settings for 第19章 project. Generated by 'django-admin startproject' using Django 2.0.3. For more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'z7w5!-=vwuu$#$6i2yr05unkjvn*td@#qxc#0=-^d_ra4b-e+)' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', #'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = '第19章.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = '第19章.wsgi.application' # Database # https://docs.djangoproject.com/en/2.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.0/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIR=( os.path.join(BASE_DIR,'static'), ) urls """第19章 URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from app01 import views urlpatterns = [ path('admin/', admin.site.urls), path('index/', views.index), path('login/', views.login), path('home/', views.Home.as_view()), ] views.py from django.shortcuts import render from django.shortcuts import HttpResponse from django.shortcuts import redirect # Create your views here. def index(request): return HttpResponse('ok') def login(request): if request.method=="GET": return render(request,'login.html') elif request.method=="POST": obj=request.FILES.get('send') print(obj,type(obj),obj.name) import os file_path=os.path.join('upload',obj.name) f=open(file_path,mode="wb") for i in obj.chunks(): f.write(i) f.close() from django.core.files.uploadedfile import InMemoryUploadedFile return render(request,'login.html') else: return redirect('/index/') from django.views import View class Home(View): def dispatch(self, request, *args, **kwargs): print('before')#可以定制写功能 result=super(Home,self).dispatch(request, *args, **kwargs)#相当于分发器 print('after')#可以定制写功能 return result def get(self,request): print(request.method) return render(request,'home.html') def post(self,request): print(request.method) return render(request,'home.html') home.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/home/" method="POST"> <input type="text" name="user"> <input type="submit"> </form> </body> </html> 第19周 06章 django 模板语音循环字典 settings.py """ Django settings for 第19章 project. Generated by 'django-admin startproject' using Django 2.0.3. For more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'z7w5!-=vwuu$#$6i2yr05unkjvn*td@#qxc#0=-^d_ra4b-e+)' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', #'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = '第19章.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = '第19章.wsgi.application' # Database # https://docs.djangoproject.com/en/2.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.0/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIR=( os.path.join(BASE_DIR,'static'), ) views.py from django.shortcuts import render from django.shortcuts import HttpResponse from django.shortcuts import redirect # Create your views here. USER_DICT={ 'k1':'root1', 'k2':'root2', 'k3':'root3', 'k4':'root4', } def index(request): return render(request,'index.html',{'user_dict':USER_DICT}) def login(request): if request.method=="GET": return render(request,'login.html') elif request.method=="POST": obj=request.FILES.get('send') print(obj,type(obj),obj.name) import os file_path=os.path.join('upload',obj.name) f=open(file_path,mode="wb") for i in obj.chunks(): f.write(i) f.close() from django.core.files.uploadedfile import InMemoryUploadedFile return render(request,'login.html') else: return redirect('/index/') # from django.views import View # # class Home(View): # def dispatch(self, request, *args, **kwargs): # print('before')#kkkk # result=super(Home,self).dispatch(request, *args, **kwargs) # print('after') # return result # # def get(self,request): # print(request.method) # return render(request,'home.html') # def post(self,request): # print(request.method) # return render(request,'home.html') urls.py """第19章 URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from app01 import views urlpatterns = [ path('admin/', admin.site.urls), path('login/', views.login), #path('home/', views.Home.as_view()), path('index/', views.index), ] index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {{ user_dict.k1 }} <ul> {% for key,row in user_dict.items %} <li>{{ key }}-{{ row }}</li> {% endfor %} </ul> </body> </html> 访问 http://127.0.0.1:8000/index/ 第19章 django 07 正则表达示 url id发生变化 url跟着发生变化 settings.py """ Django settings for 第19章 project. Generated by 'django-admin startproject' using Django 2.0.3. For more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'z7w5!-=vwuu$#$6i2yr05unkjvn*td@#qxc#0=-^d_ra4b-e+)' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', #'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = '第19章.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = '第19章.wsgi.application' # Database # https://docs.djangoproject.com/en/2.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.0/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIR=( os.path.join(BASE_DIR,'static'), ) views.py from django.shortcuts import render from django.shortcuts import HttpResponse from django.shortcuts import redirect # Create your views here. # USER_DICT={ # 'k1':'root1', # 'k2':'root2', # 'k3':'root3', # 'k4':'root4', # } USER_DICT={ '1':{'name':'root1','email':'root@123.com'}, '2':{'name':'root2','email':'root@123.com'}, '3':{'name':'root3','email':'root@123.com'}, '4':{'name':'root4','email':'root@123.com'} } def index(request): return render(request,'index.html',{'user_dict':USER_DICT}) def detail(request): nid=request.GET.get('nid') detail_info=USER_DICT[nid] return render(request,'detail.html',{'detail_info':detail_info}) def login(request): if request.method=="GET": return render(request,'login.html') elif request.method=="POST": obj=request.FILES.get('send') print(obj,type(obj),obj.name) import os file_path=os.path.join('upload',obj.name) f=open(file_path,mode="wb") for i in obj.chunks(): f.write(i) f.close() from django.core.files.uploadedfile import InMemoryUploadedFile return render(request,'login.html') else: return redirect('/index/') # from django.views import View # # class Home(View): # def dispatch(self, request, *args, **kwargs): # print('before')#kkkk # result=super(Home,self).dispatch(request, *args, **kwargs) # print('after') # return result # # def get(self,request): # print(request.method) # return render(request,'home.html') # def post(self,request): # print(request.method) # return render(request,'home.html') urls.py """第19章 URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from app01 import views urlpatterns = [ path('admin/', admin.site.urls), path('login/', views.login), #path('home/', views.Home.as_view()), path('index/', views.index), path('detail/', views.detail), ] index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <ul> {% for k,row in user_dict.items %} <li><a target="_blank" href="/detail/?nid={{ k }}">{{ row.name }}</a></li> {% endfor %} </ul> </body> </html> detail.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>详细信息</h1> <h6>用户名:{{ detail_info.name }}</h6> <h6>详细信息:{{ detail_info.email }}</h6> </body> </html> </body> </html> home.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/home/" method="POST"> <input type="text" name="user"> <input type="submit"> </form> </body> </html> login.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body > <form action="/login/" method="POST" enctype="multipart/form-data"> <p> <input type="text" name="user" placeholder="用户名"> </p> <p> <input type="password" name="pwd" placeholder="密码"> </p> <p> 男:<input type="radio" name="gender" value="1"/> 女:<input type="radio" name="gender" value="2"/> 小李:<input type="radio" name="gender" value="3"/> </p> <p> 男:<input type="checkbox" name="favor" value="11"/> 女:<input type="checkbox" name="favor" value="22"/> 小李:<input type="checkbox" name="favor" value="33"/> </p> <p> <select name="city" multiple> <option value="sh">上海</option> <option value="bj">北京</option> <option value="tj">天津</option> </select> </p> <p> <input type="file" name="send"> </p> <p> <input type="submit" value="提交"> </p> </form> </body> </html> 静态方式:常用方式 settings.py """ Django settings for 第19章 project. Generated by 'django-admin startproject' using Django 2.0.3. For more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'z7w5!-=vwuu$#$6i2yr05unkjvn*td@#qxc#0=-^d_ra4b-e+)' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', #'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = '第19章.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = '第19章.wsgi.application' # Database # https://docs.djangoproject.com/en/2.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.0/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIR=( os.path.join(BASE_DIR,'static'), ) views.py from django.shortcuts import render from django.shortcuts import HttpResponse from django.shortcuts import redirect import urllib # Create your views here. # USER_DICT={ # 'k1':'root1', # 'k2':'root2', # 'k3':'root3', # 'k4':'root4', # } USER_DICT={ '1':{'name':'root1','email':'root@123.com'}, '2':{'name':'root2','email':'root@123.com'}, '3':{'name':'root3','email':'root@123.com'}, '4':{'name':'root4','email':'root@123.com'} } def index(request): return render(request,'index.html',{'user_dict':USER_DICT}) def detail(request,nid): detail_info=USER_DICT[nid] return render(request,'detail.html',{ 'detail_info':detail_info}) def login(request): if request.method=="GET": return render(request,'login.html') elif request.method=="POST": obj=request.FILES.get('send') print(obj,type(obj),obj.name) import os file_path=os.path.join('upload',obj.name) f=open(file_path,mode="wb") for i in obj.chunks(): f.write(i) f.close() from django.core.files.uploadedfile import InMemoryUploadedFile return render(request,'login.html') else: return redirect('/index/') # from django.views import View # # class Home(View): # def dispatch(self, request, *args, **kwargs): # print('before')#kkkk # result=super(Home,self).dispatch(request, *args, **kwargs) # print('after') # return result # # def get(self,request): # print(request.method) # return render(request,'home.html') # def post(self,request): # print(request.method) # return render(request,'home.html') detail.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>详细信息</h1> <h6>用户名:{{ detail_info.name }}</h6> <h6>详细信息:{{ detail_info.email }}</h6> </body> </html> </body> </html> urls.py """第19章 URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from app01 import views from django.conf.urls import url import urllib urlpatterns = [ path('admin/', admin.site.urls), path('login/', views.login), #path('home/', views.Home.as_view()), path('index/', views.index), url('detail-(\d+).html', views.detail), ] index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <ul> {% for k,row in user_dict.items %} <li><a target="_blank" href="/detail-{{ k }}.html"> {{ row.name }} </a></li> {% endfor %} </ul> </body> </html> 19周 08章 DJango基于正则表达式 url2 路由系统: 1、path('login/', views.login), path('home/', views.Home.as_view()), 2、url('detail-(\d+).html', views.detail), 3、url('detail-(?P<nid>\d+)-(?P<nid>\d+).html', views.detail), 19周 09章 url的 name 对utl路由关系进行命令,以后可以根据这个名称来定制想要的url path('indexhhh/', views.index,name='indexx') url('indexhhh/(\d+)', views.index,name='indexx'), 模板语言: {% url indexx %} {% url indexx 3 %} 当前的url: action="{{ request.path_info }} 生成自己想要的url url('indexhhh/(\d+)/(\d+)', views.index,name='indexx'), v=reverse('indexx',args=(90,80)) url('indexhhh/(?P<nid>\d+)/(?P<uid>\d+)', views.index,name='indexx'), v=reverse('indexx',kwargs={"nid":"1", "uid":"99"}) <form action="{% url 'indexx' nid=1 uid=3 %}" method="POST"> settings.py """ Django settings for 第19章 project. Generated by 'django-admin startproject' using Django 2.0.3. For more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'z7w5!-=vwuu$#$6i2yr05unkjvn*td@#qxc#0=-^d_ra4b-e+)' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', #'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = '第19章.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = '第19章.wsgi.application' # Database # https://docs.djangoproject.com/en/2.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.0/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIR=( os.path.join(BASE_DIR,'static'), ) views.py from django.shortcuts import render from django.shortcuts import HttpResponse from django.shortcuts import redirect import urllib # Create your views here. # USER_DICT={ # 'k1':'root1', # 'k2':'root2', # 'k3':'root3', # 'k4':'root4', # } USER_DICT={ '1':{'name':'root1','email':'root@123.com'}, '2':{'name':'root2','email':'root@123.com'}, '3':{'name':'root3','email':'root@123.com'}, '4':{'name':'root4','email':'root@123.com'} } def index(request,nid,uid): print(request.path_info) from django.urls import reverse #v=reverse('indexx',args=(90,80)) v=reverse('indexx',kwargs={"nid":"1", "uid":"99"}) print(v) return render(request,'index.html',{'user_dict':USER_DICT}) def detail(request,nid): detail_info=USER_DICT[nid] return render(request,'detail.html',{ 'detail_info':detail_info}) def login(request): if request.method=="GET": return render(request,'login.html') elif request.method=="POST": obj=request.FILES.get('send') print(obj,type(obj),obj.name) import os file_path=os.path.join('upload',obj.name) f=open(file_path,mode="wb") for i in obj.chunks(): f.write(i) f.close() from django.core.files.uploadedfile import InMemoryUploadedFile return render(request,'login.html') else: return redirect('/index/') # from django.views import View # # class Home(View): # def dispatch(self, request, *args, **kwargs): # print('before')#kkkk # result=super(Home,self).dispatch(request, *args, **kwargs) # print('after') # return result # # def get(self,request): # print(request.method) # return render(request,'home.html') # def post(self,request): # print(request.method) # return render(request,'home.html') detail.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>详细信息</h1> <h6>用户名:{{ detail_info.name }}</h6> <h6>详细信息:{{ detail_info.email }}</h6> </body> </html> </body> </html> urls.py """第19章 URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from app01 import views from django.conf.urls import url import urllib urlpatterns = [ path('admin/', admin.site.urls), path('login/', views.login), #path('home/', views.Home.as_view()), #url('indexhhh/(\d+)/(\d+)', views.index,name='indexx'), url('indexhhh/(?P<nid>\d+)/(?P<uid>\d+)', views.index,name='indexx'), #path('indexhhh/', views.index,name='indexx'), #url('detail-(\d+).html', views.detail), url('detail-(?P<nid>\d+).html', views.detail), ] index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="{% url 'indexx' nid=1 uid=3 %}" method="POST"> <p><input type="text" name="user" placeholder="用户名"></p> <p><input type="text" name="user" placeholder="用户名"></p> <input type="submit" value="提交"> </form> <ul> {% for k,row in user_dict.items %} <li><a target="_blank" href="/detail-{{ k }}.html"> {{ row.name }} </a></li> {% endfor %} </ul> </body> </html> 访问: http://127.0.0.1:8000/indexhhh/1/9/ 19周 10章 django 路由分发 总的urls: from django.conf.urls import url,include import urllib urlpatterns = [ url(r'^cmdb/',include("app01.urls")), url(r'^monitor/',include("app02.urls")), ] cmdb里面的urls: from django.urls import path from app01 import views urlpatterns = [ path('login/', views.login), ] monitor里面的urls: from django.urls import path from app02 import views urlpatterns = [ path('login/', views.login), ] 19周 11章 django ORM基本创建类型以及生成数据库结构 类型: dbfirst :通过数据库创建类 codefirst:先创建类 再创建数据库 --最常用 ORM的意思: 通过类创建数据库 创建类 1、根据类自动创建书记库表 配置 app下的model.py 2、根据类对数据库表中的数据进行各种操作 class UserInfo(models.Model): #自动创建 id列 自增主键 username=models.CharField(max_length=32) password=models.CharField(max_length=64) 执行命令: python manage.py makemigrations python manage.py migrate 默认链接 sqlite 如果要链接myaql 需要进行配置: 前提:需要创建mysql表 DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME':'dbname', 'USER': 'root', 'PASSWORD': 'xxx', 'HOST': '', 'PORT': '', } } models.py from django.db import models # Create your models here. class UserInfo(models.Model): #自动创建 id列 自增主键 username=models.CharField(max_length=32) password=models.CharField(max_length=64) 19周 12章 django ORM使用mysql 注意: 需要先修改pymysql:在project同名文件夹的__init__文件中添加如下代码: import pymysql pymysql.install_as_MySql() 19周 13章 django ORM 基本操作 增、删、改、查 1、先导入模块 from app01 import models 创建 models.UserInfo.objects.create(username='root',password='123',) obj=models.UserInfo(username='bob',password='456') obj.save() dic={'username':'jack','password':'789'} models.UserInfo.objects.create(dic) 查 result=models.UserInfo.objects.all() result=models.UserInfo.objects.filter(username='root',password=999) 拿到的是一个对象,而且是名字、密码都一样的第一个 obj=models.UserInfo.objects.filter(username=u,password=p).first() 取对象中的某一个数据 obj=models.UserInfo.objects.filter(id=3).first() print(obj.username) 拿到的是一个列表,而且是名字、密码都一样的多个 obj=models.UserInfo.objects.filter(username=u,password=p) 循环拿列表中的某一个数据: def orm(request): obj=models.UserInfo.objects.filter(id=3) for i in obj: print(i.username) return HttpResponse('orm') 删除: models.UserInfo.objects.filter().delete() 更新 models.UserInfo.objects.all().update(password=888) models.UserInfo.objects.filter(id=1).update(password=999 第19章\urls.py urlpatterns = [ url(r'^cmdb/',include("app01.urls")), url(r'^monitor/',include("app02.urls")), ] app01\views.py from app01 import models def orm(request): 创建 models.UserInfo.objects.create(username='root',password='123',) obj=models.UserInfo(username='bob',password='456') obj.save() dic={'username':'jack','password':'789'} models.UserInfo.objects.create(dic) 查 result=models.UserInfo.objects.all() result=models.UserInfo.objects.filter(username='root',password=999) 删除: models.UserInfo.objects.filter().delete() 更新 models.UserInfo.objects.all().update(password=888) models.UserInfo.objects.filter(id=1).update(password=999 第19章 14节 基于ORM实现用户登录: 报错问题: 1、访问页面没有内容,返回200错误,说明肯定是html里面的内容写错了 2、ValueError: not enough values to unpack (expected 2, got 1) 这个错误说明:obj=models.UserInfo.objects.filter(id=nid).first() 这个里面没有写“id=” 或者:{'obj':obj} 这个写错了 总之是括号里面的少个东西 3、url一定要写成这样格式,否则很容易报错 url(r'^userdetail-(?P<nid>\d+)/', views.user_detail,), 过程: app01/urls.py """第19章 URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from app01 import views from django.conf.urls import url urlpatterns = [ path('login/', views.login), path('index/', views.index,), path('user_info/', views.user_info,), url(r'^userdetail-(?P<nid>\d+)/', views.user_detail,), path('orm/', views.orm), ] app01/views.py from django.shortcuts import render from django.shortcuts import HttpResponse from django.shortcuts import redirect import urllib # Create your views here. # USER_DICT={ # 'k1':'root1', # 'k2':'root2', # 'k3':'root3', # 'k4':'root4', # } USER_DICT={ '1':{'name':'root1','email':'root@123.com'}, '2':{'name':'root2','email':'root@123.com'}, '3':{'name':'root3','email':'root@123.com'}, '4':{'name':'root4','email':'root@123.com'} } def index(request): return render(request,'index.html') def user_info(request): user_list=models.UserInfo.objects.all() #print(user_list.query) return render(request,'user_info.html',{'user_list':user_list}) def user_detail(request,nid): obj=models.UserInfo.objects.filter(id=nid).first() return render(request,'user_detail.html',{'obj':obj}) def login(request): if request.method=="GET": return render(request,'login.html') elif request.method=="POST": #数据库中执行 select 判断用户名和密码是否中确 u=request.POST.get('user') p=request.POST.get('pwd') #count=models.UserInfo.objects.filter(username=u,password=p).count() 也可以,但是不经常用 obj=models.UserInfo.objects.filter(username=u, password=p).first() #print(obj) #下面意思:如果obj为真 if obj: return redirect('/cmdb/index/') else: return render(request,'login.html') else: return redirect('/index/') from app01 import models def orm(request): #创建 #models.UserInfo.objects.create(username='root',password='123',) # obj=models.UserInfo(username='bob',password='456') # obj.save() # dic={'username':'jack','password':'789'} # models.UserInfo.objects.create(dic) #查 result=models.UserInfo.objects.all() #result=models.UserInfo.objects.filter(username='root',password=999) # #删除: #models.UserInfo.objects.filter().delete() #更新 #models.UserInfo.objects.all().update(password=888) # obj=models.UserInfo.objects.filter(id=3) # for i in obj: # print(i.username) # return HttpResponse('orm') # from django.views import View # # class Home(View): # def dispatch(self, request, *args, **kwargs): # print('before')#kkkk # result=super(Home,self).dispatch(request, *args, **kwargs) # print('after') # return result # # def get(self,request): # print(request.method) # return render(request,'home.html') # def post(self,request): # print(request.method) # return render(request,'home.html') templates/login.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body > <form action="/cmdb/login/" method="POST" enctype="multipart/form-data"> <p> <input type="text" name="user" placeholder="用户名"> </p> <p> <input type="password" name="pwd" placeholder="密码"> </p> <input type="submit" value="提交"> </form> </body> </html> templates/index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> body{ margin: 0; } .menu{ display: block; padding: 5px; } </style> </head> <body> <div style="height: 48px;background-color: black;color: white"> 欢迎到来 </div> <div> <div style="position: absolute;top: 48px;bottom: 0;left: 0;width: 200px;background-color: aquamarine"> <a class="menu" href="/cmdb/user_info/">用户管理</a> <a class="menu" href="/cmdb/user_group/">用户组管理</a> </div> </div> <div style="position: absolute;top: 48px;bottom: 0;left: 210px;width: 0;overflow: auto"> </div> </body> </html> templates/user_info.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> body{ margin: 0; } .menu{ display: block; padding: 5px; } </style> </head> <body> <div style="height: 48px;background-color: black;color: white"> 欢迎到来 </div> <div> <div style="position: absolute;top: 48px;bottom: 0;left: 0;width: 200px;background-color: aquamarine"> <a class="menu" href="/cmdb/user_info/">用户管理</a> <a class="menu" href="/cmdb/user_group/">用户组管理</a> </div> </div> <div style="position: absolute;top: 48px;bottom: 0;left: 210px;width: 700px;overflow: auto;background-color: antiquewhite"> <h3>用户列表</h3> <ul> {% for row in user_list %} <li><a href="/cmdb/userdetail-{{ row.id }}/">{{ row.username }}</a></li> {% endfor %} </ul> </div> </body> </html> templates/user_detail.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> body{ margin: 0; } .menu{ display: block; padding: 5px; } </style> </head> <body> <div style="height: 48px;background-color: black;color: white"> 欢迎到来 </div> <div> <div style="position: absolute;top: 48px;bottom: 0;left: 0;width: 200px;background-color: aquamarine"> <a class="menu" href="/cmdb/user_info/">用户管理</a> <a class="menu" href="/cmdb/user_group/">用户组管理</a> </div> </div> <div style="position: absolute;top: 48px;bottom: 0;left: 210px;width: 700px;overflow: auto;background-color: antiquewhite"> <h1>用户详细信息</h1> <h2>{{ obj.id }}</h2> <h2>{{ obj.name }}</h2> <h2>{{ obj.password }}</h2> </div> </body> </html> 19周-15章python基于 Django 基于ORM实现用户增加、删除、修改、查看 models.Business.objects.all() 是个对象 models.Business.objects.values('id','caption') #[{'id':'1','caption':'运维','code':'sa'}] values 是个字典 models.Business.objects.values_list('id','caption') #[(1,运维),(2,市场)] values_list 是个元组 1、 注意:method="post" 一定要写。一定是小写 否则报错 <form action="/cmdb/user_info/" method="post"> 2、 注意href和action、return redirect三个的区分,容易混淆 这是做的跳转: <a class="menu" href="/cmdb/user_info/">用户管理</a> 这是提交的当前的页面: <form method="post" action="/cmdb/useredit-{{ obj.id }}/"> 这个不加html return redirect用法:不加html return redirect('/cmdb/index/') 3、 根据id删除用户的瞬间跳转到当前页面 <a href="/cmdb/userdel-{{ row.id }}/"> 删除 </a> def user_del(request,nid): models.UserInfo.objects.filter(id=nid).delete() return redirect('/cmdb/user_info/') 4、 注意不成功的话 重新打开一个页面试试 5、 注意:<input type="text" name="id" value="1"/> value的意思是可以在输入框中显示出来id style="display: none" 6、 注意form表单里面action路径 一定要和 url里面的保持一致,否则报错, 例如: href="/cmdb/userdetail-{{ row.id }} url(r'^userdetail-(?P<nid>\d+)/', views.user_detail,), app01/urls.py """第19章 URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from app01 import views from django.conf.urls import url urlpatterns = [ path('login/', views.login), path('index/', views.index,), path('user_info/', views.user_info,), url(r'^userdetail-(?P<nid>\d+)/', views.user_detail,), url(r'^userdel-(?P<nid>\d+)/', views.user_del,), url(r'^useredit-(?P<nid>\d+)/', views.user_edit,), path('orm/', views.orm), ] app01/views.py from django.shortcuts import render from django.shortcuts import HttpResponse from django.shortcuts import redirect from app01 import models import urllib # Create your views here. # USER_DICT={ # 'k1':'root1', # 'k2':'root2', # 'k3':'root3', # 'k4':'root4', # } USER_DICT={ '1':{'name':'root1','email':'root@123.com'}, '2':{'name':'root2','email':'root@123.com'}, '3':{'name':'root3','email':'root@123.com'}, '4':{'name':'root4','email':'root@123.com'} } def index(request): return render(request,'index.html') def user_info(request): if request.method=="GET": user_list=models.UserInfo.objects.all() return render(request,'user_info.html',{'user_list':user_list}) elif request.method=="POST": u=request.POST.get('user') p=request.POST.get('pwd') models.UserInfo.objects.create(username=u,password=p) user_list=models.UserInfo.objects.all() #print(user_list.query) return render(request,'user_info.html',{'user_list':user_list}) def user_del(request,nid): models.UserInfo.objects.filter(id=nid).delete() return redirect('/cmdb/user_info/') def user_edit(request,nid): if request.method=='GET': obj=models.UserInfo.objects.filter(id=nid).first() return render(request,'user_edit.html',{'obj':obj}) elif request.method=='POST': nid=request.POST.get('id') u=request.POST.get('username') p=request.POST.get('password') models.UserInfo.objects.filter(id=nid).update(username=u,password=p) return redirect('/cmdb/user_detail/') def user_detail(request,nid): obj=models.UserInfo.objects.filter(id=nid).first() return render(request,'user_detail.html',{'obj':obj}) def login(request): #models.UserGroup.objects.create(caption='DBA') if request.method=="GET": return render(request,'login.html') elif request.method=="POST": #数据库中执行 select 判断用户名和密码是否中确 u=request.POST.get('user') p=request.POST.get('pwd') #count=models.UserInfo.objects.filter(username=u,password=p).count() 也可以,但是不经常用 obj=models.UserInfo.objects.filter(username=u,password=p).first() #print(obj) #下面意思:如果obj为真 if obj: return redirect('/cmdb/index/') else: return render(request,'login.html') else: return redirect('/index/') def orm(request): #创建 #models.UserInfo.objects.create(username='root',password='123',) # obj=models.UserInfo(username='bob',password='456') # obj.save() # dic={'username':'jack','password':'789'} # models.UserInfo.objects.create(dic) #查 result=models.UserInfo.objects.all() #result=models.UserInfo.objects.filter(username='root',password=999) # #删除: #models.UserInfo.objects.filter().delete() #更新 #models.UserInfo.objects.all().update(password=888) # obj=models.UserInfo.objects.filter(id=3) # for i in obj: # print(i.username) # return HttpResponse('orm') # from django.views import View # # class Home(View): # def dispatch(self, request, *args, **kwargs): # print('before')#kkkk # result=super(Home,self).dispatch(request, *args, **kwargs) # print('after') # return result # # def get(self,request): # print(request.method) # return render(request,'home.html') # def post(self,request): # print(request.method) # return render(request,'home.html') templates/index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> body{ margin: 0; } .menu{ display: block; padding: 5px; } </style> </head> <body> <div style="height: 48px;background-color: black;color: white"> 欢迎到来 </div> <div> <div style="position: absolute;top: 48px;bottom: 0;left: 0;width: 200px;background-color: aquamarine"> <a class="menu" href="/cmdb/user_info/">用户管理</a> <a class="menu" href="/cmdb/user_group/">用户组管理</a> </div> </div> <div style="position: absolute;top: 48px;bottom: 0;left: 210px;width: 0;overflow: auto"> </div> </body> </html> templates/login.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body > <form action="/cmdb/login/" method="POST" enctype="multipart/form-data"> <p> <input type="text" name="user" placeholder="用户名"> </p> <p> <input type="password" name="pwd" placeholder="密码"> </p> <input type="submit" value="提交"> </form> </body> </html> templates/user_info.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> body { margin: 0; } .menu { display: block; padding: 5px; } </style> </head> <body> <div style="height: 48px;background-color: black;color: white"> 欢迎到来 </div> <div> <div style="position: absolute;top: 48px;bottom: 0;left: 0;width: 200px;background-color: aquamarine"> <a class="menu" href="/cmdb/user_info/">用户管理</a> <a class="menu" href="/cmdb/user_group/">用户组管理</a> </div> </div> <div style="position: absolute;top: 48px;bottom: 0;left: 210px;width: 700px;overflow: auto;background-color: antiquewhite"> <h3>添加用户</h3> <form action="/cmdb/user_info/" method="post"> <input type="text" name="user"/> <input type="text" name="pwd"/> <input type="submit" value="添加"/> </form> <h3>用户列表</h3> <ul> {% for row in user_list %} <li><a href="/cmdb/userdetail-{{ row.id }}/">{{ row.username }} </a> | <a href="/cmdb/userdel-{{ row.id }}/"> 删除 </a> | <a href="/cmdb/useredit-{{ row.id }}/"> 编辑 </a> </li> {% endfor %} </ul> </div> </body> </html> templates/user_detail.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> body{ margin: 0; } .menu{ display: block; padding: 5px; } </style> </head> <body> <div style="height: 48px;background-color: black;color: white"> 欢迎到来 </div> <div> <div style="position: absolute;top: 48px;bottom: 0;left: 0;width: 200px;background-color: aquamarine"> <a class="menu" href="/cmdb/user_info/">用户管理</a> <a class="menu" href="/cmdb/user_group/">用户组管理</a> </div> </div> <div style="position: absolute;top: 48px;bottom: 0;left: 210px;width: 700px;overflow: auto;background-color: antiquewhite"> <h1>用户详细信息</h1> <h2>{{ obj.id }}</h2> <h2>{{ obj.name }}</h2> <h2>{{ obj.password }}</h2> </div> </body> </html> templates/user_edit.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>编辑用户</h1> <form method="post" action="/cmdb/useredit-{{ obj.id }}/"> <input style="display: none" type="text" name="id" value="{{ obj.id }}" /> <input type="text" name="username" value="{{ obj.username }}" /> <input type="text" name="password" value="{{ obj.password }}" /> <input type="submit" name="提交" > </form> </body> </html> 19周 16章 Django 字段类型介绍 字符串、数字、时间、二进制、自增 # Create your models here. class UserGroup(models.Model): uid=models.AutoField(primary_key=True) caption=models.CharField(max_length=50) class UserInfo(models.Model): #自动创建 id列 自增主键 username=models.CharField(max_length=32) password=models.CharField(max_length=60) email=models.CharField(max_length=60) #gender=models.CharField(max_length=60,null=True) test=models.EmailField(max_length=20,null=True) 更新表: password=models.CharField(max_length=60) make manage.py makemigrations make manage.py migrate 增加表: 1、 email=models.CharField(max_length=60) 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py Select an option: 1 Please enter the default value now, as valid Python The datetime and django.utils.timezone modules are available, so you can do e.g. timezone.now Type 'exit' to exit this prompt Invalid input: name 'jack' is not defined >>> 'bob' make manage.py makemigrations make manage.py migrate 然后关掉软件,重新打开才生效。 2、、 gender=models.CharField(max_length=60,null=True) make manage.py makemigrations make manage.py migrate 删除表: #gender=models.CharField(max_length=60,null=True) make manage.py makemigrations make manage.py migrate 自增: class UserGroup(models.Model): uid=models.AutoField(primary_key=True) caption=models.CharField(max_length=50) 19周 17章:Django ORM字段参数介绍: 这些都是在Django admin里面使用 null 数据库中字段是否可以为空 db_column 数据库中字段的列名 db_tablespace default 数据库中字段的默认值 primary_key 数据库中字段是否为主键 db_index 数据库中字段是否可以建立索引 unique 数据库中字段是否可以建立唯一索引 unique_for_date 数据库中字段【日期】部分是否可以建立唯一索引 unique_for_month 数据库中字段【月】部分是否可以建立唯一索引 unique_for_year 数据库中字段【年】部分是否可以建立唯一索引 verbose_name Admin中显示的字段名称 blank Admin中是否允许用户输入为空 username=models.CharField(max_length=50,blank=True,verbose_name='用户名') editable Admin中是否可以编辑 help_text Admin中该字段的提示信息 choices Admin中显示选择框的内容,用不变动的数据放在内存中从而避免跨表操作 如:gf = models.IntegerField(choices=[(0, '何穗'),(1, '大表姐'),],default=1) error_messages 自定义错误信息(字典类型),从而定制想要显示的错误信息; 字典健:null, blank, invalid, invalid_choice, unique, and unique_for_date 如:{'null': "不能为空.", 'invalid': '格式错误'} validators 自定义错误验证(列表类型),从而定制想要的验证规则 auto_now uptime=models.DateTimeField(auto_now=True,null=True) 自动更新时间: 错误方式; obj=UserGroup.objects.filter(id=1).update(caption='CEO') 正确方式; obj=UserGroup.objects.filter(id=1).first() obj.caption="CEO" obj.save() choices :用在admin user_type_id=models.IntegerField(choices=user_type_choice,default=1) user_type_choice=( (1,'超级用户'), (2,'白金客户'), (3,'普通客户'), ) user_type_id=models.IntegerField(choices=user_type_choice,default=1) 19周 18章:Django ORM外键操作 外键的意思: 主要作用就是把两个数据库表连接起来,比如把员工组表、员工信息表给连接起来 注意python3.7外键的变化: user_group=models.ForeignKey("UserGroup",to_field='uid',default=1,on_delete=models.CASCADE) 注意:怎么取里面的值 row.user_group 是个对象 user_list=Userinfo.object.all() for row in user_list: print(row.user_group_id) = print(row.user_group.uid) print(row.user_group.caption) <ul> {% for row in user_list %} <li><a href="/cmdb/userdetail-{{ row.id }}/">{{ row.username }}</a> <span>{{ row.user_group.caption }}</span> </li> {% endfor %} </ul> 实例:接之前的,变动的如下: app01/models.py from django.db import models # Create your models here. class UserGroup(models.Model): uid=models.AutoField(primary_key=True) caption=models.CharField(max_length=50) ctime=models.DateTimeField(auto_now_add=True,null=True) uptime=models.DateTimeField(auto_now=True,null=True) #username=models.CharField(max_length=50,blank=True) class UserInfo(models.Model): #自动创建 id列 自增主键 username=models.CharField(max_length=32) password=models.CharField(max_length=60) email=models.CharField(max_length=60) #gender=models.CharField(max_length=60,null=True) test=models.EmailField(max_length=20,null=True) username=models.CharField(max_length=50,blank=True,verbose_name='用户名') user_group=models.ForeignKey("UserGroup",to_field='uid',default=1,on_delete=models.CASCADE) user_type_choice=( (1,'超级用户'), (2,'白金客户'), (3,'普通客户'), ) user_type_id=models.IntegerField(choices=user_type_choice,default=1) templates/user_info.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> body { margin: 0; } .menu { display: block; padding: 5px; } </style> </head> <body> <div style="height: 48px;background-color: black;color: white"> 欢迎到来 </div> <div> <div style="position: absolute;top: 48px;bottom: 0;left: 0;width: 200px;background-color: aquamarine"> <a class="menu" href="/cmdb/user_info/">用户管理</a> <a class="menu" href="/cmdb/user_group/">用户组管理</a> </div> </div> <div style="position: absolute;top: 48px;bottom: 0;left: 210px;width: 700px;overflow: auto;background-color: antiquewhite"> <h3>添加用户</h3> <form action="/cmdb/user_info/" method="post"> <input type="text" name="user"/> <input type="text" name="pwd"/> <input type="submit" value="添加"/> </form> <h3>用户列表</h3> <ul> {% for row in user_list %} <li><a href="/cmdb/userdetail-{{ row.id }}/">{{ row.username }} </a> | <span>{{ row.user_group.caption }}</span> <a href="/cmdb/userdel-{{ row.id }}/"> 删除 </a> | <a href="/cmdb/useredit-{{ row.id }}/"> 编辑 </a> </li> {% endfor %} </ul> </div> </body> </html> 第19章/urls.py """第19章 URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from app01 import views from django.conf.urls import url from django.conf.urls import url,include import urllib urlpatterns = [ path('login/', views.login), path('index/', views.index,), path('user_info/', views.user_info,), url(r'^userdetail-(?P<nid>\d+)/', views.user_detail,), url(r'^userdel-(?P<nid>\d+)/', views.user_del,), url(r'^useredit-(?P<nid>\d+)/', views.user_edit,), path('orm/', views.orm), ] 19周 19章: 外键实现增加用户(含select标签) 注意下面多个是这么写:弄得好苦 return render(request,'user_info.html',{'user_list':user_list,"group_list":group_list}) app01/views.py from django.shortcuts import render from django.shortcuts import HttpResponse from django.shortcuts import redirect from app01 import models import urllib # Create your views here. # USER_DICT={ # 'k1':'root1', # 'k2':'root2', # 'k3':'root3', # 'k4':'root4', # } USER_DICT={ '1':{'name':'root1','email':'root@123.com'}, '2':{'name':'root2','email':'root@123.com'}, '3':{'name':'root3','email':'root@123.com'}, '4':{'name':'root4','email':'root@123.com'} } def index(request): return render(request,'index.html') def user_info(request): if request.method=="GET": user_list=models.UserInfo.objects.all() group_list=models.UserGroup.objects.all() return render(request,'user_info.html',{'user_list':user_list,"group_list":group_list}) elif request.method=="POST": u=request.POST.get('user') p=request.POST.get('pwd') models.UserInfo.objects.create(username=u,password=p) user_list=models.UserInfo.objects.all() #print(user_list.query) return render(request,'user_info.html',{'user_list':user_list}) def user_del(request,nid): models.UserInfo.objects.filter(id=nid).delete() return redirect('/cmdb/user_info/') def user_edit(request,nid): if request.method=='GET': obj=models.UserInfo.objects.filter(id=nid).first() return render(request,'user_edit.html',{'obj':obj}) elif request.method=='POST': nid=request.POST.get('id') u=request.POST.get('username') p=request.POST.get('password') models.UserInfo.objects.filter(id=nid).update(username=u,password=p) return redirect('/cmdb/user_detail/') def user_detail(request,nid): obj=models.UserInfo.objects.filter(id=nid).first() return render(request,'user_detail.html',{'obj':obj}) def login(request): #models.UserGroup.objects.create(caption='DBA') if request.method=="GET": return render(request,'login.html') elif request.method=="POST": #数据库中执行 select 判断用户名和密码是否中确 u=request.POST.get('user') p=request.POST.get('pwd') #count=models.UserInfo.objects.filter(username=u,password=p).count() 也可以,但是不经常用 obj=models.UserInfo.objects.filter(username=u,password=p).first() #print(obj) #下面意思:如果obj为真 if obj: return redirect('/cmdb/index/') else: return render(request,'login.html') else: return redirect('/index/') def orm(request): #创建 #models.UserInfo.objects.create(username='root',password='123',) # obj=models.UserInfo(username='bob',password='456') # obj.save() # dic={'username':'jack','password':'789'} # models.UserInfo.objects.create(dic) #查 result=models.UserInfo.objects.all() #result=models.UserInfo.objects.filter(username='root',password=999) models.UserInfo.objects.create( username='root1', password=123, email='123@.com', test='ceshi', user_group_id=1, ) #删除: #models.UserInfo.objects.filter().delete() #更新 #models.UserInfo.objects.all().update(password=888) # obj=models.UserInfo.objects.filter(id=3) # for i in obj: # print(i.username) # return HttpResponse('orm') # from django.views import View # # class Home(View): # def dispatch(self, request, *args, **kwargs): # print('before')#kkkk # result=super(Home,self).dispatch(request, *args, **kwargs) # print('after') # return result # # def get(self,request): # print(request.method) # return render(request,'home.html') # def post(self,request): # print(request.method) # return render(request,'home.html') app01/models.py from django.db import models # Create your models here. class UserGroup(models.Model): uid=models.AutoField(primary_key=True) caption=models.CharField(max_length=50) ctime=models.DateTimeField(auto_now_add=True,null=True) uptime=models.DateTimeField(auto_now=True,null=True) #username=models.CharField(max_length=50,blank=True) class UserInfo(models.Model): #自动创建 id列 自增主键 username=models.CharField(max_length=32) password=models.CharField(max_length=60) email=models.CharField(max_length=60) #gender=models.CharField(max_length=60,null=True) test=models.EmailField(max_length=20,null=True) username=models.CharField(max_length=50,blank=True,verbose_name='用户名') user_group=models.ForeignKey("UserGroup",to_field='uid',default=1,on_delete=models.CASCADE) user_type_choice=( (1,'超级用户'), (2,'白金客户'), (3,'普通客户'), ) user_type_id=models.IntegerField(choices=user_type_choice,default=1) app01/urls.py """第19章 URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from app01 import views from django.conf.urls import url from django.conf.urls import url,include import urllib urlpatterns = [ path('login/', views.login), path('index/', views.index,), path('user_info/', views.user_info,), url(r'^userdetail-(?P<nid>\d+)/', views.user_detail,), url(r'^userdel-(?P<nid>\d+)/', views.user_del,), url(r'^useredit-(?P<nid>\d+)/', views.user_edit,), path('orm/', views.orm), ] templates/user_info.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> body { margin: 0; } .menu { display: block; padding: 5px; } </style> </head> <body> <div style="height: 48px;background-color: black;color: white"> 欢迎到来 </div> <div> <div style="position: absolute;top: 48px;bottom: 0;left: 0;width: 200px;background-color: aquamarine"> <a class="menu" href="/cmdb/user_info/">用户管理</a> <a class="menu" href="/cmdb/user_group/">用户组管理</a> </div> </div> <div style="position: absolute;top: 48px;bottom: 0;left: 210px;width: 700px;overflow: auto;background-color: antiquewhite"> <h3>添加用户</h3> <form action="/cmdb/user_info/" method="post"> <input type="text" name="user"/> <input type="text" name="pwd"/> <select name="group_id"> {% for item in group_list %} <option value="{{ item.uid }}">{{ item.caption }}</option> {% endfor %} </select> <input type="submit" value="添加"/> </form> <h3>用户列表</h3> <ul> {% for row in user_list %} <li><a href="/cmdb/userdetail-{{ row.id }}/">{{ row.username }} </a> | <span>{{ row.user_group.caption }}</span> <a href="/cmdb/userdel-{{ row.id }}/"> 删除 </a> | <a href="/cmdb/useredit-{{ row.id }}/"> 编辑 </a> </li> {% endfor %} </ul> </div> </body> </html> templates/index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> body{ margin: 0; } .menu{ display: block; padding: 5px; } </style> </head> <body> <div style="height: 48px;background-color: black;color: white"> 欢迎到来 </div> <div> <div style="position: absolute;top: 48px;bottom: 0;left: 0;width: 200px;background-color: aquamarine"> <a class="menu" href="/cmdb/user_info/">用户管理</a> <a class="menu" href="/cmdb/user_group/">用户组管理</a> </div> </div> <div style="position: absolute;top: 48px;bottom: 0;left: 210px;width: 0;overflow: auto"> </div> </body> </html> templates/login.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body > <form action="/cmdb/login/" method="POST" enctype="multipart/form-data"> <p> <input type="text" name="user" placeholder="用户名"> </p> <p> <input type="password" name="pwd" placeholder="密码"> </p> <input type="submit" value="提交"> </form> </body> </html> templates/user_detail.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> body{ margin: 0; } .menu{ display: block; padding: 5px; } </style> </head> <body> <div style="height: 48px;background-color: black;color: white"> 欢迎到来 </div> <div> <div style="position: absolute;top: 48px;bottom: 0;left: 0;width: 200px;background-color: aquamarine"> <a class="menu" href="/cmdb/user_info/">用户管理</a> <a class="menu" href="/cmdb/user_group/">用户组管理</a> </div> </div> <div style="position: absolute;top: 48px;bottom: 0;left: 210px;width: 700px;overflow: auto;background-color: antiquewhite"> <h1>用户详细信息</h1> <h2>{{ obj.id }}</h2> <h2>{{ obj.name }}</h2> <h2>{{ obj.password }}</h2> </div> </body> </html> templates/user_edit.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>编辑用户</h1> <form method="post" action="/cmdb/useredit-{{ obj.id }}/"> <input style="display: none" type="text" name="id" value="{{ obj.id }}" /> <input type="text" name="username" value="{{ obj.username }}" /> <input type="text" name="password" value="{{ obj.password }}" /> <input type="submit" name="提交" > </form> </body> </html> 访问: http://127.0.0.1:8000/cmdb/user_info/ 第20章 03节 Django 一对多创建介绍 第20章 04节 Django 创建 一对多表结构 1、先创建一个工程 app01/models.py from django.db import models # Create your models here. class Business(models.Model): caption=models.CharField(max_length=32) class Host(models.Model): nid=models.AutoField(primary_key=True) hostname=models.CharField(max_length=32,db_index=True) ip=models.GenericIPAddressField(protocol="both",max_length=32,db_index=True) port=models.IntegerField() b=models.ForeignKey(to="Business",to_field='id',on_delete=models.CASCADE) 第20章-05 获取单表数据的三种方式 models.Business.objects.all() 是个对象 models.Business.objects.values('id','caption') #[{'id':'1','caption':'运维','code':'sa'}] values 是个字典 models.Business.objects.values_list('id','caption') #[(1,运维),(2,市场)] values_list 是个元组 第20章/settings.py """ Django settings for 第20章 project. Generated by 'django-admin startproject' using Django 2.0.3. For more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'u#@z=2@*h^sph5$uqwo+gwgml#ivnq&l@b7-9jg8ve@pmv4z_6' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app01', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', #'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = '第20章.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = '第20章.wsgi.application' # Database # https://docs.djangoproject.com/en/2.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.0/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS=( os.path.join(BASE_DIR,'static'), ) app01/models.py from django.db import models # Create your models here. class Business(models.Model): caption=models.CharField(max_length=32) code=models.CharField(max_length=32,null=True) class Host(models.Model): nid=models.AutoField(primary_key=True) hostname=models.CharField(max_length=32,db_index=True) ip=models.GenericIPAddressField(protocol="both",max_length=32,db_index=True) port=models.IntegerField() b=models.ForeignKey(to="Business",to_field='id',on_delete=models.CASCADE) 第20章/urls.py """第20章 URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from app01 import views from django.conf.urls import url urlpatterns = [ path('admin/', admin.site.urls), #path('business/', views.business,), url(r'^business/$', views.business,), ] app01/views.py from django.shortcuts import render # Create your views here. from app01 import models def business(request): v1=models.Business.objects.all() v2=models.Business.objects.values('id','caption') #[{'id':'1','caption':'运维','code':'sa'}] values 对象是个字典 v3=models.Business.objects.values_list('id','caption') #[(1,运维),(2,市场)] values_list 对象是个元组 return render(request,'business.html',{'v1':v1,'v2':v2,'v3':v3}) templates/business.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>业务线列表(对象)</h1> <ul> {% for row in v1 %} <li>{{ row.id }} - {{ row.caption }} - {{ row.code }}</li> {% endfor %} </ul> <h1>业务线列表(字典)</h1> <ul> {% for row in v2 %} <li>{{ row.id }} - {{ row.caption }} </li> {% endfor %} </ul> <h1>业务线列表(元组)</h1> <ul> {% for row in v3 %} <li>{{ row.0 }} - {{ row.1 }} </li> {% endfor %} </ul> </body> </html> 第20章-06 一对多跨表操作 实例接上面: 第20章/settings.py """ Django settings for 第20章 project. Generated by 'django-admin startproject' using Django 2.0.3. For more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'u#@z=2@*h^sph5$uqwo+gwgml#ivnq&l@b7-9jg8ve@pmv4z_6' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app01', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', #'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = '第20章.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = '第20章.wsgi.application' # Database # https://docs.djangoproject.com/en/2.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.0/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS=( os.path.join(BASE_DIR,'static'), ) app01/models.py from django.db import models # Create your models here. class Business(models.Model): caption=models.CharField(max_length=32) code=models.CharField(max_length=32,null=True) class Host(models.Model): nid=models.AutoField(primary_key=True) hostname=models.CharField(max_length=32,db_index=True) ip=models.GenericIPAddressField(protocol="both",max_length=32,db_index=True) port=models.IntegerField() b=models.ForeignKey(to="Business",to_field='id',on_delete=models.CASCADE) 第20章/urls.py """第20章 URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from app01 import views from django.conf.urls import url urlpatterns = [ path('admin/', admin.site.urls), #path('business/', views.business,), url(r'^business/$', views.business,), url(r'^host/$', views.host,), ] app01/views.py from django.shortcuts import render,HttpResponse # Create your views here. from app01 import models def business(request): v1=models.Business.objects.all() v2=models.Business.objects.values('id','caption') #[{'id':'1','caption':'运维','code':'sa'}] values 是个字典 v3=models.Business.objects.values_list('id','caption') #[(1,运维),(2,市场)] values_list 是个元组 return render(request,'business.html',{'v1':v1,'v2':v2,'v3':v3}) def host(request): v1=models.Host.objects.filter(nid__gt=0) return render(request,'host.html',{'v1':v1}) templates/business.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>业务线列表(对象)</h1> <ul> {% for row in v1 %} <li>{{ row.id }} - {{ row.caption }} - {{ row.code }}</li> {% endfor %} </ul> <h1>业务线列表(字典)</h1> <ul> {% for row in v2 %} <li>{{ row.id }} - {{ row.caption }} </li> {% endfor %} </ul> <h1>业务线列表(元组)</h1> <ul> {% for row in v3 %} <li>{{ row.0 }} - {{ row.1 }} </li> {% endfor %} </ul> </body> </html> templates/host.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>业务线列表</h1> <table border="1"> <thead> <tr> <th>主机名</th> <th>ip地址</th> <th>端口</th> <th>业务线名称</th> </tr> </thead> <tbody> {% for row in v1 %} <tr ht_d="{{ row.nid }}" b_id="{{ row.b.id }}"> <th>{{ row.hostname }}</th> <th>{{ row.ip }}</th> <th>{{ row.port }}</th> <th>{{ row.b.caption }}</th> </tr> {% endfor %} </tbody> </table> </body> </html> 第20周-07 一对多块表操作的三种方式 接上面: app01/views.py from django.shortcuts import render,HttpResponse # Create your views here. from app01 import models def business(request): v1=models.Business.objects.all() # for row in v1: # print(row.id,row.caption) v2=models.Business.objects.values('id','caption') # for row in v2: # print(row['id'],row['caption']) #[{'id':'1','caption':'运维','code':'sa'}] values 是个字典 v3=models.Business.objects.values_list('id','caption') #[(1,运维),(2,市场)] values_list 是个元组 return render(request,'business.html',{'v1':v1,'v2':v2,'v3':v3}) #return HttpResponse('ok') def host(request): v1=models.Host.objects.filter(nid__gt=0) # for row in v1: # print(row.nid,row.hostname) v2=models.Host.objects.filter(nid__gt=0).values('nid','hostname','b_id','b__caption') # for row in v2: # print(row['nid'],row['hostname'],row['b_id']) v3=models.Host.objects.filter(nid__gt=0).values_list('nid','hostname','b_id','b__caption') # for row in v3: # print(row[0],row[1]) #return HttpResponse('ok') return render(request,'host.html',{'v1':v1,'v2':v2,'v3':v3}) templates/host.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>主机列表(列表)</h1> <table border="1"> <thead> <tr> <th>主机名</th> <th>ip地址</th> <th>端口</th> <th>业务线名称</th> </tr> </thead> <tbody> {% for row in v1 %} <tr ht-d="{{ row.nid }}" b-id="{{ row.b.id }}"> <th>{{ row.hostname }}</th> <th>{{ row.ip }}</th> <th>{{ row.port }}</th> <th>{{ row.b.caption }}</th> </tr> {% endfor %} <tbody> </table> <h1>主机列表(字典)</h1> <table border="1"> <thead> <tr> <th>主机名</th> <th>ip地址</th> <th>端口</th> <th>业务线名称</th> </tr> </thead> <tbody> {% for row in v1 %} <tr ht-d="{{ row.nid }}" b-id="{{ row.b.id }}"> <th>{{ row.hostname }}</th> <th>{{ row.ip }}</th> <th>{{ row.port }}</th> <th>{{ row.b.caption }}</th> </tr> {% endfor %} <tbody> </table> <h1>业务线列表*(元组)</h1> <table border="1"> <thead> <tr> <th>主机名</th> <th>ip地址</th> </tr> </thead> <tbody> {% for row in v3 %} <tr ht-d="{{ row.0 }}" b-id="{{ row.2 }}"> <th>{{ row.1 }}</th> <th>{{ row.3 }}</th> </tr> {% endfor %} <tbody> </table> </body> </html> 第20周-09 增加一对多数据示例; --添加主机--用模态对话框演示: 接上面: app01/views.py from django.shortcuts import render,HttpResponse,redirect # Create your views here. from app01 import models def business(request): v1=models.Business.objects.all() # for row in v1: # print(row.id,row.caption) v2=models.Business.objects.values('id','caption') # for row in v2: # print(row['id'],row['caption']) #[{'id':'1','caption':'运维','code':'sa'}] values 是个字典 v3=models.Business.objects.values_list('id','caption') #[(1,运维),(2,市场)] values_list 是个元组 return render(request,'business.html',{'v1':v1,'v2':v2,'v3':v3}) #return HttpResponse('ok') def host(request): if request.method=='GET': b_list=models.Business.objects.all() elif request.method=='POST': h=request.POST.get('hostname') i=request.POST.get('ip') p=request.POST.get('port') b=request.POST.get('b_id') models.Host.objects.create(hostname=h,ip=i,port=p,b_id=b) return redirect('/host/') v1=models.Host.objects.filter(nid__gt=0) # for row in v1: # print(row.nid,row.hostname) v2=models.Host.objects.filter(nid__gt=0).values('nid','hostname','b_id','b__caption') # for row in v2: # print(row['nid'],row['hostname'],row['b_id']) v3=models.Host.objects.filter(nid__gt=0).values_list('nid','hostname','b_id','b__caption') # for row in v3: # print(row[0],row[1]) #return HttpResponse('ok') return render(request,'host.html',{'v1':v1,'v2':v2,'v3':v3,'b_list':b_list}) templates/host.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .hide { display: none; } .shade { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: black; opacity: 0.6; z-index: 100; } .add-modal { position: fixed; height: 300px; width: 400px; top: 100px; left: 50%; z-index: 101; border: 1px solid red; background: white; margin-left: -200px; } </style> </head> <body> <h1>主机列表(列表)</h1> <div> <input id="add_host" type="button" value="添加"> </div> <table border="1"> <thead> <tr> <th>序号</th> <th>主机名</th> <th>ip地址</th> <th>端口</th> <th>业务线名称</th> </tr> </thead> <tbody> {% for row in v1 %} <tr ht-d="{{ row.nid }}" b-id="{{ row.b.id }}"> <th>{{ forloop.counter }}</th> <th>{{ row.hostname }}</th> <th>{{ row.ip }}</th> <th>{{ row.port }}</th> <th>{{ row.b.caption }}</th> </tr> {% endfor %} <tbody> </table> <h1>主机列表(字典)</h1> <table border="1"> <thead> <tr> <th>主机名</th> <th>ip地址</th> <th>端口</th> <th>业务线名称</th> </tr> </thead> <tbody> {% for row in v1 %} <tr ht-d="{{ row.nid }}" b-id="{{ row.b.id }}"> <th>{{ row.hostname }}</th> <th>{{ row.ip }}</th> <th>{{ row.port }}</th> <th>{{ row.b.caption }}</th> </tr> {% endfor %} <tbody> </table> <h1>主机列表*(元组)</h1> <table border="1"> <thead> <tr> <th>主机名</th> <th>ip地址</th> </tr> </thead> <tbody> {% for row in v3 %} <tr ht-d="{{ row.0 }}" b-id="{{ row.2 }}"> <th>{{ row.1 }}</th> <th>{{ row.3 }}</th> </tr> {% endfor %} <tbody> </table> <div class="shade hide"></div> <div class="add-modal hide"> <form method="post" action="/host/"> <div class="group"> <input type="text" placeholder="主机名" name="hostname"> </div> <div class="group"> <input type="text" placeholder="IP" name="ip"> </div> <div class="group"> <input type="text" placeholder="端口" name="port"> </div> <div class="group"> <select name="b_id"> {% for op in b_list %} <option value="{{ op.id }}">{{ op.caption }}</option> {% endfor %} </select > <input type="submit" value="提交"> <input id="cancle" type="button" value="取消"> </div> </form> </div> <script src="/static/jquery-3.2.1.js"></script> <script> $(function () { $('#add_host').click(function () { $('.add-modal,.shade').removeClass('hide'); }); $('#cancle').click(function(){ $('.add-modal,.shade').addClass('hide'); }) }) </script> </body> </html> 第20周-09 初识Ajax :返回另一个界面,弹出一个框 接上面: templates/host.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .hide { display: none; } .shade { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: black; opacity: 0.6; z-index: 100; } .add-modal { position: fixed; height: 300px; width: 400px; top: 100px; left: 50%; z-index: 101; border: 1px solid red; background: white; margin-left: -200px; } </style> </head> <body> <h1>主机列表(列表)</h1> <div> <input id="add_host" type="button" value="添加"> </div> <table border="1"> <thead> <tr> <th>序号</th> <th>主机名</th> <th>ip地址</th> <th>端口</th> <th>业务线名称</th> </tr> </thead> <tbody> {% for row in v1 %} <tr ht-d="{{ row.nid }}" b-id="{{ row.b.id }}"> <th>{{ forloop.counter }}</th> <th>{{ row.hostname }}</th> <th>{{ row.ip }}</th> <th>{{ row.port }}</th> <th>{{ row.b.caption }}</th> </tr> {% endfor %} <tbody> </table> <h1>主机列表(字典)</h1> <table border="1"> <thead> <tr> <th>主机名</th> <th>ip地址</th> <th>端口</th> <th>业务线名称</th> </tr> </thead> <tbody> {% for row in v1 %} <tr ht-d="{{ row.nid }}" b-id="{{ row.b.id }}"> <th>{{ row.hostname }}</th> <th>{{ row.ip }}</th> <th>{{ row.port }}</th> <th>{{ row.b.caption }}</th> </tr> {% endfor %} <tbody> </table> <h1>主机列表*(元组)</h1> <table border="1"> <thead> <tr> <th>主机名</th> <th>ip地址</th> </tr> </thead> <tbody> {% for row in v3 %} <tr ht-d="{{ row.0 }}" b-id="{{ row.2 }}"> <th>{{ row.1 }}</th> <th>{{ row.3 }}</th> </tr> {% endfor %} <tbody> </table> <div class="shade hide"></div> <div class="add-modal hide"> <form method="post" action="/host/"> <div class="group"> <input id="host" type="text" placeholder="主机名" name="hostname"> </div> <div class="group"> <input id="ip" type="text" placeholder="IP" name="ip"> </div> <div class="group"> <input id="port" type="text" placeholder="端口" name="port"> </div> <div class="group"> <select id="sel" name="b_id"> {% for op in b_list %} <option value="{{ op.id }}">{{ op.caption }}</option> {% endfor %} </select > <input type="submit" value="提交"> <a id="ajax_submit" style="display:inline-block;padding: 5px;background: blue;color: white">悄悄提交</a> <input id="cancle" type="button" value="取消"> </div> </form> </div> <script src="/static/jquery-3.2.1.js"></script> <script> $(function () { $('#add_host').click(function () { $('.add-modal,.shade').removeClass('hide'); }); $('#cancle').click(function(){ $('.add-modal,.shade').addClass('hide'); }); $('#ajax_submit').click(function(){ $.ajax({ url:"/test_ajax/", type:"POST", data:{'hostname':$('#host').val(),'ip':$('#ip').val(),'port':$('#port').val(),'b_id':$('#sel').val()}, success:function(data){ if(data=='ok'){ location.reload() }else { alert(data) } } }) }) }) </script> </body> </html> 第20章/urls.py """第20章 URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from app01 import views from django.conf.urls import url urlpatterns = [ path('admin/', admin.site.urls), #path('business/', views.business,), url(r'^business/$', views.business,), url(r'^host/$', views.host,), url(r'^test_ajax/$', views.test_ajax,), ] app01/views.py from django.shortcuts import render,HttpResponse,redirect # Create your views here. from app01 import models def business(request): v1=models.Business.objects.all() # for row in v1: # print(row.id,row.caption) v2=models.Business.objects.values('id','caption') # for row in v2: # print(row['id'],row['caption']) #[{'id':'1','caption':'运维','code':'sa'}] values 是个字典 v3=models.Business.objects.values_list('id','caption') #[(1,运维),(2,市场)] values_list 是个元组 return render(request,'business.html',{'v1':v1,'v2':v2,'v3':v3}) #return HttpResponse('ok') def host(request): v1=models.Host.objects.filter(nid__gt=0) # for row in v1: # print(row.nid,row.hostname) v2=models.Host.objects.filter(nid__gt=0).values('nid','hostname','b_id','b__caption') # for row in v2: # print(row['nid'],row['hostname'],row['b_id']) v3=models.Host.objects.filter(nid__gt=0).values_list('nid','hostname','b_id','b__caption') # for row in v3: # print(row[0],row[1]) #return HttpResponse('ok') if request.method=='GET': b_list=models.Business.objects.all() elif request.method=='POST': h=request.POST.get('hostname') i=request.POST.get('ip') p=request.POST.get('port') b=request.POST.get('b_id') models.Host.objects.create(hostname=h,ip=i,port=p,b_id=b) return redirect('/host/') return render(request,'host.html',{'v1':v1,'v2':v2,'v3':v3,'b_list':b_list}) def test_ajax(request): print(request.method,request.POST) h=request.POST.get('hostname') i=request.POST.get('ip') p=request.POST.get('port') b=request.POST.get('b_id') if h and len(h) > 5: models.Host.objects.create(hostname=h,ip=i,port=p,b_id=b) return HttpResponse('ok') else: return HttpResponse('输入太短') 访问:http://127.0.0.1:8000/host/ 第20周-10 Ajax内容整理; 接上面: templates/host.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .hide { display: none; } .shade { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: black; opacity: 0.6; z-index: 100; } .add-modal { position: fixed; height: 300px; width: 400px; top: 100px; left: 50%; z-index: 101; border: 1px solid red; background: white; margin-left: -200px; } </style> </head> <body> <h1>主机列表(列表)</h1> <div> <input id="add_host" type="button" value="添加"> </div> <table border="1"> <thead> <tr> <th>序号</th> <th>主机名</th> <th>ip地址</th> <th>端口</th> <th>业务线名称</th> </tr> </thead> <tbody> {% for row in v1 %} <tr ht-d="{{ row.nid }}" b-id="{{ row.b.id }}"> <th>{{ forloop.counter }}</th> <th>{{ row.hostname }}</th> <th>{{ row.ip }}</th> <th>{{ row.port }}</th> <th>{{ row.b.caption }}</th> </tr> {% endfor %} <tbody> </table> <h1>主机列表(字典)</h1> <table border="1"> <thead> <tr> <th>主机名</th> <th>ip地址</th> <th>端口</th> <th>业务线名称</th> </tr> </thead> <tbody> {% for row in v1 %} <tr ht-d="{{ row.nid }}" b-id="{{ row.b.id }}"> <th>{{ row.hostname }}</th> <th>{{ row.ip }}</th> <th>{{ row.port }}</th> <th>{{ row.b.caption }}</th> </tr> {% endfor %} <tbody> </table> <h1>主机列表*(元组)</h1> <table border="1"> <thead> <tr> <th>主机名</th> <th>ip地址</th> </tr> </thead> <tbody> {% for row in v3 %} <tr ht-d="{{ row.0 }}" b-id="{{ row.2 }}"> <th>{{ row.1 }}</th> <th>{{ row.3 }}</th> </tr> {% endfor %} <tbody> </table> <div class="shade hide"></div> <div class="add-modal hide"> <form method="post" action="/host/"> <div class="group"> <input id="host" type="text" placeholder="主机名" name="hostname"> </div> <div class="group"> <input id="ip" type="text" placeholder="IP" name="ip"> </div> <div class="group"> <input id="port" type="text" placeholder="端口" name="port"> </div> <div class="group"> <select id="sel" name="b_id"> {% for op in b_list %} <option value="{{ op.id }}">{{ op.caption }}</option> {% endfor %} </select> <input type="submit" value="提交"> <a id="ajax_submit" style="display:inline-block;padding: 5px;background: blue;color: white">悄悄提交</a> <input id="cancle" type="button" value="取消"> <span id="error_msg"></span> </div> </form> </div> <script src="/static/jquery-3.2.1.js"></script> <script> $(function () { $('#add_host').click(function () { $('.add-modal,.shade').removeClass('hide'); }); $('#cancle').click(function () { $('.add-modal,.shade').addClass('hide'); }); $('#ajax_submit').click(function () { $.ajax({ url: "/test_ajax/", type: "POST", data: { 'hostname': $('#host').val(), 'ip': $('#ip').val(), 'port': $('#port').val(), 'b_id': $('#sel').val() }, success: function (data) { var obj = JSON.parse(data); if (obj.status) { location.reload() } else { $('#error_msg').text(obj.error); } } }) }) }) </script> </body> </html> app01/views.py from django.shortcuts import render, HttpResponse, redirect # Create your views here. from app01 import models def business(request): v1 = models.Business.objects.all() # for row in v1: # print(row.id,row.caption) v2 = models.Business.objects.values('id', 'caption') # for row in v2: # print(row['id'],row['caption']) # [{'id':'1','caption':'运维','code':'sa'}] values 是个字典 v3 = models.Business.objects.values_list('id', 'caption') # [(1,运维),(2,市场)] values_list 是个元组 return render(request, 'business.html', {'v1': v1, 'v2': v2, 'v3': v3}) # return HttpResponse('ok') def host(request): v1 = models.Host.objects.filter(nid__gt=0) # for row in v1: # print(row.nid,row.hostname) v2 = models.Host.objects.filter(nid__gt=0).values('nid', 'hostname', 'b_id', 'b__caption') # for row in v2: # print(row['nid'],row['hostname'],row['b_id']) v3 = models.Host.objects.filter(nid__gt=0).values_list('nid', 'hostname', 'b_id', 'b__caption') # for row in v3: # print(row[0],row[1]) # return HttpResponse('ok') if request.method == 'GET': b_list = models.Business.objects.all() elif request.method == 'POST': h = request.POST.get('hostname') i = request.POST.get('ip') p = request.POST.get('port') b = request.POST.get('b_id') models.Host.objects.create(hostname=h, ip=i, port=p, b_id=b) return redirect('/host/') return render(request, 'host.html', {'v1': v1, 'v2': v2, 'v3': v3, 'b_list': b_list}) def test_ajax(request): import json ret={'status':True,'error':None,'data':None} try: h = request.POST.get('hostname') i = request.POST.get('ip') p = request.POST.get('port') b = request.POST.get('b_id') if h and len(h) > 5: models.Host.objects.create(hostname=h, ip=i, port=p, b_id=b) else: ret['status']=False ret['error']='太短' except Exception as e: ret['status']=False ret['error']='请求错误' return HttpResponse(json.dumps(ret)) 第20章/urls.py """第20章 URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from app01 import views from django.conf.urls import url urlpatterns = [ path('admin/', admin.site.urls), #path('business/', views.business,), url(r'^business/$', views.business,), url(r'^host/$', views.host,), url(r'^test_ajax/$', views.test_ajax,), ] 第20周-第11章节-Python3.5-编辑一对多示例 第21周-第05章节-Python3.5-视图获取用户请求相关信息以及请求头 from django.core.handlers.wsgi import WSGIRequest print(request.environ) for k,v in request.environ.items(): print(k,v) 第21周-第06章节-Python3.5-模板之继承 master.html 写好框架代码,然后在中间加上下面这句话,就可以被继承 <!DOCTYPE html> <html lang="en"> <head> .add-modal { position: fixed; height: 300px; width: 400px; top: 100px;} {% block css %}{% endblock %} <head> <body> 框架代码 {% block content %}{% endblock %} 框架代码 <script src="/static/jquery-3.2.1.js"></script> {% block js %} {% endblock %} <body> ceshi.html 注意:其他html想定制jss和css时候,模板文件需要先写好block的位置, 写css和js没有顺序分 导入重复用的框架代码: {% extends 'master.html' %} {% block title %}用户管理{% endblock %} {% block content %} <ul> {% for row in v1 %} <li>{{ row.id }} - {{ row.caption }} - {{ row.code }}</li> {% endfor %} </ul> {% endblock %} {% block js %} <script>内容</script> {% endblock %} {% block css %}内容 {%endblock %} 第21周-第07章节-Python3.5-模板之导入 在需要导入html的位置 加上:{% include tag.html %} 有多个就循环 第21周-第09章节-Python3.5-自定义 simple_tag