"""Tratok Labs API client for Python 3.8 or newer. One file, standard library only. Version 1.0.0, made from API description 1.5.0. https://developer.tratok.net/libraries.php Keep your secret on a server. Never put it in a web page or in an app that people download. from tratok_labs import TratokLabs, TratokLabsError labs = TratokLabs('YOUR_APP_ID', 'YOUR_SECRET') try: found = labs.search_cruises(region='caribbean', limit=3) print(found['total'], found['items']) except TratokLabsError as e: print(e.code, e.message, e.request_id) Every method takes the fields of the reference as keyword arguments and returns the answer of the API as a dictionary. A refused call raises TratokLabsError. Field names may be written as in the reference (nightsMin) or in Python style (nights_min): https://developer.tratok.net/docs.php You may use, copy and change this file in your own projects. It comes without warranty of any kind. """ import json import re import socket import urllib.error import urllib.request VERSION = '1.0.0' __all__ = ['TratokLabs', 'TratokLabsError', 'VERSION'] class TratokLabsError(Exception): """A call that was refused, or that never got an answer.""" def __init__(self, message, code='unknown', status=0, request_id=None, retry_after=None, body=None): super().__init__(message) self.message = message self.code = code # the short code of the API, such as invalid_credentials; 'network' or 'timeout' when no answer came self.status = status # the HTTP status; 0 when no answer came self.request_id = request_id # quote this if you write to us self.retry_after = retry_after # seconds to wait, with rate_limited self.body = body # the whole answer, when there was one def _camel(name): """nights_min -> nightsMin; a name already written as in the reference is left as it is.""" return re.sub(r'_([a-z0-9])', lambda m: m.group(1).upper(), name) def _number(headers, name): value = headers.get(name) try: return int(value) if value not in (None, '') else None except ValueError: return None class TratokLabs: def __init__(self, app_id, secret, base_url='https://developer.tratok.net/v1/', timeout=30): if not app_id or not secret: raise ValueError('TratokLabs needs an app ID and a secret') self.app_id = str(app_id) self.secret = str(secret) # your secret, or a test key for the booking test mode self.base_url = base_url self.timeout = timeout # Facts about the last answer: status, request_id, rate_limit_limit, rate_limit_remaining, # rate_limit_reset, free_calls_remaining. self.last_meta = None def call(self, method, **fields): """Call any method by its name. Fields that are None are not sent.""" body = {'request': str(method), 'id': self.app_id, 'secret': self.secret} for key, value in fields.items(): if value is not None: body[_camel(key)] = value request = urllib.request.Request( self.base_url, data=json.dumps(body).encode('utf-8'), method='POST', headers={'Content-Type': 'application/json', 'Accept': 'application/json', 'User-Agent': 'tratok-labs-python/' + VERSION}) try: with urllib.request.urlopen(request, timeout=self.timeout) as response: status, headers, raw = response.status, response.headers, response.read() except urllib.error.HTTPError as e: # the API answered with an error status: read its answer status, headers, raw = e.code, e.headers, e.read() except (socket.timeout, TimeoutError) as e: raise TratokLabsError('The call timed out', code='timeout') from e except Exception as e: # no answer at all: no network, a refused connection reason = getattr(e, 'reason', e) if isinstance(reason, (socket.timeout, TimeoutError)): raise TratokLabsError('The call timed out', code='timeout') from e raise TratokLabsError('The call could not be made: %s' % reason, code='network') from e self.last_meta = { 'status': status, 'request_id': headers.get('X-Request-Id'), 'rate_limit_limit': _number(headers, 'X-RateLimit-Limit'), 'rate_limit_remaining': _number(headers, 'X-RateLimit-Remaining'), 'rate_limit_reset': _number(headers, 'X-RateLimit-Reset'), 'free_calls_remaining': _number(headers, 'X-Free-Calls-Remaining'), } text = raw.decode('utf-8', 'replace') try: data = json.loads(text) except ValueError: data = None if not isinstance(data, dict): raise TratokLabsError('The answer was not JSON (HTTP %d)' % status, code='bad_answer', status=status, request_id=self.last_meta['request_id'], body=text) if status >= 400 or data.get('status') == 'Error': raise TratokLabsError(data.get('message') or 'The call was refused', code=data.get('code') or 'unknown', status=status, request_id=data.get('requestId') or self.last_meta['request_id'], retry_after=data.get('retryAfter'), body=data) return data # Hotels def hotels_in_country(self, **fields): """hotelsInCountry. Fields: country.""" return self.call('hotelsInCountry', **fields) def hotels_in_city(self, **fields): """hotelsInCity. Fields: city.""" return self.call('hotelsInCity', **fields) def get_hotel_information(self, **fields): """getHotelInformation. Fields: hotelId.""" return self.call('getHotelInformation', **fields) def get_hotel_gallery(self, **fields): """getHotelGallery. Fields: hotelId.""" return self.call('getHotelGallery', **fields) # Car rentals def get_list_of_car_cities(self, **fields): """getListOfCarCities. No fields.""" return self.call('getListOfCarCities', **fields) def get_list_of_all_car_venues_in_city(self, **fields): """getListOfAllCarVenuesInCity. Fields: city.""" return self.call('getListOfAllCarVenuesInCity', **fields) def get_list_of_cars_at_venue(self, **fields): """getListOfCarsAtVenue. Fields: locationId.""" return self.call('getListOfCarsAtVenue', **fields) # Cruises def search_cruises(self, **fields): """searchCruises. Fields: q?, region?, lineId?, port?, month?, nightsMin?, nightsMax?, priceMax?, sort?, limit?, offset?. (? = optional)""" return self.call('searchCruises', **fields) def get_cruise(self, **fields): """getCruise. Fields: cruiseId.""" return self.call('getCruise', **fields) def get_cruise_regions(self, **fields): """getCruiseRegions. No fields.""" return self.call('getCruiseRegions', **fields) def get_cruise_lines(self, **fields): """getCruiseLines. No fields.""" return self.call('getCruiseLines', **fields) # Translation def supported_languages(self, **fields): """supportedLanguages. No fields.""" return self.call('supportedLanguages', **fields) def detect_language(self, **fields): """detectLanguage. Fields: text.""" return self.call('detectLanguage', **fields) def translate(self, **fields): """translate. Fields: text, sourceLanguage?, targetLanguage. (? = optional)""" return self.call('translate', **fields) # Tara AI def tara_chat(self, **fields): """taraChat. Fields: message, conversationId?, maxTokens?. (? = optional)""" return self.call('taraChat', **fields) def tara_reset(self, **fields): """taraReset. Fields: conversationId.""" return self.call('taraReset', **fields) # Inventory and booking def search_stays(self, **fields): """searchStays. Fields: q?, city?, country?, nearLat?, nearLng?, radiusKm?, limit?, offset?. (? = optional)""" return self.call('searchStays', **fields) def search_activities(self, **fields): """searchActivities. Fields: q?, city?, country?, nearLat?, nearLng?, radiusKm?, limit?, offset?. (? = optional)""" return self.call('searchActivities', **fields) def search_restaurants(self, **fields): """searchRestaurants. Fields: q?, city?, country?, nearLat?, nearLng?, radiusKm?, limit?, offset?. (? = optional)""" return self.call('searchRestaurants', **fields) def get_listing(self, **fields): """getListing. Fields: vertical?, listingId. (? = optional)""" return self.call('getListing', **fields) def get_quote(self, **fields): """getQuote. Fields: accessToken, vertical, listingId, roomId?, packageId?, checkIn?, checkOut?, guests?, date?, participants?, time?, party?. (? = optional)""" return self.call('getQuote', **fields) def book_listing(self, **fields): """bookListing. Fields: accessToken, vertical?, listingId?, roomId?, packageId?, checkIn?, checkOut?, guests?, date?, participants?, time?, party?, quoteId, idempotencyKey, guestName?, guestPhone?, notes?. (? = optional)""" return self.call('bookListing', **fields) def my_bookings(self, **fields): """myBookings. Fields: accessToken, tab?. (? = optional)""" return self.call('myBookings', **fields) def get_booking(self, **fields): """getBooking. Fields: accessToken, bookingId.""" return self.call('getBooking', **fields) def cancel_booking(self, **fields): """cancelBooking. Fields: accessToken, bookingId.""" return self.call('cancelBooking', **fields)