腾讯云-发送短信
https://cloud.tencent.com/document/product/382/43196
python
# -*- coding: utf-8 -*-
from tencentcloud.common import credential
from tencentcloud.common.exception.tencent_cloud_sdk_exception import (
TencentCloudSDKException,
)
# 导入可选配置类
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
# 导入对应产品模块的 client models。
from tencentcloud.sms.v20210111 import models, sms_client
def send_sms(phones: list, code: str, duration: str = "5"):
try:
cred = credential.Credential(
"AKID66rMbaIjuoRntjIabLo1yg8JDrELEtHO", "OWOzJMAizzjCOJwJPEm33RZR2NRItDG2"
)
httpProfile = HttpProfile()
httpProfile.reqMethod = "POST" # post请求(默认为post请求)
httpProfile.reqTimeout = 30 # 请求超时时间,单位为秒(默认60秒)
httpProfile.endpoint = "sms.tencentcloudapi.com" # 指定接入地域域名(默认就近接入)
clientProfile = ClientProfile()
clientProfile.signMethod = "TC3-HMAC-SHA256" # 指定签名算法
clientProfile.language = "en-US"
clientProfile.httpProfile = httpProfile
client = sms_client.SmsClient(cred, "ap-guangzhou", clientProfile)
req = models.SendSmsRequest()
req.SmsSdkAppId = "1400229652"
req.SignName = "青灯教育"
req.ExtendCode = ""
req.SessionContext = "xxx"
req.SenderId = ""
req.PhoneNumberSet = [f"+86{phone}" for phone in phones]
req.TemplateId = "1308690"
req.TemplateParamSet = [code, duration]
resp = client.SendSms(req)
ret = resp.to_json_string(indent=2)
# print(ret)
return True
except TencentCloudSDKException as err:
# print(err)
return False
if __name__ == "__main__":
send_sms(["18675867241"], "875421", "5")
flask-上传文件
python
def upload_images(image: FileStorage):
"""
将图片保存到本地
"""
path = os.path.dirname(current_app.instance_path)
avatar_dir = os.path.join(
path, "static", "upload", datetime.today().strftime("%Y-%m")
)
if not os.path.exists(avatar_dir):
os.makedirs(avatar_dir)
# 从 FileStorage 对象里面获取文件名字
filename = image.filename
# 名字相同,内容不同
suffix = filename.split(".")[-1]
# name = uuid.uuid4().hex
# 内容相同,名字不同 md5 摘要
content = image.stream.read() # 读取图片之后,就没有内容了
name = hashlib.md5(content).hexdigest() # 获取 md5 的值
# print(name)
filename = ".".join([name, suffix])
# 1. 将文件保存
# avatar.save(dst=os.path.join(avatar_dir, filename))
open(os.path.join(avatar_dir, filename), mode="wb").write(content)
# 2. 生成访问地址
images_url = "/".join(
["/static", "upload", datetime.today().strftime("%Y-%m"), filename]
)
return images_url
腾讯云-静态资源存储
python
from datetime import date
from qcloud_cos import CosConfig, CosS3Client
# 文档地址: https://cloud.tencent.com/document/product/436/12269
class TenCos:
def __init__(self):
secret_id = "AKIDEG4d50OdEZkicO5Tdu9KcfU6axCSoLYX" # 替换为用户的 secretId
secret_key = "0mLpY2WnVXMSKxNYS5W1GGBuT0HLCn9S" # 替换为用户的 secretKey
region = "ap-nanjing"
config = CosConfig(
Region=region, SecretId=secret_id, SecretKey=secret_key # 替换为用户的 Region
)
# 2. 获取客户端对象
self.client = CosS3Client(config)
def save_user_pic(self, filename, file, default_path="user_pic"):
filename = "/".join([default_path, date.today().strftime("%Y-%m"), filename])
file_url = (
"https://qingdeng123-1257113111.cos.ap-nanjing.myqcloud.com/" + filename
)
response = self.client.put_object(
Bucket="qingdeng123-1257113111", Body=file, Key=filename, EnableMD5=False
)
if response["ETag"]:
return "ok", file_url
else:
return "", ""
图片验证码
python
from io import BytesIO
from random import choices
from captcha.image import ImageCaptcha
from PIL import Image
def gen_captcha(content="012345689"):
"""生成验证码"""
image = ImageCaptcha()
# 获取字符串
captcha_text = "".join(choices(content, k=4)) # 从 content 里面随机选取四个内容
# 生成图像
# print(image.generate(captcha_text))
data = image.generate(captcha_text)
captcha_image = Image.open(data)
out = BytesIO()
captcha_image.save(out, "png")
# resp = make_response(out.read())
# resp.content_type = 'image/png' return captcha_text, captcha_image
# 生成验证码
def get_captcha_image():
code, image = gen_captcha()
out = BytesIO()
# session["code"] = code
image.save(out, "png")
out.seek(0)
content = out.read() # 读取图片的二进制数据做成响应体
return content, code
if __name__ == "__main__":
text, img = gen_captcha()
print(text)
print(img)
拓展-Redis 插件
python
from redis import StrictRedis # Redis
from com import constants
class RedisStore:
def __init__(self, app=None):
if app is not None:
self.init_app(app)
self.strict_redis: StrictRedis = None
def init_app(self, app):
# 配置 redis 数据库
if "REDIS_HOST" not in app.config:
raise Exception("需要先加载redis配置信息")
self.strict_redis = StrictRedis(
host=app.config["REDIS_HOST"],
port=app.config["REDIS_PORT"],
decode_responses=True,
)
# current_app.strict_redis.xxx 的方式进行调用
setattr(app, "strict_redis", self.strict_redis)
def store_chapter_image(self, code_id, text):
self.strict_redis.setex(
"ImageCode_" + code_id, constants.IMAGE_CODE_REDIS_EXPIRES, text
)
def get_chapter_image(self, code_id):
return self.strict_redis.get("ImageCode_" + code_id)
def store_sms_code(self, mobile, sms_code):
self.strict_redis.setex(
"sms_code_" + mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code
)
def get_sms_code(self, mobile):
return self.strict_redis.get("sms_code_" + mobile)