yqzj微信公衆號&小程序開發

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

參考解決方案:
https://stackoverflow.com/questions/51700960/runtimeerror-generator-raised-stopiteration-every-time-i-try-to-run-app

把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

每日一句 crash

每日一句 crash消息
123.24.75.113 - - [09/Mar/2019 10:05:18] “GET / HTTP/1.0” 404 -
pycharm 遠程調試?
退出ssh連接,服務就報錯?
因爲代碼中加入了print語句,ssh連接退出後,找不到輸出終端。

git 放棄本地修改並獲取服務器代碼

git branch -a //查看branch名稱
git reset --hard origin/master
git pull

微信小程序開發

目前公衆號“每日一句”功能已經上線。後面計劃能夠提供給用戶自己輸入材料的功能,這需要用到微信小程序。目前瞭解到小程序前端是使用JavaScript,後端可以使用雲開發,也可以使用普通的後端服務器開發。雲開發需要熟悉nodejs的內容,優點是不用搭建服務端,省去了備案等麻煩事,缺點是雲函數個數有限制,nodejs的開發需要學習。普通後端服務器的開發可以利用之前公衆號已經搭建起來的flask後臺,缺點是小程序的後端服務器必須要備案。

  1. 官方入門指南
    https://developers.weixin.qq.com/miniprogram/dev/quickstart/basic/getstart.html
    按照上面的順序,安裝開發環境,開啓雲開發功能等。這個時候已經可以在自己的手機上運行一個開發板的樣例小程序了。
    在這裏插入圖片描述

  2. JavaScript學習

推薦liaoxuefeng的個人博客,理解匿名函數,箭頭函數,閉包,promise等基本概念
https://www.liaoxuefeng.com/wiki/001434446689867b27157e896e74d51a89c25cc8b43bdb3000

對async、await的理解
https://segmentfault.com/a/1190000007535316?utm_source=tag-newest

2.瞭解普通開發模式下,前端和後端的交互
https://blog.csdn.net/jsyzliuyu/article/details/81878336

  1. 入門慕課視頻課程
    https://www.imooc.com/course/list?c=fe

準備在自己mac上用virtualbox模擬aws雲服務器,先本地開發。
Ubuntu鏡像國內地址:
http://mirrors.163.com/ubuntu-releases/bionic/
http://mirrors.163.com/centos/
安裝Ubuntu鏡像
ubuntu-18.04.2-live-server-amd64.iso

1)virtualbox 共享文件失敗

https://blog.csdn.net/l349074299/article/details/77869317
對於一個新的虛擬機系統,使用mount -t vboxsf AAA /mnt/BBB時出現下面問題:
“wrong fs type,bad option,bad superblock…”
這個問題是因爲系統沒有安裝VMBOX增強插件,使用以下命令可以解決:

sudo apt install nfs-common
sudo apt install cifs-utils
sudo apt install virtualbox-guest-utils
2)主機ssh連接虛擬主機
使用橋接網絡,ifconfig 獲取IP地址,然後使用主機的ssh進行連接。

3)ubuntu 開機運行 rc.local
ubuntu18.04不再使用initd管理系統,改用systemd。
使用systemd設置開機啓動
爲了像以前一樣,在/etc/rc.local中設置開機啓動程序,需要以下幾步:
(1)
systemd默認讀取/etc/systemd/system下的配置文件,該目錄下的文件會鏈接/lib/systemd/system/下的文件。一般系統安裝完/lib/systemd/system/下會有rc-local.service文件,即我們需要的配置文件。
鏈接過來:

ln -fs /lib/systemd/system/rc-local.service /etc/systemd/system/rc-local.service 

查看 rc-local.service 內容可以看到開機執行的文件爲 rc.local.
(2)
創建/etc/rc.local文件
touch /etc/rc.local
chmod 777 /etc/rc.local
rc.local 文件內容:

#!/bin/sh
sudo mount -t vboxsf github_directory /mnt/pcshare

4)以root身份運行
虛擬機服務器:
如果是第一次獲得Root權限那麼首先要設置root密碼
~$ sudo passwd root
獲取root權限:~$ su root
輸入之前你設置的密碼
退出root:~$ exit

安裝ssh server
sudo apt install openssh-server

編輯配置文件,讓其支持root用戶登錄,因爲默認是不支持root用戶的。
sudo vi /etc/ssh/sshd_config
把其中的“PermitRootLogin prohibit-password” 修改爲“PermitRootLogin yes”
重啓openssh服務。
systemctl restart sshd(server服務)

本地pc機 ssh root登陸:
ssh [email protected]

5)python 中文支持
在編寫Python時,當使用中文輸出或註釋時運行腳本,會提示錯誤信息:
SyntaxError: Non-ASCII character ‘\xe5’ in file
Python的默認編碼文件是用的ASCII碼,而你的python文件中使用了中文等非英語字符。
在Python源文件的最開始一行,加入一句:

# coding=UTF-8

2019.5.12 wx_flasky run success in virtualbox ubuntu-18.04.2-live-server-amd64.iso

2019.5.19
把“慕課”上的樣例代碼加入到了工程中,可以pycharm寫代碼,微信開發者工具看效果。通過Photoshop完成了主頁面的修改,發佈體驗版1.0.0.

5)靜態ip配置

sudo vim /etc/netplan/xxxx.ymal

然後在ethernet部分添加以下配置。

network:
    ethernets:
        ens33:
            addresses:
            - 192.168.4.254/24
            dhcp4: false
            nameservers:
                addresses:
                - 8.8.8.8
                search: []
    version: 2 

sudo netplan apply

6)c語言編譯工具安裝
sudo apt install (make gcc g++ 等)
如果有些庫找不到
試輸入sudoapt-get install gcc-multilib即可

2019.8.10 利奇馬臺風

  1. use vscode as the ide for this project.
  2. add api_suna for suna’s mini program.
  3. modify the shell script, so that I can deploy it to aws server easily.

在這裏插入圖片描述
flask support multiple db:
http://www.pythondoc.com/flask-sqlalchemy/binds.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章