Python中实战小案例
一、正则表达式
匹配4-20位可以带字母数字下划线的126或者163邮箱,创建一个分组,用group(1)取值
ret = (re.match(r"[a-zA-Z_0-9]{4,20}@(163|126)\.com$", 'abcdd@126.com'))
print (ret.group())
验证手机号是否有效,只能匹配以1开头,第二位是3,长度为2+9=11的手机号
print(re.match(r'^1[3]\d{9}$','13345678401').group())
使用sub方法替换内容 第一种,直接替换
import re
ret = re.sub(r"\d+",str(100),"python = 99")
print(ret)
第二种,调用函数替换,两种输出都是一样的
import re
def add(temp):
strNum = temp.group()
num = int(strNum) +1
return str(num)
ret = re.sub(r"\d+",add,"python = 99")
print(ret)
结果: python = 100
二、genent创建协程
genvnt: 在需要阻塞的代码处,自动切换下一个函数
注意:如果没有打补丁的话,耗时的代码不会切换另一个函数
代码如下:
import gevent
from gevent import monkey
import time
monkey.patch_all()
def work1(num):
ret=0
for i in range(num):
print(ret,'work1')
ret+=1
time.sleep(1)
def work2(num):
ret=0
for i in range(num):
print(ret,'work2')
ret+=1
time.sleep(1)
gevent.joinall(
[
gevent.spawn(work1,5),
gevent.spawn(work2,5)
]
)
运行结果:
0 work1
0 work2
1 work1
1 work2
2 work1
2 work2
3 work1
3 work2
4 work1
4 work2
三、服务端使用http协议向浏览器发送消息
浏览器作为客户端
代码原理:
- 创建套接字,监听7788端口
- 浏览器请求根目录返回主界面代码,请求文件则打开文件并返回给浏览器
- 若请求文件不存在,则返回404
- qq浏览器犯病,有时候请求体为空,所以加了一个判断,判断是否存在请求体
代码如下:
import logging
import os.path
import re
import socket
Format = logging.Formatter('%(levelname)s %(asctime)s %(filename)s %(funcName)s [%(message)s] ')
logger = logging.getLogger()
logger.setLevel('DEBUG')
console_handle = logging.StreamHandler()
console_handle.setLevel(level='INFO')
console_handle.setFormatter(Format)
logger.addHandler(console_handle)
def send_main(new_tcp_socket):
logger.info('request main')
responce = 'HTTP/1.1 200 OK\r\n'
responce += "\r\n"
send_data = "<h1>I am a cute server</h1>"
logger.info(f'sending data: {send_data}')
new_tcp_socket.send((responce + send_data).encode('utf-8'))
def send_responce(new_tcp_socket):
request = new_tcp_socket.recv(1024).decode('utf-8')
if request:
request_lines = request.splitlines()
logger.debug(request_lines)
ret = re.match(r"[^/]+/([^ ]*)", request_lines[0]).group(1)
if ret:
logger.info(f'request file = {ret}')
if os.path.exists(ret):
with open(ret, 'rb') as file:
send_data = file.read().decode('utf-8')
responce = 'HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\n'
responce += "\r\n"
logger.info(f'sending file content: {file}')
new_tcp_socket.send((responce + send_data).encode('utf-8'))
else:
responce = 'HTTP/1.1 404 Not Found\r\nContent-Type: text/html; charset=utf-8\r\n'
responce += "\r\n"
logger.error('file not exists')
new_tcp_socket.send((responce + '<h1>file not exists</h1>').encode('utf-8'))
else:
send_main(new_tcp_socket)
else:
logger.error('QQ browser disease')
send_main(new_tcp_socket)
new_tcp_socket.close()
logger.info('close connection')
def main():
logger.info('start listen port:7788')
tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcp_server_socket.bind(('', 7788))
tcp_server_socket.listen(128)
while True:
logger.info('reday for a new connection')
new_tcp_socket, client_addr = tcp_server_socket.accept()
logger.info(f'client has established a connection.client addr = {client_addr}')
send_responce(new_tcp_socket)
if __name__ == '__main__':
main()
成果展示: 后台日志:
四、深拷贝与浅拷贝
import copy
print('----------浅拷贝----------')
a=[1,2,3]
b=[4,5,6]
c=[a,b]
d=copy.copy(c)
print('c的值与id为',c,id(c))
print('d的值与id为',d,id(d))
print('a的id为',id(a))
print('d中第一个元素的id为',id(d[0]))
print('a中添加元素777')
a.append(777)
print(f'c的值为{c},d的值为{d}')
print()
print('----------深拷贝----------')
a=[1,2,3]
b=[4,5,6]
c=[a,b]
d=copy.deepcopy(c)
print('c的值与id为',c,id(c))
print('d的值与id为',d,id(d))
print('a的id为',id(a))
print('d中第一个元素的id为',id(d[0]))
a.append(777)
print(f'c的值为{c},d的值为{d}')
结果:
----------浅拷贝----------
c的值与id为 [[1, 2, 3], [4, 5, 6]] 2962023748352
d的值与id为 [[1, 2, 3], [4, 5, 6]] 2962023748608
a的id为 2962014350272
d中第一个元素的id为 2962014350272
a中添加元素777
c的值为[[1, 2, 3, 777], [4, 5, 6]],d的值为[[1, 2, 3, 777], [4, 5, 6]]
----------深拷贝----------
c的值与id为 [[1, 2, 3], [4, 5, 6]] 2962023743424
d的值与id为 [[1, 2, 3], [4, 5, 6]] 2962023748352
a的id为 2962023748096
d中第一个元素的id为 2962023743168
c的值为[[1, 2, 3, 777], [4, 5, 6]],d的值为[[1, 2, 3], [4, 5, 6]]
|