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} 


取交集



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 
    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

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 
    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://[email protected]: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://[email protected]: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
 at 0x01FA3800>




斐波拉契数列

除第一个和第二个之外 所有的数都是由前两个数相加之和。


def fib(max):
    n,a,b=0,0,1
    while n>> 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




def fib(max):
    n,a,b=0,0,1
    while n
    print(f.__next__())
StopIteration: done

Process finished with exit code 1




def fib(max):
    n,a,b=0,0,1
    while n>> bin(55)
'0b110111'



exec()  把字符串转成能够调用的对象


code="""
def fib(max):
    n,a,b=0,0,1
    while n>> 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__': , '__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 "", line 1, in 
    hash(rtyyuyu)
NameError: name 'rtyyuyu' is not defined
>>> hash(坎坎坷坷)
Traceback (most recent call last):
  File "", line 1, in 
    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': }



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模块


    
        2
        2008
        141100
        
        
    
    
        5
        2011
        59900
        
    
    
        69
        2011
        13600
        
        
            mail



        
    




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 
    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 
    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 
    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://[email protected]: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 
    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 
    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 
    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 
    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 
    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 
    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 
    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 
    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
我要开始接听电话
 ('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
我要开始接听电话
 ('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的内部标签






    
    Title


    
    老男孩







第十四周 第八章 html的body内部标签








    
    Title


    
    

klkklkkllkkkkkkk
kkkkkkkkkkkkkkklklk

555555555

8888888888

8888

8888

8888

8888

8888
8888
66666 66666 66666 老男孩       第十四周 第八章 chrome 查看html的基本样式 hello come on
hello
自然       第十四周 第十章 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 == '[email protected]' 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() 客户端: Title

第十四周 第十一章 html的body内标签input系列 Title

请选择性别:

男: 女:

爱好:

篮球: 足球: 拍球: 棒球:

技能

唱歌: 跳舞:

上传文件


第十四周 第十二章 html的body内标签多行文本以及下拉框 Title

请选择性别:

男: 女:

爱好:

篮球: 足球: 拍球: 棒球:

技能

唱歌: 跳舞:

上传文件


第十四周 第十三章 html的body内标签超链接 Title 第一章 第二章 第三章 第四章
第一章的内容
第二章的内容
第三章的内容
第四章的内容
第十四周 第十四章 html的body内标图片及表格 标准格式按照十五章 Title 美女
  • yyyy
  • yyyy
  • yyyy
  • yyyy
  1. xxx
  2. xxx
  3. xxx
  4. xxx
kkk
uuu
uuu
uuu
uuu
kkk
uuu
uuu
uuu
uuu
表格: Title
主机名 端口 操作
0.0.0.0 8080 查看信息 修改
0.0.0.0 8080 第二行,第3列
第十四周 第十五章 html的body内标图片及表格 标准格式按照这个 Title
表头1 表头1 表头1 表头1
1 1 1
1 1 1 1
1 1 1
1 1 1 1
1 1 1 1
第十四周 第十六章 html的body的fildest标签和lable标签 Title 底下情况基本不用 Title
登录
第十四周 第十八章 css选择器: id选择器:不常用 Title
fff
2
2
class选择器:最常用的方式: Title
fff
2
2
标签选择器: 注释:/*background-color: brown;*/ Title
fff
2
hhhhh
2
层级选择器: Title
fff
2
hhhhh
2
组合选择器: Title
fff
hhhhh
2
Title
fff
hhhhh
2
属性选择器: Title Title 第十四周 第十九章 css存在样式、优先级 叠加 Title
hhhhhhh
优先级: style 最优先 然后最下面的 然后最上面的 Title
hhhhhhh
css样式也可以写在单独文件中: 1.1 先写个 css文件: .c1 { background-color: yellow; color: yellow; } .c1 { font-size: 60px; color: black; } 1.2 再导入: Title
hhhhhhh
hhhhhhh
hhhhhhh
第十四周 第二十章:css边框以及其他常用样式: Title
hhhhhh
kkkkkk
第十四周 第二十一章节:css的float样式 Title
收藏本站

第十五周 第三章 css内容 position Title
返回顶部
Title
头部
内容
第十五周 第四章 css内容 position Title
kkkkk
hhhh
Title
第十五周 第五章 css内容 position 多层堆叠 Title
第十五周 第六章 css内容 overflow Title
第十五周 第七章 css内容 hover: Title
hhh
第十五周 第八章 css内容 backgroud; 点赞图标上下移动 Title
第十五周 第九章 css内容 backgroud; 登录框放个图标 Title
第十五周 第十一章节 javascript代码存在形式 1、直接写 2、从远程导入 3、要写在body的最后面 4、注释: 单行 // 多行: /* */ Title 第十五周 第十三章节: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 定时器: Title Title 一串文字一直循环 Title
欢迎顾客前来购买
第十五周 第十四章节 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() 删除 实例: Title
我的中国心
hhh kkkk tttt 运行: for(var i=1;i Title
a1
a2
a3
tag=document.getElementById('i1')
? a2 ?
? tag.className='c1'; "c1" tag
? a2 ?
? tag.classList ["c1", value: "c1"] tag.classList.add('c5') undefined tag
? a2 ?
? tag.classList.remove('c5') undefined tag
? a2 ?
?
点我
第十五周 第十九章节 模态对话框 Title
主机名 端口
192.168.1 4231
192.168.2 4232
192.168.3 4233

第十五周 第二十章节 全选、反选、取消 Title
选择 主机名 端口
192.168.1 4231
192.168.2 4232
192.168.3 4233

第十五周 第二十一章节 javascript 必须加分号 第十五周 第二十二章节 后台左侧菜单: Title
菜单1
内容1
内容2
内容3
菜单2
内容2
内容2
内容2
菜单3
内容3
内容3
内容3
菜单4
内容4
内容4
内容4
第十六周 第三章 css内容补充、后台管理页面 第十六周 第十七章 鼠标拿走在框里显示 请输入内容 第十六周 第十九章 创建标签,在标签下面再创建标签 第 十七周 03章节 jquery常用的就是讲的这些,其他的可以不会 jquery和dom之间转换 Title
123
$("#i1") jQuery.fn.init?[div#i1] document.getElementById('i1')
123
jquery转dom $("#i1")[0]
123
dom转jquery d=document.getElementById('i1')
123
$(d) jQuery.fn.init?[div#i1] 第17周 04章节 多选 反选 取消 1、组合选择标签: Title
f f
f
$('a,.c2,#i10') jQuery.fn.init(5)?[div#i10.c1, a, a, a, div.c2, prevObject: jQuery.fn.init(1)] 2、层级:选多个子标签 Title
f f
f
$('#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、属性选择器: Title
f f
f
$('[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; Title
选项 ip 端口
1.1.1.1 80
1.1.1.1 80
1.1.1.1 80
1.1.1.1 80
第17周 06章节 删选器2 点击后展开 绑定事件 兄弟标签 父标签 children标签 next()标签 preve()标签 find() 链式编程 Title
标题1
内容
标题2
内容
标题3
内容
第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]) Title
1.1.1.1 80 编辑 删除
1.1.1.1 80 编辑 删除
1.1.1.1 80 编辑 删除
1.1.1.1 80 编辑 删除
第17周 08章节 模态编程框(2)--弹出对话框 下一节完善 Title 添加
1.1.1.1 80 编辑 删除
1.1.1.2 80 编辑 删除
1.1.1.3 80 编辑 删除
1.1.1.4 80 编辑 删除
第17周 09章节 jquery样式及属性操作 --弹出对话框并且赋值 Title
hhhhhoooooouuuuu
$('#i1').html("

kkkkk

") 解析标签 $('#i1').text("

llllll

") 不解析标签 Title
hhhhhoooooouuuuu
$('#i2').val() $('#i2').val('999') Title 添加
1.1.1.1 80 编辑 删除
1.1.1.2 80 编辑 删除
1.1.1.3 80 编辑 删除
1.1.1.4 80 编辑 删除
第17周 10章节 模态编程 开关 属性操作: $('#i1').attr('type') $('#i1').removeAttr('name') $()prop $('#i2').prop('checked',true); Title
hhhhhhhhhh
$('#i1').attr('type') "button" $('#i1').attr('name','bob') $('#i1')[0] $('#i1').removeAttr('name') Title
hhhhhhhhhh
$('#i2').prop('checked',true); jQuery.fn.init?[input#i2] $('#i2').prop('checked',false); jQuery.fn.init?[input#i2] 第17周 11章节 tab菜单切换 添加ip 在中间添加一行 Title 添加
1.1.1.1 80 1.1.1.0 编辑 删除
1.1.1.2 80 1.1.1.0 编辑 删除
1.1.1.3 80 1.1.1.0 编辑 删除
1.1.1.4 80 1.1.1.0 编辑 删除
第17周 12章节 jquery内容操作 没写全 Title
内容1
内容2
内容3
第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('

hello

') 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 Title

正确访问: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 Title

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 Title

{{ error_msg }}

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 Title

{{ error_msg }}

home.html Title
{% for row in user_list %} {% endfor %}
{{ row.username }} {{ row.gender }} {{ row.email }}
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 Title

男: 女: 小李:

男: 女: 小李:

第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 Title
第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 Title {{ user_dict.k1 }}
    {% for key,row in user_dict.items %}
  • {{ key }}-{{ row }}
  • {% endfor %}
访问 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':'[email protected]'}, '2':{'name':'root2','email':'[email protected]'}, '3':{'name':'root3','email':'[email protected]'}, '4':{'name':'root4','email':'[email protected]'} } 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 Title detail.html Title Title

详细信息

用户名:{{ detail_info.name }}
详细信息:{{ detail_info.email }}
home.html Title
login.html Title

男: 女: 小李:

男: 女: 小李:

静态方式:常用方式 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':'[email protected]'}, '2':{'name':'root2','email':'[email protected]'}, '3':{'name':'root3','email':'[email protected]'}, '4':{'name':'root4','email':'[email protected]'} } 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 Title Title

详细信息

用户名:{{ detail_info.name }}
详细信息:{{ detail_info.email }}
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 Title 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\d+)-(?P\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\d+)/(?P\d+)', views.index,name='indexx'), v=reverse('indexx',kwargs={"nid":"1", "uid":"99"})
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':'[email protected]'}, '2':{'name':'root2','email':'[email protected]'}, '3':{'name':'root3','email':'[email protected]'}, '4':{'name':'root4','email':'[email protected]'} } 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 Title Title

详细信息

用户名:{{ detail_info.name }}
详细信息:{{ detail_info.email }}
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\d+)/(?P\d+)', views.index,name='indexx'), #path('indexhhh/', views.index,name='indexx'), #url('detail-(\d+).html', views.detail), url('detail-(?P\d+).html', views.detail), ] index.html Title

访问: 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\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\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':'[email protected]'}, '2':{'name':'root2','email':'[email protected]'}, '3':{'name':'root3','email':'[email protected]'}, '4':{'name':'root4','email':'[email protected]'} } 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 Title

templates/index.html Title
欢迎到来
templates/user_info.html Title
欢迎到来

用户列表

templates/user_detail.html Title
欢迎到来

用户详细信息

{{ obj.id }}

{{ obj.name }}

{{ obj.password }}

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" 一定要写。一定是小写 否则报错
2、 注意href和action、return redirect三个的区分,容易混淆 这是做的跳转: 用户管理 这是提交的当前的页面: 这个不加html return redirect用法:不加html return redirect('/cmdb/index/') 3、 根据id删除用户的瞬间跳转到当前页面 删除 def user_del(request,nid): models.UserInfo.objects.filter(id=nid).delete() return redirect('/cmdb/user_info/') 4、 注意不成功的话 重新打开一个页面试试 5、 注意: value的意思是可以在输入框中显示出来id style="display: none" 6、 注意form表单里面action路径 一定要和 url里面的保持一致,否则报错, 例如: href="/cmdb/userdetail-{{ row.id }} url(r'^userdetail-(?P\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\d+)/', views.user_detail,), url(r'^userdel-(?P\d+)/', views.user_del,), url(r'^useredit-(?P\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':'[email protected]'}, '2':{'name':'root2','email':'[email protected]'}, '3':{'name':'root3','email':'[email protected]'}, '4':{'name':'root4','email':'[email protected]'} } 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 Title
欢迎到来
templates/login.html Title

templates/user_info.html Title
欢迎到来

添加用户

用户列表

templates/user_detail.html Title
欢迎到来

用户详细信息

{{ obj.id }}

{{ obj.name }}

{{ obj.password }}

templates/user_edit.html Title

编辑用户

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) 实例:接之前的,变动的如下: 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 Title
欢迎到来

添加用户

用户列表

第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\d+)/', views.user_detail,), url(r'^userdel-(?P\d+)/', views.user_del,), url(r'^useredit-(?P\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':'[email protected]'}, '2':{'name':'root2','email':'[email protected]'}, '3':{'name':'root3','email':'[email protected]'}, '4':{'name':'root4','email':'[email protected]'} } 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='[email protected]', 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\d+)/', views.user_detail,), url(r'^userdel-(?P\d+)/', views.user_del,), url(r'^useredit-(?P\d+)/', views.user_edit,), path('orm/', views.orm), ] templates/user_info.html Title
欢迎到来

添加用户

用户列表

templates/index.html Title
欢迎到来
templates/login.html Title

templates/user_detail.html Title
欢迎到来

用户详细信息

{{ obj.id }}

{{ obj.name }}

{{ obj.password }}

templates/user_edit.html Title

编辑用户

访问: 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 Title

业务线列表(对象)

    {% for row in v1 %}
  • {{ row.id }} - {{ row.caption }} - {{ row.code }}
  • {% endfor %}

业务线列表(字典)

    {% for row in v2 %}
  • {{ row.id }} - {{ row.caption }}
  • {% endfor %}

业务线列表(元组)

    {% for row in v3 %}
  • {{ row.0 }} - {{ row.1 }}
  • {% endfor %}
第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 Title

业务线列表(对象)

    {% for row in v1 %}
  • {{ row.id }} - {{ row.caption }} - {{ row.code }}
  • {% endfor %}

业务线列表(字典)

    {% for row in v2 %}
  • {{ row.id }} - {{ row.caption }}
  • {% endfor %}

业务线列表(元组)

    {% for row in v3 %}
  • {{ row.0 }} - {{ row.1 }}
  • {% endfor %}
templates/host.html Title

业务线列表

{% for row in v1 %} {% endfor %}
主机名 ip地址 端口 业务线名称
{{ row.hostname }} {{ row.ip }} {{ row.port }} {{ row.b.caption }}
第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 Title

主机列表(列表)

{% for row in v1 %} {% endfor %}
主机名 ip地址 端口 业务线名称
{{ row.hostname }} {{ row.ip }} {{ row.port }} {{ row.b.caption }}

主机列表(字典)

{% for row in v1 %} {% endfor %}
主机名 ip地址 端口 业务线名称
{{ row.hostname }} {{ row.ip }} {{ row.port }} {{ row.b.caption }}

业务线列表*(元组)

{% for row in v3 %} {% endfor %}
主机名 ip地址
{{ row.1 }} {{ row.3 }}
第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 Title

主机列表(列表)

{% for row in v1 %} {% endfor %}
序号 主机名 ip地址 端口 业务线名称
{{ forloop.counter }} {{ row.hostname }} {{ row.ip }} {{ row.port }} {{ row.b.caption }}

主机列表(字典)

{% for row in v1 %} {% endfor %}
主机名 ip地址 端口 业务线名称
{{ row.hostname }} {{ row.ip }} {{ row.port }} {{ row.b.caption }}

主机列表*(元组)

{% for row in v3 %} {% endfor %}
主机名 ip地址
{{ row.1 }} {{ row.3 }}
第20周-09 初识Ajax :返回另一个界面,弹出一个框 接上面: templates/host.html Title

主机列表(列表)

{% for row in v1 %} {% endfor %}
序号 主机名 ip地址 端口 业务线名称
{{ forloop.counter }} {{ row.hostname }} {{ row.ip }} {{ row.port }} {{ row.b.caption }}

主机列表(字典)

{% for row in v1 %} {% endfor %}
主机名 ip地址 端口 业务线名称
{{ row.hostname }} {{ row.ip }} {{ row.port }} {{ row.b.caption }}

主机列表*(元组)

{% for row in v3 %} {% endfor %}
主机名 ip地址
{{ row.1 }} {{ row.3 }}
悄悄提交
第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 Title

主机列表(列表)

{% for row in v1 %} {% endfor %}
序号 主机名 ip地址 端口 业务线名称
{{ forloop.counter }} {{ row.hostname }} {{ row.ip }} {{ row.port }} {{ row.b.caption }}

主机列表(字典)

{% for row in v1 %} {% endfor %}
主机名 ip地址 端口 业务线名称
{{ row.hostname }} {{ row.ip }} {{ row.port }} {{ row.b.caption }}

主机列表*(元组)

{% for row in v3 %} {% endfor %}
主机名 ip地址
{{ row.1 }} {{ row.3 }}
悄悄提交
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 写好框架代码,然后在中间加上下面这句话,就可以被继承 .add-modal { position: fixed; height: 300px; width: 400px; top: 100px;} {% block css %}{% endblock %} 框架代码 {% block content %}{% endblock %} 框架代码 {% block js %} {% endblock %} ceshi.html 注意:其他html想定制jss和css时候,模板文件需要先写好block的位置, 写css和js没有顺序分 导入重复用的框架代码: {% extends 'master.html' %} {% block title %}用户管理{% endblock %} {% block content %}
    {% for row in v1 %}
  • {{ row.id }} - {{ row.caption }} - {{ row.code }}
  • {% endfor %}
{% endblock %} {% block js %} {% endblock %} {% block css %}内容 {%endblock %} 第21周-第07章节-Python3.5-模板之导入 在需要导入html的位置 加上:{% include tag.html %} 有多个就循环 第21周-第09章节-Python3.5-自定义 simple_tag

  

转载于:https://www.cnblogs.com/effortsing/p/9985808.html

你可能感兴趣的:(python学习笔记)