| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217 |
- import math
- import json
- import logging
- import datetime
- import requests
- import db
- import config
- import init_localities
- import util
- _SEARCH_PAGE_SIZE = 50
- _DATETIME_FORMAT = r'%Y-%m-%d %H:%M:%S'
- def _now():
- return datetime.datetime.now().strftime(_DATETIME_FORMAT)
- def process_properties(conn):
- count = conn.select('select count(1) from properties where processed=0')[0]
- if not count:
- return
- print('Processing %i properties...' % count)
- 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, last_update, raw_json from properties where processed=0 limit 10')
- def fetch_properties(conn):
- unknown_properties = conn.select('''
- select distinct sr.property_id
- from search_results sr left join properties p on sr.property_id = p.id
- where p.id is null
- ''')
-
-
- complete = 0
- for batch in util.batches(unknown_properties, 10):
- print('Fetching property details (complete: %i/%i)...' % (complete, len(unknown_properties)))
- stmt = 'insert into properties (id, last_update, raw_json) values'
- params = []
- for property_id in batch:
- resp = requests.get('https://api.myhome.ie/brochure/%i?ApiKey=%s&RequestTypeId=1' % (property_id, config.API_KEY))
- 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())
-
- 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 = {
- 'AddedSince': "",
- 'ApiKey': config.API_KEY,
- 'Page': page,
- 'PageSize': _SEARCH_PAGE_SIZE,
- 'RequestTypeId': 2,
- 'SearchRequest': config.SEARCH_PARAMS,
- 'SortColumn': 2,
- 'SortDirection': 2,
- 'endpoint': {
- 'name': "Search",
- 'paramsName': "SearchRequest",
- },
- 'params': {
- 'RegionId': locality_id
- },
- }
- headers = {
- 'content-type': 'application/json',
- 'accept': 'application/json',
- }
- if num_pages:
- print('Fetching page %i/%i...' % (page, num_pages))
- else:
- print('Fetching page %i...' % page)
- resp = requests.post('https://api.myhome.ie/search?ApiKey=%s' % config.API_KEY, json=body, headers=headers)
- resp.raise_for_status()
- data = resp.json()
- if not isinstance(data, dict):
- print('Error: %s' % data)
- return
- stmt = 'insert into search_results (time, property_id, price, raw_json) VALUES '
- params = []
- for result in data.get('SearchResults', []):
- if not result.get('PriceAsString'):
- continue
- if result['id'] in recent_properties:
- continue
- stmt += '(?, ?, ?, ?),'
- params.extend([
- _now(),
- result['id'],
- result['PriceAsString'].replace(',', '').replace('\u20ac', ''),
- json.dumps(result)
- ])
- inserted += 1
- if params:
- conn.execute(stmt[:-1], *params)
- num_pages = math.ceil(data['ResultCount'] / float(_SEARCH_PAGE_SIZE))
- if page >= num_pages:
- break
-
- 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)
- pass
- else:
- print('You must set MONITORED_LOCATIONS. Possible values: ')
- init_localities.init_localities(conn)
- fetch_properties(conn)
- process_properties(conn)
- if __name__ == '__main__':
- run()
|