【python基础】常见模块:openpyxl & socket & requests

liugan 2019-12-29

一、openpyxl,实现随机点名

import openpyxl, random

def call_somebody():
    excel = openpyxl.load_workbook(r"./学员名单.xlsx")
    sheet = excel.active
    name_list = []  # 装着所有的人名
    for name in range(1, 49):
        cell = sheet["C" + str(name)]  # "C" + "47"
        name_list.append(cell.value)

    return random.choice(name_list)

print(call_somebody())

二、socket——send & recieve

from socket import *

ip = "127.0.0.1"  # 接收方的 ip地址, 本机: 127.0.0.1, localhost
port = 4444  # 端口号, 65535, 1~1023, 1024--> 以后设置
address = (ip, port)  # 接收方的地址

# 创建一个socket对象
s = socket(AF_INET, SOCK_DGRAM)

while True:
    # 发送数据
    # info = "xixi"
    info = input("请输入你要发送的内容:")
    if info:
        s.sendto(info.encode(‘utf-8‘), address)
    else:
        break
# 发送完毕 --> 关闭
s.close()
from socket import *

# 初始化操作
ip = "127.0.0.1"  # 接收方的ip
port = 4444  # 接收方端口
address = (ip, port)

# 创建socket对象
s = socket(AF_INET, SOCK_DGRAM)

# 绑定接收地址
s.bind(address)

while True:
    # 接收数据
    data, adr = s.recvfrom(1024)
    print("接收到{}发送的信息, 信息的内容是:{}".format(str(adr), str(data, ‘utf-8‘)))

三、requests

import requests, base64


# 获取access_token
def get_access_token():
    url = "https://aip.baidubce.com/oauth/2.0/token?"  7           "grant_type=client_credentials&"  8           "client_id=SdnZagCfatQDEtjoPIKhf2zR&"  9           "client_secret=bL1bA9Gs3HnSoGfiR3Mix88Gg3YjIURI"
    r = requests.post(url)  # 发起请求, 获取响应
    res = r.json()  # r.text, r.content.decode(‘utf-8‘), r.json() 获取响应的json内容
    # print(type(res))  # <class ‘dict‘>
    # print(res)
    return res.get(‘access_token‘)  # 返回值为access_token的值


def detect_face():
    # 请求的地址
    url = "https://aip.baidubce.com/rest/2.0/face/v3/detect?access_token=%s" % get_access_token()

    header = {"Content-Type": "application/json"}

    with open(r"./1.jpg", "rb") as f:
        b64_img = base64.b64encode(f.read())

    data = {
        "image": b64_img,
        "image_type": "BASE64",
        "face_field": "age,beauty,expression,face_shape,gender,glasses"
    }

    # 发起请求 --> 获取响应对象r
    r = requests.post(url, headers=header, data=data)
    print(r.json())  # 获取响应的json格式数据


detect_face()

相关推荐