官术网_书友最值得收藏!

Understanding the get_address() function

This is an integral, though a potentially error-prone, component of our script because it relies on the user correctly supplying data. The code itself is just a simple data request. However, when working with user supplied arguments, it isn't safe to assume that the user gave the script the correct data. Considering the length and somewhat random-looking sequence of a Bitcoin address, it's entirely possible that the user might supply an incorrect address. We'll catch any instance of URLError from the urllib.error module to handle a malformed input. URLError isn't part of the built-in exceptions we've talked about before and is a custom exception defined by the urrlib module:

053 def get_address(address):
054 """
055 The get_address function uses the blockchain.info Data API
056 to pull pull down account information and transactions for
057 address of interest
058 :param address: The Bitcoin Address to lookup
059 :return: The response of the url request
060 """

On line 62, we insert the user-supplied address into the blockchain.info API call using the string format() method. Then, we try to return the data requested using the urllib.request.urlopen() function. If the user supplies an invalid address or if the user doesn't have an internet connection, URLError will be caught. Once the error has been caught, we notify the user and exit the script, calling sys.exit(1) on line 67:

061     url = 'https://blockchain.info/address/{}?format=json'
062 formatted_url = url.format(address)
063 try:
064 return urllib.request.urlopen(formatted_url)
065 except urllib.error.URLError:
066 print('Received URL Error for {}'.format(formatted_url))
067 sys.exit(1)
主站蜘蛛池模板: 九江市| 分宜县| 宝坻区| 堆龙德庆县| 米泉市| 沙洋县| 德安县| 兴山县| 绩溪县| 武陟县| 巩义市| 新建县| 孝昌县| 图们市| 绥中县| 安泽县| 博客| 碌曲县| 秦皇岛市| 台东市| 洛隆县| 安宁市| 鹰潭市| 高雄县| 神农架林区| 吴川市| 财经| 南岸区| 徐州市| 武隆县| 深州市| 惠东县| 汾西县| 松阳县| 临沧市| 包头市| 威海市| 长沙市| 揭东县| 元阳县| 安国市|