树莓派数据上传数据库_树莓派与postgre数据库

家附近有个加油站,油价变化挺有意思,基本是某一天跳变到某一个最高值,之后每天降一点,然后保持最低价几天,最后又跳变到一个最高开始新的循环。

决定用树莓派把每日油价自动记录下来,方便油价最低的时候去加油,同时存到数据库里,顺便摸索一下python与数据库的连接。

初始版本是记录到一个text文件里,后来增加了与数据库的连接和insert操作。

系统版本:官方的raspbian

首先安装postgre

sudo apt-get update

sudo apt-get install postgresql

看别人的记录还要装client,我没装好像也没问题

然后切换到数据库管理用户

sudo su postgres

创建一个pi用户,据说因为跟系统用户pi同名,会自动授权pi系统账户去使用pi数据库。

createuser pi -P --interactive

然后切换到pi账户去创建我需要的fuel_price DB。

createdb fuel_price

进入这个DB

psql fuel_check

创建我需要的table

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

检查下有没有创建成功

select * from fuel;

\q 退出数据库

\q

python读取网页需要的数据,同时存进去

提前安装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("今天的油价:",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()

直接拿的之前一个爬小说更新程序改的,写的很烂但是能用。

这里在日期上折腾了好久,一直以为是定义的attribute data type 不对,价格可以存进去,但是日期死活写不进去,后来发现大家喜欢用01/01/2018 这种表示日期,但是斜杠这样不能当作value insert 进去,把斜杠去掉就好了。

最后把这个文件添加到定时任务里,每天早上跑一次,数据的处理还没想好,待续...

crontab -e

image.png

你可能感兴趣的:(树莓派数据上传数据库)