定义一个路由,方法是POST,名字为wordcheck

@app.route('/wordcheck',methods=['POST']) def wordcheck(): # 获取POST请求中的msg和openid msg = request.json.get('msg') openid = request.json.get('openid')

try:
    # 调用infocheck函数进行内容安全检测
    stau = infocheck(msg,openid)
    if stau:
        # 返回检测通过的json数据
        return jsonify({'code':1})
    else:
        # 返回检测不通过的json数据
        return jsonify({'code': 0, 'msg': 'err'})
except:
    # 返回错误的json数据
    return jsonify({'code':0,'msg':'err'})

定义一个微信内容安全检测函数

def infocheck(text,openid): try: # 从数据库中获取access_token acctoken = Adj.query.filter(Adj.id == 2).first().adjinfo # 构造检测URL checkurl = "https://api.weixin.qq.com/wxa/msg_sec_check?access_token={ACCESS_TOKEN}".format( ACCESS_TOKEN=acctoken)

    # 构造数据
    data = '{"content": "' + text + '","openid": "' + openid + '","scene":  2 ,"version":  2 }'
    headers = {'Content-Type': 'application/json'}
    # 发送POST请求
    res = requests.post(checkurl, data=data.encode('utf-8'), headers=headers)
    # 获取检测结果
    lev = res.json().get("result").get("label")
    sug = res.json().get("result").get("suggest")
    # 输出结果信息
    print(res.json())
    print(lev,sug)
    # 如果检测结果为100且建议为'pass',则返回True,否则返回False
    return True if lev == 100 and sug == 'pass'  else False
except Exception as e:
    # 如果出现异常,则重新获取access_token,并返回错误信息
    getacctoken()
    print('重新获取')
    return jsonify('内容包含敏感文字,请重新编辑发送')

定义一个获取access_token的函数

def getacctoken(): print('getroken') # 构造获取access_token的URL access_token_url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential'
'&appid={appid}&secret={secret}'.format(appid=APPID, secret=SECRET) # 发送GET请求 access_token_res = requests.get(access_token_url).json()['access_token'] # 将access_token存入数据库中 atok = Adj.query.filter(Adj.id == 2).first() if atok: atok.adjinfo = access_token_res else: atok = Adj(id = 2,adjinfo=access_token_res) db.session.add(atok) db.session.commit() # 如果获取access_token失败,则抛出异常 if access_token_res.json().get('errcode'): raise 'AccessToken()'

定义一个路由,方法是POST,名字为test

@app.route('/test',methods=['POST']) def test(): # 获取POST请求中的text和openid text = request.json.get('text') openid = request.json.get('openid') # 调用infocheck函数进行内容安全检测,并返回检测结果 a = infocheck(text,openid) return a

approutewordcheckmethods=POSTdef wordcheck msg = requestjsongetmsg openid = requestjsongetopenid try stau = infocheckmsgopenid if stau return jsonifycode1 else

原文地址: https://www.cveoy.top/t/topic/HLy 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录