def settings(request): access_token = request.user.social_auth.get( provider='drchrono').extra_data['access_token'] current_doctor = call_api(access_token, API_ADDR + 'users/current') if current_doctor == False: return redirect('home') doctor_id = current_doctor['doctor'] if request.method == POST: form = AppointmentSelectionForm(request.POST) if form.is_valid(): appt_id = form.cleaned_data.get('appt_id') #url = API_ADDR+'appointments/'+str(appt_id) #result = patch_api(access_token, url, {'status': 'Cancelled'}) visit = Appointment.objects.get_or_none(appt_id=str(appt_id)) if visit: visit.delete() instance = Kiosk.objects.get_or_none(doctor_id=doctor_id) if not instance: logout(request) return redirect('home') date_range = str(datetime.date.today() - datetime.timedelta( hours=instance.hours_before)) + '/' + str( datetime.date.today() + datetime.timedelta(hours=instance.hours_after)) appts_response = call_api(instance.access_token, API_ADDR + 'appointments', { 'doctor': instance.doctor_id, 'date_range': date_range }) if appts_response == False: return redirect('home') appts_for_day = [] for appt in appts_response['results']: # returned in order if appt['scheduled_time']: appt_time = dateutil.parser.parse(appt['scheduled_time']) tz = timezone.get_current_timezone() appt_time = tz.localize(appt_time) if appt['patient']: appt_object = {} appt_object['status'] = appt['status'] appt_object['id'] = appt['id'] appt_object['patient'] = appt['patient'] appt_object[ 'scheduled_time'] = appt_time if appt_time else "Unavailable" appts_for_day.append(appt_object) return render(request, 'admin.html', {'appts_for_day': appts_for_day})
def update(request, instance_guid): if request.method == POST: form = PatientVerificationForm(request.POST) if form.is_valid(): instance = Kiosk.objects.get_or_none(guid=instance_guid) if not instance: return redirect('home') appt_id = form.cleaned_data.get('appt_id') appt = call_api(instance.access_token, API_ADDR + 'appointments/' + str(appt_id)) if appt == False: return redirect('home') if appt['doctor'] != instance.doctor_id or appt['status'] not in ( '', 'Confirmed'): return redirect('error', instance_guid=instance_guid) patient = call_api(instance.access_token, API_ADDR + 'patients/' + str(appt['patient'])) if patient == False: return redirect('home') if patient['gender'] and patient[ 'gender'] != form.cleaned_data.get('gender'): return redirect('error', instance_guid=instance_guid) if patient['first_name'] and patient[ 'first_name'] != form.cleaned_data.get('first_name'): return redirect('error', instance_guid=instance_guid) if patient['last_name'] and patient[ 'last_name'] != form.cleaned_data.get('last_name'): return redirect('error', instance_guid=instance_guid) if patient['date_of_birth'] and str( patient['date_of_birth']) != str( form.cleaned_data.get('date_of_birth')): return redirect('error', instance_guid=instance_guid) patient['appt_id'] = appt_id update_form = PatientUpdateForm(initial=patient) return render(request, 'update.html', { 'form': update_form, 'instance_guid': instance_guid }) else: return redirect('error', instance_guid=instance_guid) else: return redirect('error', instance_guid=instance_guid)
def checkin(request, instance_guid): if request.method == 'POST': form = AppointmentSelectionForm(request.POST) if form.is_valid(): instance = Kiosk.objects.get_or_none(guid=instance_guid) if not instance: return redirect('home') appt_id = form.cleaned_data.get('appt_id') appt = call_api(instance.access_token, API_ADDR + 'appointments/' + str(appt_id)) if appt == False: return redirect('home') if appt['doctor'] != instance.doctor_id or appt['status'] not in ( '', 'Confirmed'): return redirect('error', instance_guid=instance_guid) form = PatientVerificationForm(initial={'appt_id': appt_id}) return render(request, 'verification.html', { 'form': form, 'instance_guid': instance_guid }) else: return redirect('error', instance_guid=instance_guid) else: return redirect('error', instance_guid=instance_guid)
def pushtx(self, tx): """ """ if not re.match('^[0-9a-fA-F]*$', tx): tx = tx.encode('hex') return call_api(self._base_url, 'api/tx/send', {'rawtx': tx})
def create_wallet(password, api_code, priv=None, label=None, email=None): """Create a new Blockchain.info wallet. It can be created containing a pre-generated private key or will otherwise generate a new private key. :param str password: password for the new wallet. At least 10 characters. :param str api_code: API code with create wallets permission :param str priv: private key to add to the wallet (optional) :param str label: label for the first address in the wallet (optional) :param str email: email to associate with the new wallet (optional) :return: an instance of :class:`WalletResponse` class """ params = {'password': password, 'api_code': api_code} if priv is not None: params['priv'] = priv if label is not None: params['label'] = label if email is not None: params['email'] = email response = util.call_api("api/v2/create_wallet", params) json_response = json.loads(response) return CreateWalletResponse(json_response['guid'], json_response['address'], json_response['link'])
def get_tx_confirmation(self, tx): """In block chain info, there is no api to get transaction confirmation """ block_count = call_api(self._base_url, 'q/getblockcount') source = 'tx/{}?show_adv=false&format=json'.format(tx) data = call_api(self._base_url, source) try: jsonobj = json.loads(data) except: raise Exception("Failed to decode data: "+data) block_height = jsonobj['block_height'] return int(block_count) - int(block_height) + 1
def __find_active_app_id_by_name(self, name): request = Request(self.gearpump_uri + GearpumpApiConfig.call_applist, headers=self.__create_user_headers_with_cookies()) json = util.call_api(request) for app in json['appMasters']: if app['appName'] == name and app['status'] == 'active': return app['appId']
def get_balance(self, address): """call api to get the balance of address in BTC """ data = call_api(self._base_url, 'address/balance/{}'.format(address)) try: jsonobj = json.loads(data) except: raise Exception('Failed to decode data: '+data) return jsonobj['data']['balance']
def get_tx_confirmation(self, tx): """call blockr api to get tx's confirmation """ data = call_api(self._base_url, 'tx/info/{}'.format(tx)) try: jsonobj = json.loads(data) except: raise Exception('Failed to decode data: '+data) return jsonobj['data']['confirmations']
def get_balance(self): """Fetch the wallet balance. Includes unconfirmed transactions and possibly double spends. :return: wallet balance in satoshi """ response = util.call_api("merchant/{0}/balance".format(self.identifier), self.build_basic_request()) json_response = json.loads(response) self.parse_error(json_response) return json_response.get('balance')
def history(self, address): """ """ data = call_api(self._base_url, 'api/txs/?address={}'.format(address)) try: jsonobj = json.loads(data) except: raise Exception('Failed to decode data: '+data) return jsonobj['txs']
def get_latest_block(api_code=None): """Get the latest block on the main chain. :param str api_code: Blockchain.info API code (optional) :return: an instance of :class:`LatestBlock` class """ resource = '/api/getblockcount' if api_code is not None: resource += '?api_code=' + api_code response = util.call_api(resource) return response
def get_tx_info(self, tx): """call our node's api to get the information of transaction """ data = call_api(self._base_url, 'api/tx/{}'.format(tx)) try: jsonobj = json.loads(data) except: raise Exception('Failed to decode data: '+data) return jsonobj
def get_addr_info(self, address): """call our node's api to get the information of address """ data = call_api(self._base_url, 'api/addr/{}'.format(address)) try: jsonobj = json.loads(data) except: raise Exception('Failed to decode data: '+data) return jsonobj
def get_inventory_data(hash, api_code=None): """Get inventory data. :param str hash: tx or block hash :param str api_code: Blockchain.info API code (optional) :return: an instance of :class:`InventoryData` class """ resource = "inv/{0}?format=json".format(hash) if api_code is not None: resource += "&api_code=" + api_code response = util.call_api(resource) json_response = json.loads(response) return InventoryData(json_response)
def to_btc(ccy, value, api_code = None): """Call the 'tobtc' method and convert x value in the provided currency to BTC. :param str ccy: currency code :param float value: value to convert :param str api_code: Blockchain.info API code :return: the value in BTC """ res = 'tobtc?currency={0}&value={1}'.format(ccy, value) if api_code is not None: res += '&api_code=' + api_code return util.call_api(res)
def create_user(user_info): return call_api( 'POST', '/users', { 'action': 'custCreate', 'user_info': { 'email': user_info['username'], 'type': '2', # Licensed 'first_name': user_info['first_name'], 'last_name': user_info['last_name'] } }).json()
def get_unconfirmed_tx(api_code = None): """Get a list of currently unconfirmed transactions. :param str api_code: Blockchain.info API code (optional) :return: an array of :class:`Transaction` objects """ resource = 'unconfirmed-transactions?format=json' if api_code is not None: resource += '&api_code=' + api_code response = util.call_api(resource) json_response = json.loads(response) return [Transaction(t) for t in json_response['txs']]
def get_block_hash(block_id, api_code=None): """Get a single block based on a block hash. :param str block_id: block hash to look up :param str api_code: Blockchain.info API code (optional) :return: an instance of :class:`Block` class """ resource = '/api/getblockhash?index=' + block_id log(resource) if api_code is not None: resource += '&api_code=' + api_code response = util.call_api(resource) return response
def get_latest_block(api_code=None): """Get the latest block on the main chain. :param str api_code: Blockchain.info API code (optional) :return: an instance of :class:`LatestBlock` class """ resource = "latestblock" if api_code is not None: resource += "?api_code=" + api_code response = util.call_api(resource) json_response = json.loads(response) return LatestBlock(json_response)
def get_tx(tx_id, api_code=None): """Get a single transaction based on a transaction hash. :param str tx_id: transaction hash to look up :param str api_code: Blockchain.info API code (optional) :return: an instance of :class:`Transaction` class """ log(tx_id) resource = '/api/getrawtransaction?txid=' + tx_id if api_code is not None: resource += '?api_code=' + api_code response = util.call_api(resource) json_response = json.loads(response) return Transaction(json_response)
def get_inventory_data(hash, api_code = None): """Get inventory data. :param str hash: tx or block hash :param str api_code: Blockchain.info API code (optional) :return: an instance of :class:`InventoryData` class """ resource = 'inv/{0}?format=json'.format(hash) if api_code is not None: resource += '&api_code=' + api_code response = util.call_api(resource) json_response = json.loads(response) return InventoryData(json_response)
def unarchive_address(self, address): """Unarchive an address. :param str address: address to unarchive :return: string representation of the unarchived address """ params = self.build_basic_request() params['address'] = address response = util.call_api("merchant/{0}/unarchive_address".format(self.identifier), params) json_response = json.loads(response) self.parse_error(json_response) return json_response['active']
def to_btc(ccy, value, api_code=None): """Call the 'tobtc' method and convert x value in the provided currency to BTC. :param str ccy: currency code :param float value: value to convert :param str api_code: Blockchain.info API code :return: the value in BTC """ res = 'tobtc?currency={0}&value={1}'.format(ccy, value) if api_code is not None: res += '&api_code=' + api_code return util.call_api(res)
def get_unconfirmed_tx(api_code=None): """Get a list of currently unconfirmed transactions. :param str api_code: Blockchain.info API code (optional) :return: an array of :class:`Transaction` objects """ resource = "unconfirmed-transactions?format=json" if api_code is not None: resource += "&api_code=" + api_code response = util.call_api(resource) json_response = json.loads(response) return [Transaction(t) for t in json_response["txs"]]
def get(api_code=None): """Get network statistics. :param str api_code: Blockchain.info API code (optional) :return: an instance of :class:`Stats` class """ resource = 'stats?format=json' if api_code is not None: resource += '&api_code=' + api_code response = util.call_api(resource) json_response = json.loads(response) return Stats(json_response)
def get_balance(self): """Fetch the wallet balance. Includes unconfirmed transactions and possibly double spends. :return: wallet balance in satoshi """ response = util.call_api( "merchant/{0}/balance".format(self.identifier), self.build_basic_request()) json_response = json.loads(response) self.parse_error(json_response) return json_response.get('balance')
def get_block_height(height, api_code = None): """Get an array of blocks at the specified height. :param int height: block height to look up :param str api_code: Blockchain.info API code (optional) :return: an array of :class:`Block` objects """ resource = 'block-height/{0}?format=json'.format(height) if api_code is not None: resource += '&api_code=' + api_code response = util.call_api(resource) json_response = json.loads(response) return [Block(b) for b in json_response['blocks']]
def get_balance(address, filter=None, api_code=None): """Get balances for each address provided. :param tuple addresses: addresses(xpub or base58) to look up :param FilterType filter: the filter for transactions selection (optional) :param str api_code: Blockchain.info API code (optional) :return: a dictionary of str, :class:`Balance` """ resource = '/ext/getbalance/' + address log(resource) if api_code is not None: resource += '&api_code=' + api_code response = util.call_api(resource) return response
def history(self, address): """call api to get the tx history of this address """ data = call_api(self._base_url, 'address/txs/{}'.format(address)) try: jsonobj = json.loads(data) except: raise Exception('Failed to decode data: '+data) # TODO: # will this return a list of dict? return jsonobj['data']['txs']
def get_tx(tx_id, api_code=None): """Get a single transaction based on a transaction index or hash. :param str block_id: transaction hash or index to look up :param str api_code: Blockchain.info API code (optional) :return: an instance of :class:`Transaction` class """ resource = "rawtx/" + tx_id if api_code is not None: resource += "?api_code=" + api_code response = util.call_api(resource) json_response = json.loads(response) return Transaction(json_response)
def get_address(address, api_code=None): """Get data for a single address. :param str address: address to look up :param str api_code: Blockchain.info API code (optional) :return: an instance of :class:`Address` class """ resource = "rawaddr/" + address if api_code is not None: resource += "?api_code=" + api_code response = util.call_api(resource) json_response = json.loads(response) return Address(json_response)
def get_block_height(height, api_code=None): """Get an array of blocks at the specified height. :param int height: block height to look up :param str api_code: Blockchain.info API code (optional) :return: an array of :class:`Block` objects """ resource = "block-height/{0}?format=json".format(height) if api_code is not None: resource += "&api_code=" + api_code response = util.call_api(resource) json_response = json.loads(response) return [Block(b) for b in json_response["blocks"]]
def get_address(address, api_code = None): """Get data for a single address. :param str address: address to look up :param str api_code: Blockchain.info API code (optional) :return: an instance of :class:`Address` class """ resource = 'rawaddr/' + address if api_code is not None: resource += '?api_code=' + api_code response = util.call_api(resource) json_response = json.loads(response) return Address(json_response)
def get_unspent_outputs(address, api_code=None): """Get unspent outputs for a single address. :param str address: address to look up :param str api_code: Blockchain.info API code (optional) :return: an array of :class:`UnspentOutput` objects """ resource = "unspent?active=" + address if api_code is not None: resource += "&api_code=" + api_code response = util.call_api(resource) json_response = json.loads(response) return [UnspentOutput(o) for o in json_response["unspent_outputs"]]
def get_unspent_outputs(address, api_code = None): """Get unspent outputs for a single address. :param str address: address to look up :param str api_code: Blockchain.info API code (optional) :return: an array of :class:`UnspentOutput` objects """ resource = 'unspent?active=' + address if api_code is not None: resource += '&api_code=' + api_code response = util.call_api(resource) json_response = json.loads(response) return [UnspentOutput(o) for o in json_response['unspent_outputs']]
def get_block(block_id, api_code=None): """Get a single block based on a block index or hash. :param str block_id: block hash or index to look up :param str api_code: Blockchain.info API code (optional) :return: an instance of :class:`Block` class """ resource = "rawblock/" + block_id if api_code is not None: resource += "?api_code=" + api_code response = util.call_api(resource) json_response = json.loads(response) return Block(json_response)
def get_block(block_id, api_code = None): """Get a single block based on a block index or hash. :param str block_id: block hash or index to look up :param str api_code: Blockchain.info API code (optional) :return: an instance of :class:`Block` class """ resource = 'rawblock/' + block_id if api_code is not None: resource += '?api_code=' + api_code response = util.call_api(resource) json_response = json.loads(response) return Block(json_response)
def unarchive_address(self, address): """Unarchive an address. :param str address: address to unarchive :return: string representation of the unarchived address """ params = self.build_basic_request() params['address'] = address response = util.call_api( "merchant/{0}/unarchive_address".format(self.identifier), params) json_response = json.loads(response) self.parse_error(json_response) return json_response['active']
def consolidate(self, days): """Consolidate the wallet addresses. :param int days: addresses which have not received any transactions in at least this many days will be consolidated. :return: a string array of consolidated addresses """ params = self.build_basic_request() params['days'] = days response = util.call_api("merchant/{0}/auto_consolidate".format(self.identifier), params) json_response = json.loads(response) self.parse_error(json_response) return json_response['consolidated']
def main(request): result = {} if not request.user.is_authenticated(): return render(request, 'index.html', {}) user_access_status = access_status(request.user) if user_access_status != STATUS_OK: logout(request) return render(request, 'index.html', {'user_access_status': user_access_status}) access_token = request.user.social_auth.get( provider='drchrono').extra_data['access_token'] # calling the API logger.info('calling the api with %s') try: current_doctor = call_api(access_token, API_ADDR + 'users/current') doctor_info = call_api( access_token, API_ADDR + 'doctors/' + str(current_doctor['doctor'])) except urllib2.HTTPError as e: logging.info("Http Error with %s" % e) logout(request) return render(request, 'index.html', {'user_access_status': False}) # get kiosk kiosk_instance = updateKoisk(request, Kiosk, current_doctor, doctor_info, timezone) # get waiting updateWaiting(current_doctor, Average_wait) logout(request) return redirect('kiosk', instance_guid=kiosk_instance.guid)
def consolidate(self, days): """Consolidate the wallet addresses. :param int days: addresses which have not received any transactions in at least this many days will be consolidated. :return: a string array of consolidated addresses """ params = self.build_basic_request() params['days'] = days response = util.call_api( "merchant/{0}/auto_consolidate".format(self.identifier), params) json_response = json.loads(response) self.parse_error(json_response) return json_response['consolidated']
def new_address(self, label = None): """Generate a new address and add it to the wallet. :param str label: label to attach to this address (optional) :return: an instance of :class:`Address` class """ params = self.build_basic_request() if label is not None: params['label'] = label response = util.call_api("merchant/{0}/new_address".format(self.identifier), params) json_response = json.loads(response) self.parse_error(json_response) return Address(0, json_response['address'], json_response['label'], 0)
def get_currency_rate(self, currency_type): """use bitcoin api rate give the param currency_type to get correspond value """ data = call_api(self._base_url, 'ticker') try: jsonobj = json.loads(data) except: raise Exception('Failed to decode data: '+data) try: rate = jsonobj[currency_type] except: raise Exception('unsupported currency') return rate['last']
def get_address(self, address, confirmations = 0): """Retrieve an address from the wallet. :param str address: address in the wallet to look up :param int confirmations: minimum number of confirmations transactions must have before being included in the balance (optional) :return: an instance of :class:`Address` class """ params = self.build_basic_request() params['address'] = address params['confirmations'] = confirmations response = util.call_api("merchant/{0}/address_balance".format(self.identifier), params) json_response = json.loads(response) self.parse_error(json_response) return Address(json_response['balance'], json_response['address'], None, json_response['total_received'])
def get_ticker(api_code = None): """Call the 'ticker' method and return a dictionary of :class:`Currency` objects. :param str api_code: Blockchain.info API code (optional) :return: a dictionary in the format of ccy_symbol(str):currency(:class:`Currency`) """ response = util.call_api('ticker' if api_code is None else 'ticker?api_code=' + api_code) json_response = json.loads(response) ticker = {} for key in json_response: json_ccy = json_response[key] ccy = Currency(json_ccy['last'], json_ccy['buy'], json_ccy['sell'], json_ccy['symbol'], json_ccy['15m']) ticker[key] = ccy return ticker
def list_addresses(self, confirmations = 0): """List all active addresses in the wallet. :param int confirmations: minimum number of confirmations transactions must have before being included in balance of addresses (optional) :return: an array of :class:`Address` objects """ params = self.build_basic_request() params['confirmations'] = confirmations response = util.call_api("merchant/{0}/list".format(self.identifier), params) json_response = json.loads(response) self.parse_error(json_response) addresses = [] for a in json_response['addresses']: address = Address(a['balance'], a['address'], a['label'], a['total_received']) addresses.append(address) return addresses
def send_many(self, recipients, from_address = None, fee = None, note = None): """Send bitcoin from your wallet to multiple addresses. :param dictionary recipients: dictionary with the structure of 'address':amount :param str from_address: specific address to send from (optional) :param int fee: transaction fee in satoshi. Must be greater than the default fee (optional). :param str note: public note to include with the transaction (optional) :return: an instance of :class:`PaymentResponse` class """ params = self.build_basic_request() method = '' if len(recipients) == 1: to_address, amount = recipients.popitem() params['to'] = to_address params['amount'] = amount method = 'payment' else: params['recipients'] = json.dumps(recipients) method = 'sendmany' if from_address is not None: params['from'] = from_address if fee is not None: params['fee'] = fee if note is not None: params['note'] = note response = util.call_api("merchant/{0}/{1}".format(self.identifier, method), params) json_response = json.loads(response) self.parse_error(json_response) payment_response = PaymentResponse( json_response['message'], json_response['tx_hash'], json_response.get('notice')) return payment_response
def unspent(self, address): """to get unspen of the address """ result = [] try: data = call_api(self._base_url, 'unspent?address='+address) except Exception as e: print(e) try: jsonobj = json.loads(data) for obj in jsonobj['unspent_outputs']: # to get tx_hash big endian h = obj['tx_hash_big_endian'] result.append({ "output": h+':'+str(obj['tx_output_n']), "value": obj['value'] }) except: raise Exception("Failed to decode data: "+data) return result
def get_blocks(time=None, pool_name=None, api_code=None): """Get a list of blocks for a specific day or mining pool. Both parameters are optional but at least one is required. :param int time: time in milliseconds :param str pool_name: name of the mining pool :param str api_code: Blockchain.info API code (optional) :return: an array of :class:`SimpleBlock` objects """ resource = "blocks/{0}?format=json" if api_code is not None: resource += "&api_code=" + api_code if time is not None: resource = resource.format(time) elif pool_name is not None: resource = resource.format(pool_name) else: resource = resource.format("") response = util.call_api(resource) json_response = json.loads(response) return [SimpleBlock(b) for b in json_response["blocks"]]
def __kill_app(self, app_id): request = Request(self.gearpump_uri + GearpumpApiConfig.call_appmaster + "/" + str(app_id), headers=self.__create_user_headers_with_cookies()) request.get_method = lambda: 'DELETE' return util.call_api(request)