My favorites | Sign in
Project Home Downloads Wiki Issues Source
Repository:
Checkout   Browse   Changes   Clones    
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# urlfetcher
#

import sys
import sqlite3
import logging
import urllib2
import bz2
import binascii
import datetime
from hashlib import md5

class UrlFetcher:
''' Url Fetcher '''
def __init__(self, database='urlfetcher.sqlite'):
'''
init

database - database
treads_limit - threads limit
'''
self.__db_conn = sqlite3.connect(database, detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
self.__db_conn.row_factory = sqlite3.Row
self.__db_cursor = self.__db_conn.cursor()

#initial actions with feed database
self.__db_cursor.execute('CREATE TABLE IF NOT EXISTS url_data (url UNIQUE, data, hash, updated);')
self.__db_cursor.execute('CREATE TABLE IF NOT EXISTS journal (url, data, hash, updated);')

# logging
self.__logger = logging.getLogger(database.split('.')[0])
self.__logger.setLevel(logging.DEBUG)
# console handler
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
# formatter
ch.setFormatter(logging.Formatter('%(asctime)s;%(name)s;%(levelname)s:%(message)s'))
self.__logger.addHandler(ch)

self.__TIMEOUT = 60

def log(self, level, message):
'''
logging message
'''
if level == 'debug': self.__logger.debug(message)
elif level == 'info': self.__logger.info(message)
elif level == 'warn': self.__logger.warn(message)
elif level == 'error': self.__logger.error(message)
elif level == 'critical': self.__logger.critical(message)
else: print "Warning! Unkown logging level"

def sync(self):
'''
UrlFetcher DB Commit
'''
self.__db_conn.commit()

def md5calc(self, data):
'''
md5 calculation
'''
return md5(data).hexdigest()

def urls(self):
'''
return list of urls in database
'''
return self.__db_cursor.execute('SELECT url FROM url_data').fetchall()

def url_info(self, url):
'''
get URL data from database
'''
return self.__db_cursor.execute('SELECT * FROM url_data WHERE url = ?', (url,)).fetchone()

def compress_data(self, data):
'''
compress data
'''
return binascii.hexlify(bz2.compress(data))

def add_url(self, url):
'''
add url to database

return:
True - if url was added
False - if url wasn't added
'''
try:
self.__db_cursor.execute('INSERT INTO url_data (url) VALUES (?);', (url,))
self.sync()
return True
except sqlite3.IntegrityError:
return False

def update_url_data(self, url, data, hash, updated):
'''
update url data to database
'''

self.__db_cursor.execute('UPDATE url_data SET data=?, hash=?, updated=? WHERE url=?;',
(self.compress_data(data), hash, updated, url,))
self.sync()

def update_journal_data(self, url, data, hash, updated):
'''
update journal data
'''

self.__db_cursor.execute('INSERT INTO journal (url, data, hash, updated) VALUES (?,?,?,?);',
(url, data, hash, updated,))
self.sync()


def update_urls_data(self):
'''
update url data
'''
for url in self.urls():
url_info = self.url_info(url[0])

try:
try:
data = urllib2.urlopen(url[0], timeout=self.__TIMEOUT).read()
except TypeError:
# for python 2.5
import socket
socket.setdefaulttimeout(self.__TIMEOUT)
data = urllib2.urlopen(url[0]).read()
except IOError:
self.log('error', ('connection failed,%s' % url[0]))
continue

md5data = self.md5calc(data)
if md5data == url_info['hash']:
self.log('info', ('no updates,%s' % url[0]))
continue

self.log('info', ('updated,%s' % url[0]))
self.update_journal_data(url_info['url'], url_info['data'], url_info['hash'], url_info['updated'])
self.update_url_data(url_info['url'], data, md5data, datetime.datetime.now())


if __name__ == '__main__':
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-d", "--database", dest="database", help="UrlFetcher database, by default: urlfetcher.sqlite")
parser.add_option("-a", "--add_url", dest="add_url", help="add url for fecthing")
parser.add_option("-l", "--url_list", action='store_true', dest="url_list",
default=False, help="printout url list from database")
parser.add_option("-u", "--update_urls_data", action='store_true', dest="update_urls_data",
default=False, help="update URLs data")
(options, args) = parser.parse_args()

# definition of database
if options.database:
url_db = UrlFetcher(database=options.database)
else:
url_db = UrlFetcher()

# action: add new url
if options.add_url:
if url_db.add_url(options.add_url):
url_db.log('info', 'URL:%s was added' % options.add_url)
else:
url_db.log('warn', 'URL:%s wasn\'t added' % options.add_url)
sys.exit()

# action: print out list of urls
elif options.url_list:
for url in url_db.urls():
print "%s" % (url[0])
sys.exit()

# action: update for urls data
elif options.update_urls_data:
try:
url_db.update_urls_data()
except KeyboardInterrupt:
print "Interrupted by user"

sys.exit()

Change log

41e904c8d859 by ownport <ownport> on Apr 19, 2010   Diff
urlfetch.py: support for python 2.5
Go to: 
Project members, sign in to write a code review

Older revisions

defa81b97af0 by ownport <ownport> on Mar 21, 2010   Diff
new type of storage rss data in db
be24f4f727bb by ownport <ownport> on Mar 9, 2010   Diff
added new scripts: rss2sqlite.py and
urlfetcher.py
All revisions of this file

File info

Size: 6056 bytes, 188 lines
Powered by Google Project Hosting