1. 《微信開發入門》文檔中
list = [token, timestamp, nonce]
list.sort()
sha1 = hashlib.sha1()
map(sha1.update, list)//此處錯誤
hashcode = sha1.hexdigest()
應修改爲
list = [token, timestamp, nonce]
list.sort()
sha1 = hashlib.sha1()
sha1.update(list[0].encode("utf-8"))
sha1.update(list[1].encode("utf-8"))
sha1.update(list[2].encode("utf-8"))
hashcode = sha1.hexdigest()
參考文章
微信公衆號token無法通過的bug解決
2.XmlForm.format(**self.__dict)
這屬於python的字符串格式化
它通過{}和:來代替傳統%方式
要點:關鍵字參數值要對得上,可用字典當關鍵字參數傳入值,字典前加 ** 即可
例如:
hash = {‘name’:‘hoho’,‘age’:18}
‘my name is {name},age is {age}’.format(**hash)
‘my name is hoho,age is 18’
def __init__(self, toUserName, fromUserName, content):
self.__dict = dict()
self.__dict['ToUserName'] = toUserName
self.__dict['FromUserName'] = fromUserName
self.__dict['CreateTime'] = int(time.time())
self.__dict['Content'] = content
def send(self):
XmlForm = """
<xml>
<ToUserName><![CDATA[{ToUserName}]]></ToUserName>
<FromUserName><![CDATA[{FromUserName}]]></FromUserName>
<CreateTime>{CreateTime}</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[{Content}]]></Content>
</xml>
"""
return XmlForm.format(**self.__dict)
這裏就是把dict相應字段的值填入到xml字符串裏。
3. web.py 本地運行
python 3 環境下安裝web.py
pip install web.py==0.40-dev1
編寫腳本hello.py並運行。
#hello.py
import web
urls = ('/wx', 'hello',)
class hello():
def GET(self):
return 'hello world'
if __name__ == "__main__":
app = web.application(urls, globals())
app.run()
出現如下錯誤信息:
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "F:\xw\project\python_from_beginning\wx\hello.py", line 10, in <module>
app = web.application(urls, globals())
File "D:\Users\admin\AppData\Local\Programs\Python\Python37\lib\site-packages\web\application.py", line 62, in __init__
self.init_mapping(mapping)
File "D:\Users\admin\AppData\Local\Programs\Python\Python37\lib\site-packages\web\application.py", line 130, in init_mapping
self.mapping = list(utils.group(mapping, 2))
File "D:\Users\admin\AppData\Local\Programs\Python\Python37\lib\site-packages\web\utils.py", line 531, in group
x = list(take(seq, size))
RuntimeError: generator raised StopIteration
把util.py中
line 526, in take
yield next(seq)
StopIteration
修改爲
try:
yield next(seq)
except StopIteration:
return
瀏覽器中輸入
http://127.0.0.1:8080/wx
可以看見 hello world!
打開任務管理器,我們可以看到python的 hello.py 進程。當我們訪問這臺服務器的8080端口,並且url爲/wx時,就進入了這個程序。
urls = ('/wx', 'hello',)
class hello():
def GET(self):
return 'hello world'
4.使用flask創建微信後端
# -*- coding:utf-8 -*-
from flask import Flask
from flask import request
import hashlib
app = Flask(__name__)
app.debug = True
@app.route('/wx_flask',methods=['GET','POST'])
def wechat():
if request.method == 'GET':
#這裏改寫你在微信公衆平臺裏輸入的token
token = 'xiaoqingxin'
#獲取輸入參數
data = request.args
signature = data.get('signature','')
timestamp = data.get('timestamp','')
nonce = data.get('nonce','')
echostr = data.get('echostr','')
#字典排序
list = [token, timestamp, nonce]
list.sort()
s = list[0] + list[1] + list[2]
#sha1加密算法
hascode = hashlib.sha1(s.encode('utf-8')).hexdigest()
#如果是來自微信的請求,則回覆echostr
if hascode == signature:
return echostr
else:
return ""
if __name__ == '__main__':
app.run()
其中
@app.route('/wx_flask',methods=['GET','POST'])
def wechat():
是python decorator,表示當網頁訪問“/wx_flask”目錄時,會調用到wechat()函數。
具體語法解釋見下文。
https://www.cnblogs.com/zh605929205/p/7704902.html
5.python 字符串格式%s的用法
比如下面的例子:
print("I'm %s. I'm %d year old" % ('Vamei', 99))
輸出 I'm Vamei. I'm 99 year old"
6.部署到aws上
1.首先在本地使用github創建wx_flask
1)github 頁面點擊"create repository".
2)在本地文件夾下 用命令行"git add repository_address"
3)使用 GitHub desktop程序 “add local repository”進行管理。
4)安裝Python3及使用venv,編寫工程代碼。
2.創建aws服務器及使用git 管理代碼
1)git clone “repository url”。
2) 學習使用 git的 checkout, log, reflog, reset等命令管理版本。
sudo apt-get update
sudo apt install python3-pip
#pip3 install virtualenv
sudo apt-get install python3-venv
python3 -m venv venv_aws_ubuntu18
source venv_aws_ubuntu18/bin/activate
/更新單個文件/
git checkout origin/master -- hello.py
從aws下載文件到本地(aws 無法 git push的替代辦法)
scp -i myawskey2019.pem [email protected]:/home/ubuntu/wx_flask/hello.py /Users/xiongwei/Downloads/my_project/github_directory
從aws下載文件夾到本地
scp -i myawskey2019.pem -r [email protected]:/home/ubuntu/wx_flask/venv_aws_ubuntu18/ /Users/xiongwei/Downloads/my_project/github_directory/wx_flask/
ps: ubuntu18 refers to AWS AMI=“ubuntu/images/hvm-ssd/ubuntu-bionic-18.04-amd64-server-20180912 (ami-0f65671a86f061fcd)”
從本地把文件上傳到aws文件夾:
scp -i myawskey2019.pem /Users/xiongwei/Downloads/my_project/github_directory/wx_flask/wx_flask.py [email protected]:/home/ubuntu/wx_flask/
github 建tag
$ git tag
v1.0
$ git tag -d v1.0
Deleted tag ‘v1.0’ (was 9b81e22)
$ git tag -a v1.0 -m “hello world can be seen on broswer by http://18.224.25.101:8080”
$ git push origin --tags
在後臺運行python程序的命令:
(venv) $ python hello.py &
ssh連接斷開命令:
輸入 logout
對接微信接口
微信http消息只能在80端口,而aws ubuntu默認用戶爲普通用戶,無法開啓 80端口。
會報如下錯誤:
(venv_aws_ubuntu18) ubuntu@ip-172-31-21-46:~/wx_flask$ python wx_flask.py
* Serving Flask app "wx_flask" (lazy loading)
* Environment: production
WARNING: Do not use the development server in a production environment.
Use a production WSGI server instead.
* Debug mode: on
Traceback (most recent call last):
File "wx_flask.py", line 28, in <module>
app.run(debug=True, host='0.0.0.0', port=80)
File "/home/ubuntu/wx_flask/venv_aws_ubuntu18/lib/python3.6/site-packages/flask/app.py", line 943, in run
run_simple(host, port, self, **options)
File "/home/ubuntu/wx_flask/venv_aws_ubuntu18/lib/python3.6/site-packages/werkzeug/serving.py", line 795, in run_simple
s.bind(get_sockaddr(hostname, port, address_family))
PermissionError: [Errno 13] Permission denied
爲了解決這個問題,就必須使用root用戶來運行程序。在sudo情況下,venv環境會失效,因此要指定venv python路徑。用下面命令解決這個問題。
(venv_aws_ubuntu18) ubuntu@ip-172-31-21-46:~/wx_flask$ sudo /home/ubuntu/wx_flask/venv_aws_ubuntu18/bin/python wx_flask.py &
使用PyCharm作爲IDE
安裝的是免費的社區版,感覺很好用。可以查看代碼定義,git管理等,這對於目前的開發來說已經夠用並且十分方便了。
學習bootstrap開發數據錄入界面
1.先學習bootstrap
http://www.runoob.com/bootstrap/bootstrap-tutorial.html
2.flask表單處理
https://zhuanlan.zhihu.com/p/53782945