短信邮件

eval

  • 将一个有效的 Python 代码字符串执行一遍
  • 示例 1:
    1
    2
    3
    4
    5
    6
    a = 10
    b = 20

    s = 'a+b'
    # 打印的结果是30
    print(eval(s))
  • 示例 2:
    1
    2
    3
    4
    5
    s = '[1, 2, 3, 4, 5]'

    l = eval(s)
    # 打印结果是[1, 2, 3, 4, 5]
    print(l)
  • date

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    from datetime import date
    import time as t

    d1 = date(2019, 3, 26)
    print(d1)
    print(type(d1))

    d2 = date.today()
    print(d2)

    d3 = date.fromtimestamp(t.time())
    print(d3)

    # 标准格式字符串
    print(d1.isoformat())

    # 日历显示形式(年,第几周,星期)
    print(d1.isocalendar())

    # 获取星期(1~7)
    print(d1.isoweekday())

    # 获取星期(0~6)
    print(d1.weekday())

    # 格式化
    print(d1.strftime('%Y-%m-%d'))

    # 转换为元组形式
    print(d1.timetuple())
  • time

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    from datetime import time

    t = time(12, 13, 14)
    print(t)
    # 单独获取时、分、秒
    print(t.hour)
    print(t.minute)
    print(t.second)

    # 格式化
    print(t.strftime('%H::%M::%S'))
  • datetime

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    import time
    from datetime import datetime

    dt = datetime(2019, 3, 26, 17, 39, 30)
    print(dt)

    # 本地时间
    dt2 = datetime.now()
    print(dt2)

    # 不带时区的时间
    dt3 = datetime.utcnow()
    print(dt3)

    # 将一个时间戳转换为datetime
    dt4 = datetime.fromtimestamp(time.time())
    print(dt4)

    # 获取日期
    print(dt4.date())
    # 获取时间
    print(dt4.time())
    # 获取时间戳
    print(dt4.timestamp())
    # 格式化显示
    print(dt4.strftime('%Y-%m-%d %H:%M:%S'))
  • timedelta

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    from datetime import datetime, timedelta

    d1 = datetime(2019, 3, 21, 17, 48, 50)
    d2 = datetime(2019, 3, 26, 17, 50, 50)

    delta = d2 - d1
    print(delta)
    print(type(delta))

    delta2 = timedelta(days=2, hours=2, seconds=30)
    print(delta2)

    d3 = d1 + delta2
    print(d3)

    # 天数
    print(delta2.days)
    # 除天数外的秒数
    print(delta2.seconds)
    # 总秒数
    print(delta2.total_seconds())
  • 实例

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    from datetime import datetime, date, timedelta

    # 获取今天 日期+时间
    now = datetime.now()
    print(now) # 2021-11-16 09:16:36.515233

    # 获取今天日期
    today = date.today()
    print(today) # 2021-11-16

    # 获取昨天日期
    yesterday = date.today() + timedelta(-1)
    print(yesterday) # 2021-11-15

hashlib

  • md5:非对称加密,不可逆的,经常用于加密密码然后存储
  • 示例:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    import hashlib

    # 创建hash对象,可以指定需要加密的字符串
    md = hashlib.md5()

    # 设置加密字符串,创建md5对象时就不必指定了,不能两个地方都指定
    md.update('123456'.encode('utf-8'))

    # 获取加密后的字符串(32位)
    print(md.hexdigest())

urllib

  • 说明:
    • URI:统一资源标识符
    • URL:统一资源定位符,URI 的一种形式,如:http://www.baidu.com:80?name=xiaoming&age=10
  • 示例:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    from urllib.parse import urlencode

    d = {'name': 'dahua', 'age': 10}

    print(d)
    # 转换为:name=dahua&age=10
    print(urlencode(d))


    from urllib.parse import urlparse

    url = 'http://www.baidu.com:80/abc/def?page=3&size=5'
    # 解析出url中所有的参数
    # 结果:ParseResult(scheme='http', netloc='www.baidu.com:80', path='/abc/def', params='', query='page=3&size=5', fragment='')
    p = urlparse(url)
    print(p)
    # 请求参数
    print(p.query)


    from urllib.parse import parse_qs

    # 将url请求参数转换成字典
    # 结果:{'page': ['3'], 'size': ['5']}
    d = parse_qs(p.query)
    print(d)

http.client

  • 说明:可以模拟浏览器发送 http 请求 (是爬虫的基础)
  • 示例:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    import http.client

    # 创建连接(相当于浏览器)
    connect = http.client.HTTPConnection('www.baidu.com')

    # 发送请求(GET、POST)
    connect.request(method='GET', url='https://www.baidu.com/')

    # 获取响应
    resp = connect.getresponse()

    # 打印响应内容,读取并解码
    print(resp.read().decode('utf-8'))

邮件发送

  • 说明:在一个网站中经常使用邮件操作,如:激活、通知、等
  • smtp 使用:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    import os
    import smtplib

    # 将字符串转换为邮件的文本格式
    from email.mime.text import MIMEText

    # 邮箱服务器
    mail_server = 'smtp.163.com'

    # 用户名
    mail_user = '16657158725@163.com'

    # 密码或授权码,为了不将密码公开,可以通过环境变量的形式获取
    mail_password = os.environ.get('MAIL_PASSWORD') or '123456'
    # mail_password = 'suyin'

    # 邮件消息
    message = '你好,欢迎注册xxx平台,激活请点击右边链接<a href="https://www.baidu.com/">百度一下</a>'
    # 将邮件字符串消息转换成邮件格式,若内容是HTML需要指定第二个参数为'html'
    message = MIMEText(message, 'html')

    # 设置主题
    message['Subject'] = '账户激活'
    # 设置发送人
    message['From'] = mail_user

    # 创建邮件对象
    mail = smtplib.SMTP(mail_server, 25)
    # 登录服务器
    mail.login(mail_user, mail_password)

    # 接收者,多个使用逗号隔开
    to = '15893896748@163.com'

    # 发送邮件
    mail.sendmail(mail_user, to, message.as_string())

    # 结束
    mail.quit()

短信发送

  • 说明:注册验证码、通知消息、营销短息、...
  • 短信发送平台:阿里、云之讯、秒滴、...
  • 示例:秒滴(http://www.miaodiyun.com)
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    import time
    import hashlib
    import http.client
    from urllib.parse import urlencode

    # 请求地址
    url = 'https://api.miaodiyun.com/20150822/industrySMS/sendSMS'

    # 请求头
    headers = {'Content-type': 'application/x-www-form-urlencoded'}

    # 账户id
    accountSid = '8d7ec5467c27456b859d727268b62ca9'

    # auth token
    auth_token = '62438af2632f448c94b028a1641b3906'

    # 时间戳
    timestamp = time.strftime('%Y%m%d%H%M%S')

    sig = accountSid + auth_token + timestamp

    # 加密一下
    md = hashlib.md5()
    md.update(sig.encode('utf-8'))
    sig = md.hexdigest()

    # 模板参数
    yzm = '632881'
    t = '5'
    param = yzm + ',' + t

    # 表单数据
    form_data = {
    'accountSid': accountSid,
    'templateid': '1502437573',
    'to': '16657158725',
    'timestamp': timestamp,
    'sig': sig,
    'param': param
    }

    # 将字典转换为url参数形式
    form_data = urlencode(form_data)

    # 创建浏览器对象
    connect = http.client.HTTPConnection('api.miaodiyun.com')

    # 发送POST请求
    connect.request(method='POST', url=url, body=form_data, headers=headers)

    # 获取响应;
    resp = connect.getresponse()

    # 打印响应结果
    print(resp.read().decode('utf-8'))