| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147 |
- import math
- import json
- import logging
- import datetime
- import requests
- import db
- import config
- import init_localities
- import util
- _SEARCH_PAGE_SIZE = 50
- def _now():
- return datetime.datetime.now().strftime(r'%Y-%m-%d %H:%M:%S')
- 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, raw_json from properties where processed=0 limit 10')
- while rows:
- rows = conn.select('select id, 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))
- data = resp.json()['Brochure']['Property']
- stmt += ' (?, ?, ?),'
- params.extend([
- property_id,
- _now(),
- json.dumps(data)
- ])
-
- conn.execute(stmt[:-1], *params)
- complete += len(batch)
- def search(conn, locality_id):
- logging.info('Searching %i...', locality_id)
-
- page = 1
- num_pages = None
- 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
- stmt += '(?, ?, ?, ?),'
- params.extend([
- _now(),
- result['id'],
- result['PriceAsString'].replace(',', '').replace('\u20ac', ''),
- json.dumps(result)
- ])
- conn.execute(stmt[:-1], *params)
- num_pages = math.ceil(data['ResultCount'] / float(_SEARCH_PAGE_SIZE))
- if page >= num_pages:
- break
-
- page += 1
- 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()
|