
Contrast
結(jié)合 Python、MySQL、Redis 發(fā)布訂閱功能,實(shí)現(xiàn) Email 自動(dòng)發(fā)送 HTML 模版郵件.
1. Centos7 上搭建 Python3.6 開發(fā)環(huán)境
這個(gè)可以產(chǎn)考我的另一篇文章CentOS7.3 編譯安裝 Python3.6.2
使用 pip 安裝以下庫(kù)
pip install sqlacodegen
pip install mysql-connector==2.1.4
pip install sqlalchemy
pip install redis
pip install requests
pip install setuptools
pip install pymysql
查看已安裝的庫(kù)
pip list
** pip 升級(jí)包**
pip install --upgrade PackageName
2. 查看Python安裝路徑
Python交互模式下查看Python安裝路徑
>>> import sys
>>> path = sys.executable
>>> print(path)
命令行模式下查看Python安裝路徑
- which python
3. 使用SQLAlchemy創(chuàng)建數(shù)據(jù)模型
pymysql
sqlacodegen mysql+pymysql://root:653155073@192.168.0.107:3306/pythonemail > models.py
也可以導(dǎo)出某一張表的數(shù)據(jù)模型
sqlacodegen mysql+pymysql://root:653155073@192.168.0.107:3306/pyemail --tables test_user > models.py
sqlalchemy
sqlacodegen mysql+mysqlconnector://root:653155073@192.168.0.107:3306/pythonemail > models.py
也可以導(dǎo)出某一張表的數(shù)據(jù)模型
sqlacodegen mysql+mysqlconnector://root:653155073@192.168.0.107:3306/pyemail --tables test_user>models.py
4. 開機(jī)自動(dòng)啟動(dòng)腳本pythonemail
#!/bin/sh
#chkconfig: 23456 80 90
#description:auto_run
lock="subscription.py"
start(){
echo "service start...."
su root -c "/usr/local/bin/python /usr/local/apache2/htdocs/python_email/Subscription/subscription.py &"
}
stop(){
echo "service stop...." pkill -f $lock
}
status(){
if [ -e $lock ];then
echo "$0 service start"
else
echo "$0 service stop"
fi
}
restart(){
stop
start
}
case "$1" in
"start")
start
;;
"stop")
stop
;;
"status")
status
;;
"restart")
restart
;;
*)
echo "$0 start|stop|status|restart"
;;
esac
把腳本 pythonemail 放入 /etc/rc.d/init.d 文件夾下
腳本可以先執(zhí)行一下看看報(bào)不報(bào)錯(cuò)
cd /etc/rc.d/init.d
chmod +x pythonemail
./pythonemail start
賦予腳本權(quán)限
cd /etc/rc.d/init.d
chmod +x pythonemail
chkconfig --add pythonemail
chkconfig --list pythonemail
這樣腳本開機(jī)就會(huì)自動(dòng)運(yùn)行
也可以后臺(tái)靜默執(zhí)行,每一次重新開機(jī)啟動(dòng)需要重新執(zhí)行命令
cd /etc/rc.d/init.d
chmod +x pythonemail
nohup ./pythonemail start &
回車
exit
不能直接關(guān)閉shell窗口,不然不會(huì)在后臺(tái)靜默執(zhí)行,一定要exit退出登錄后,再關(guān)閉shell窗口
Tip:
- CentOS重啟命令:reboot
- 如果郵件發(fā)送不出去也有可能是服務(wù)器端口的問題,需要在服務(wù)器安全組中打開對(duì)應(yīng)的端口.
這里我并不會(huì)講具體的實(shí)現(xiàn),只講前期準(zhǔn)備,具體的代碼實(shí)現(xiàn)參考 Github 上的源碼
結(jié)合 Python、MySQL、Redis 發(fā)布訂閱功能,實(shí)現(xiàn) Email 自動(dòng)發(fā)送,源碼中有詳細(xì)的注釋說明,理解起來不難,歡迎大家提意見.