本人用flask作為微信公眾號服務端框架,開發一款“猜數字”小游戲,可是全域變數竟然出現混亂狀態,很是奇怪。還請大家不吝賜教!
下面貼上代碼:
# coding:utf-8
from flask import Flask, request, abort, render_template
import hashlib
import xmltodict, time
import random
#global myvalue,guesstime
myvalue = 2222
guesstime = 0
# 常量
# 微信的token令牌
WECHAT_TOKEN = "******"
app = Flask(__name__)
@app.route("/connect", methods=["GET", "POST"])
#def index_html():
# return render_template('index.html',name='stronger')
def wechat():
"""對接微信公眾號服務器"""
# 接收微信服務器發送的引數
signature = request.args.get("signature")
timestamp = request.args.get("timestamp")
nonce = request.args.get("nonce")
if not all([signature, timestamp, nonce]):
abort(400)
# 按照微信的流程進行計算簽名
li = [WECHAT_TOKEN, timestamp, nonce]
# 排序
li.sort()
# 拼接字串
tmp_str = ''.join(li)
# 進行sha1加密, 得到正確的簽名值
sign = hashlib.sha1(tmp_str.encode('utf-8')).hexdigest()
# 將自己計算的簽名值與請求的簽名引數進行對比,如果相同,則證明請求來自微信服務器
if sign != signature:
# 表示請求不是微信發的
abort(403)
else:
# 表示是微信發送的請求
if request.method == "GET":
# 表示是第一次接入微信服務器的驗證
echostr = request.args.get("echostr")
if not echostr:
abort(404)
return echostr
elif request.method == "POST":
# 表示微信服務器轉發訊息過來
xml_str = request.data
if not xml_str:
abort(400)
# 對xml字串進行決議
xml_dict = xmltodict.parse(xml_str)
xml_dict = xml_dict.get("xml")
# 提取訊息型別
msg_type = xml_dict.get("MsgType")
if msg_type == "text":
result=''
global guesstime
global myvalue
inputvalue = xml_dict.get("Content")
if inputvalue == 'guess':
myvalue = random.randint(1000,10000)
print(myvalue)
result='請輸入1000~10000之間的整數'
#elif inputvalue.isdigit():
else:
print('you input value is %s' % inputvalue )
print(myvalue)
if int(inputvalue) > myvalue:
result = '大了!'
guesstime += 1
elif int(inputvalue) < myvalue:
result = '小了!'
guesstime += 1
else:
result = u'恭喜猜中!\n可以繼續猜下一個數字哦!'
#saveMysql(msg.source, guesstime)
myvalue = random.randint(1000,10000)
guesstime = 0
# 表示發送的是文本訊息
# 構造回傳值,經由微信服務器回復給用戶的訊息內容
resp_dict = {
"xml": {
"ToUserName": xml_dict.get("FromUserName"),
"FromUserName": xml_dict.get("ToUserName"),
"CreateTime": int(time.time()),
"MsgType": "text",
"Content": result
}
}
else:
resp_dict = {
"xml": {
"ToUserName": xml_dict.get("FromUserName"),
"FromUserName": xml_dict.get("ToUserName"),
"CreateTime": int(time.time()),
"MsgType": "text",
"Content": "Dear I Love you so much"
}
}
# 將字典轉換為xml字串
resp_xml_str = xmltodict.unparse(resp_dict)
# 回傳訊息資料給微信服務器
return resp_xml_str
if __name__ == '__main__':
app.run(host="127.0.0.1", port=80, debug=True)
運行結果就是隨機變數myvalue的值時而是隨機值,時而是全域變數的初始值,太令人費解了。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/232177.html
