mercredi 11 février 2015

Cron executed python script runs but does not update sqlite db

My python script (creates if needed) and inserts one row into an sqlite database. It works perfectly when run manually, but not when run by cron. When run by cron it will create the db file, without a schema, and also not insert the row.


Additionally, the command is set in my normal user's crontab, but the empty db file is owned by root.


This is the line in my crontab:



0/3 * * * * /home/ubuntu/fullstack/scrape.py


And this is the python script:



#!/usr/bin/env python
# -*- coding: utf-8 -*-

#file scrape.py

import urllib2
import json
import datetime
import time
import sqlite3

from datetime import timedelta

response = urllib2.urlopen('http://ift.tt/1vZ6vTM')
res = response.read()
date = response.info()['date']
# Sun, 19 Oct 2014 17:58:01 GMT
datetime = datetime.datetime.strptime(date, '%a, %d %b %Y %H:%M:%S %Z')
datetime = datetime - timedelta(hours=5)
timestamp = int(time.mktime(datetime.timetuple()))
response.close()
res = json.loads(res)

title = res['items'][0]['title']
url = res['items'][0]['url']
points = res['items'][0]['points']



db = sqlite3.connect('/home/ubuntu/fullstack/interval_data.db')
cursor = db.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS data(id INTEGER PRIMARY KEY NOT NULL UNIQUE, title TEXT, url TEXT, points INTEGER, timestamp INTEGER, datetime TEXT);
''')
db.commit()

cursor.execute('''INSERT INTO data(title, url, points, timestamp, datetime)
VALUES(?, ?, ?, ?, ?);''', (title, url, points, timestamp, datetime.strftime('%d %b %Y, %I:%M %p %z')))
db.commit()




db.close()

Aucun commentaire:

Enregistrer un commentaire