樹莓派與postgre數(shù)據(jù)庫

家附近有個(gè)加油站,油價(jià)變化挺有意思,基本是某一天跳變到某一個(gè)最高值,之后每天降一點(diǎn),然后保持最低價(jià)幾天,最后又跳變到一個(gè)最高開始新的循環(huán)。
決定用樹莓派把每日油價(jià)自動(dòng)記錄下來,方便油價(jià)最低的時(shí)候去加油,同時(shí)存到數(shù)據(jù)庫里,順便摸索一下python與數(shù)據(jù)庫的連接。
初始版本是記錄到一個(gè)text文件里,后來增加了與數(shù)據(jù)庫的連接和insert操作。
系統(tǒng)版本:官方的raspbian
首先安裝postgre

sudo apt-get update
sudo apt-get install postgresql

看別人的記錄還要裝client,我沒裝好像也沒問題
然后切換到數(shù)據(jù)庫管理用戶

sudo su postgres

創(chuàng)建一個(gè)pi用戶,據(jù)說因?yàn)楦到y(tǒng)用戶pi同名,會(huì)自動(dòng)授權(quán)pi系統(tǒng)賬戶去使用pi數(shù)據(jù)庫。

createuser pi -P --interactive

然后切換到pi賬戶去創(chuàng)建我需要的fuel_price DB。

createdb fuel_price

進(jìn)入這個(gè)DB

psql fuel_check

創(chuàng)建我需要的table

create table fuel(current_date1 text primary key, price text);

檢查下有沒有創(chuàng)建成功

select * from fuel;

\q 退出數(shù)據(jù)庫

\q

python讀取網(wǎng)頁需要的數(shù)據(jù),同時(shí)存進(jìn)去
提前安裝python3的psycopg2

sudo apt-get install python3-Psycopg2
from urllib import request
import time
import psycopg2
req = request.Request('https://www.fuelcheck.nsw.gov.au/app/FuelPrice/ByLocation?latitude=-33.945423&longitude=151.246243&fuelType=U91&radius=4&suburb=MAROU$
req.add_header('User-Agent', 'Mozilla/6.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/8.0 Mobile/10A5376e Safar$
port_num=[]
keywords='Coles Express Maroubra","Lat":-33.949944,"Long":151.240710,"Price":'
with request.urlopen(req) as f:
    port_num.append(f.read().decode('GBK'))
    # print(port_num)
    start=port_num[0].find(keywords)
    # print(start)
    port_num.append(port_num[0][(start+len(keywords)):(start+len(keywords)+5)])

print("今天的油價(jià):",port_num[1])
print ("今日的日期:" + time.strftime("%d/%m/%Y"))
date1=str(time.strftime("%d%m%Y"))
today_recording=[time.strftime("%d/%m/%Y"),port_num[1]]
with open('/home/pi/spider/fuel/fuel_recording', 'a') as f:
    f.write(str(today_recording)+'\n')

conn = psycopg2.connect(dbname="fuel_price", user="pi",
        password="731731", host="127.0.0.1", port="5432")
cur = conn.cursor()
cur.execute("INSERT INTO fuel "
       "VALUES(%s,%s);"%(date1,port_num[1]))
conn.commit()
cur.close()
conn.close()

直接拿的之前一個(gè)爬小說更新程序改的,寫的很爛但是能用。
這里在日期上折騰了好久,一直以為是定義的attribute data type 不對,價(jià)格可以存進(jìn)去,但是日期死活寫不進(jìn)去,后來發(fā)現(xiàn)大家喜歡用01/01/2018 這種表示日期,但是斜杠這樣不能當(dāng)作value insert 進(jìn)去,把斜杠去掉就好了。
最后把這個(gè)文件添加到定時(shí)任務(wù)里,每天早上跑一次,數(shù)據(jù)的處理還沒想好,待續(xù)...

crontab -e
image.png

[參考了這篇](https://linux.cn/article-9056-1.html
[官方說明](http://www.postgresqltutorial.com/postgresql-python/

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容