瀏覽代碼

mapping of properties to locality ancestors

Martin 8 年之前
父節點
當前提交
cf82104399
共有 4 個文件被更改,包括 60 次插入 和 4 次删除
  1. 4 2
      config.py
  2. 7 0
      db_schema.py
  3. 3 0
      init_localities.py
  4. 46 2
      monitor.py

+ 4 - 2
config.py

@@ -4,7 +4,9 @@ BASE = 'https://api.myhome.ie'
 DB_PATH = 'data.db'
 
 MONITORED_LOCALITIES = [
-    1265, # Dublin
+    1265, # Co Dublin
+    4011, # Co Wicklow
+    3587, # Co Tipp
 ]
 
 SEARCH_PARAMS = {
@@ -34,7 +36,7 @@ SEARCH_PARAMS = {
     'PropertyTypeIds': [],
     'Query': "",
     'RegionGroup': 2168,
-    'RegionId': "1265",
+    'RegionId': None, # to be set to a locality id
     'SaleTypeIds': [],
     'SearchContent': False,
     'SortBy': "Most Recent",

+ 7 - 0
db_schema.py

@@ -61,5 +61,12 @@ SCHEMA_STATEMENTS = [
     'alter table properties add column bathrooms integer',
     'alter table properties add column bedrooms integer',
     
+    '''
+    create table property_locality_map (
+        id varchar(255) primary key not null,
+        property_id integer not null,
+        locality_id integer not null
+    )
+    ''',
     
 ]

+ 3 - 0
init_localities.py

@@ -34,6 +34,9 @@ def init_localities(conn, locality_id=None):
         for x in data:
             print('%s: %s' % (x['id'], x['name']))
 
+            if not x['name'].startswith(' '):
+                conn.execute('replace into localities (id, name) values (?,?)', x['id'], x['name'])
+
     else:
         resp = requests.get('https://api.myhome.ie/localities/%s?ApiKey=%s&classId=1' % (locality_id, config.API_KEY))
         resp.raise_for_status()

+ 46 - 2
monitor.py

@@ -1,3 +1,4 @@
+import collections
 import math
 import json
 import logging
@@ -18,11 +19,32 @@ _DATETIME_FORMAT = r'%Y-%m-%d %H:%M:%S'
 def _now():
     return datetime.datetime.now().strftime(_DATETIME_FORMAT)
 
+def get_locality_tree(conn):
+    parents = {}
+    for parent, child in conn.select('select parent, child from locality_relationships'):
+        parents[child] = parent
+
+    roots = set()
+    locality_ancestors = collections.defaultdict(list)
+
+    for child, parent in parents.items():
+        locality_ancestors[child].append(parent)
+        while parents.get(parent):
+            locality_ancestors[child].append(parents[parent])
+            parent = parents[parent]
+        roots.add(parent)
+    
+    return roots, parents, locality_ancestors
+
 def process_properties(conn):
     count = conn.select('select count(1) from properties where processed=0')[0]
     if not count:
         return
 
+    _, _, locality_ancestors = get_locality_tree(conn)
+
+    
+
     print('Processing %i properties...' % count)
 
     rows = conn.select('select id, last_update, raw_json from properties where processed=0 limit 50')
@@ -30,6 +52,8 @@ def process_properties(conn):
         stmt = 'replace into properties (id, last_update, raw_json, processed, price, lat, lon, size, ber, address, locality_id, property_type, bathrooms, bedrooms) values'
         params = []
 
+        property_localities = []
+
         for property_id, last_update, raw_json  in rows:
             stmt += ' (?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?),'
 
@@ -64,6 +88,24 @@ def process_properties(conn):
                     data.get('BedsString', '').replace(' beds', '') or None,
                 ])
 
+                if data.get('LocalityId'):
+                    property_localities.append((property_id, data.get('LocalityId')))
+
+        if params:
+            conn.execute(stmt[:-1], *params)
+
+        stmt = 'replace into property_locality_map (id, property_id, locality_id) values'
+        params = []
+        for property_id, locality_id in property_localities:
+            ancestors = [locality_id] + locality_ancestors.get(locality_id, [])
+            for ancestor in ancestors:
+                stmt += ' (?, ?, ?),'
+                params.extend([
+                    '%i_%i' % (property_id, ancestor),
+                    property_id,
+                    ancestor
+                ])
+        
         if params:
             conn.execute(stmt[:-1], *params)
 
@@ -129,6 +171,8 @@ def search(conn, locality_id):
     inserted = 0
 
     while True:
+        config.SEARCH_PARAMS['RegionId'] = str(locality_id)
+        
         body = {
             'AddedSince': "",
             'ApiKey': config.API_KEY,
@@ -202,8 +246,8 @@ 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)
+                init_localities.init_localities(conn, locality_id=locality_id)
+                search(conn, locality_id)
                 pass
 
         else: