소스 검색

property processing

Martin 8 년 전
부모
커밋
68e9b7543f
4개의 변경된 파일과 110개의 추가작업 그리고 21개의 파일을 삭제
  1. 2 2
      config.py
  2. 24 0
      db_schema.py
  3. 0 5
      init_localities.py
  4. 84 14
      monitor.py

+ 2 - 2
config.py

@@ -18,12 +18,12 @@ SEARCH_PARAMS = {
     'LocalityIds': [],
     'MaxBeds': "",
     'MaxEnergyRating': "",
-    'MaxPrice': "500000",
+    'MaxPrice': "600000",
     'MaxSize': "",
     'MinBathrooms': "1",
     'MinBeds': "2",
     'MinEnergyRating': "",
-    'MinPrice': "200000",
+    'MinPrice': "100000",
     'MinSize': "",
     'NegotiatorIds': [],
     'PreSixtyThree': False,

+ 24 - 0
db_schema.py

@@ -38,4 +38,28 @@ SCHEMA_STATEMENTS = [
     'alter table properties add column lon float;',
     'alter table properties add column size;',
     'alter table properties add column ber varchar(255);',
+
+    'drop table properties;',
+
+    '''
+    create table properties (
+        id integer not null primary key,
+        last_update datetime not null,
+        raw_json text,
+        processed tinyint default 0 not null,
+        price integer,
+        lat float,
+        lon float,
+        size integer,
+        ber varchar(255)
+    )
+    ''',
+
+    'alter table properties add column address varchar(1023)',
+    'alter table properties add column locality_id integer',
+    'alter table properties add column property_type varchar(255)',
+    'alter table properties add column bathrooms integer',
+    'alter table properties add column bedrooms integer',
+    
+    
 ]

+ 0 - 5
init_localities.py

@@ -16,15 +16,10 @@ def _init_relationships(conn, locality_id):
     resp.raise_for_status()
     data = resp.json()
 
-    print('checking %i' % locality_id)
-
-
-    print(data)
     for obj in _extract_localities(data):
         pk = '%i_%i' % (obj['LocalityId'], locality_id)
         conn.execute('replace into locality_relationships (id, parent, child) values (?,?, ?)', pk, locality_id, obj['LocalityId'])
 
-
 def init_localities(conn, locality_id=None):
     logging.info('Loading known localities...')
     known = set(conn.select('select id from localities'))

+ 84 - 14
monitor.py

@@ -13,8 +13,10 @@ import util
 
 _SEARCH_PAGE_SIZE = 50
 
+_DATETIME_FORMAT = r'%Y-%m-%d %H:%M:%S'
+
 def _now():
-    return datetime.datetime.now().strftime(r'%Y-%m-%d %H:%M:%S')
+    return datetime.datetime.now().strftime(_DATETIME_FORMAT)
 
 def process_properties(conn):
     count = conn.select('select count(1) from properties where processed=0')[0]
@@ -23,10 +25,49 @@ def process_properties(conn):
 
     print('Processing %i properties...' % count)
 
-    rows = conn.select('select id, raw_json from properties where processed=0 limit 10')
+    rows = conn.select('select id, last_update, raw_json from properties where processed=0 limit 50')
     while rows:
+        stmt = 'replace into properties (id, last_update, raw_json, processed, price, lat, lon, size, ber, address, locality_id, property_type, bathrooms, bedrooms) values'
+        params = []
+
+        for property_id, last_update, raw_json  in rows:
+            stmt += ' (?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?),'
+
+            params.extend([
+                    property_id,
+                    last_update,
+                    raw_json,
+            ])
+
+            if raw_json is None:
+                params.extend([None] * 10)
+            
+            else:
+                data = json.loads(raw_json)
+
+                size = None
+                if data.get('SizeStringMeters'):
+                    size = data.get('SizeStringMeters')
+                elif data.get('SizeStringFeet'):
+                    size = round(data.get('SizeStringFeet') * 0.09290304, 2)
+
+                params.extend([
+                    data.get('Price', {}).get('MinPrice'),
+                    data.get('BrochureMap', {}).get('latitude'),
+                    data.get('BrochureMap', {}).get('longitude'),
+                    size,
+                    data.get('BerRating'),
+                    data.get('DisplayAddress', data.get('Address')),
+                    data.get('LocalityId'),
+                    data.get('PropertyType'),
+                    data.get('Bathrooms', data.get('BathString', '').replace(' baths', '') or None),
+                    data.get('BedsString', '').replace(' beds', '') or None,
+                ])
+
+        if params:
+            conn.execute(stmt[:-1], *params)
 
-        rows = conn.select('select id, raw_json from properties where processed=0 limit 10')
+        rows = conn.select('select id, last_update, raw_json from properties where processed=0 limit 10')
 
 
 
@@ -48,23 +89,44 @@ def fetch_properties(conn):
 
         for property_id in batch:
             resp = requests.get('https://api.myhome.ie/brochure/%i?ApiKey=%s&RequestTypeId=1' % (property_id, config.API_KEY))
-            data = resp.json()['Brochure']['Property']
-            stmt += ' (?, ?, ?),'
-            params.extend([
-                property_id,
-                _now(),
-                json.dumps(data)
-            ])
+
+            if resp.json() in ["The property you requested isn't available any more", "The property you requested is inactive and can't be found"]:
+                stmt += ' (?, ?, ?),'
+                params.extend([
+                    property_id,
+                    _now(),
+                    None,
+                ])
+
+            else:
+                try:
+                    data = resp.json()['Brochure']['Property']
+                    stmt += ' (?, ?, ?),'
+                    params.extend([
+                        property_id,
+                        _now(),
+                        json.dumps(data)
+                    ])
+                except Exception as e:
+                    print(str(e))
+                    print(resp.json())
         
-        conn.execute(stmt[:-1], *params)
+        if params:
+            conn.execute(stmt[:-1], *params)
 
         complete += len(batch)
 
 def search(conn, locality_id):
     logging.info('Searching %i...', locality_id)
     
+    cutoff = (datetime.datetime.now() - datetime.timedelta(hours=20)).strftime(_DATETIME_FORMAT)
+
+    recent_properties = set(conn.select('''select property_id from (select property_id, max(time) m 
+                                           from search_results group by property_id) where m > ?''', cutoff))
+
     page = 1
     num_pages = None
+    inserted = 0
 
     while True:
         body = {
@@ -110,6 +172,8 @@ def search(conn, locality_id):
         for result in data.get('SearchResults', []):
             if not result.get('PriceAsString'):
                 continue
+            if result['id'] in recent_properties:
+                continue
 
             stmt += '(?, ?, ?, ?),' 
 
@@ -120,7 +184,10 @@ def search(conn, locality_id):
                 json.dumps(result)
             ])
 
-        conn.execute(stmt[:-1], *params)
+            inserted += 1
+
+        if params:
+            conn.execute(stmt[:-1], *params)
 
         num_pages = math.ceil(data['ResultCount'] / float(_SEARCH_PAGE_SIZE))
 
@@ -129,19 +196,22 @@ def search(conn, locality_id):
         
         page += 1
 
+    print('Search complete. %i records inserted.' % inserted)
+
 def run():
     with db.connect() as conn:
         if config.MONITORED_LOCALITIES:
             for locality_id in config.MONITORED_LOCALITIES:
                 # init_localities.init_localities(conn, locality_id=locality_id)
-                search(conn, 1265)
+                # search(conn, 1265)
                 pass
+
         else:
             print('You must set MONITORED_LOCATIONS. Possible values: ')
             init_localities.init_localities(conn)
 
         fetch_properties(conn)
-        # process_properties(conn)
+        process_properties(conn)
 
 if __name__ == '__main__':
     run()