|
| 1 | +import requests |
| 2 | +from decimal import Decimal |
| 3 | +from time import gmtime, strftime |
| 4 | +from sys import argv |
| 5 | + |
| 6 | + |
| 7 | +def currency_rates(find_currency): |
| 8 | + '''решение через str''' |
| 9 | + req = requests.get('http://www.cbr.ru/scripts/XML_daily.asp') |
| 10 | + if req.status_code == 200: # check connection |
| 11 | + dat = req.headers |
| 12 | + li_date = dat['Date'] |
| 13 | + res_date = strftime(li_date, gmtime()) |
| 14 | + all_text = req.text |
| 15 | + lines = all_text.split('/Valute') |
| 16 | + for currency in lines: |
| 17 | + if '/ValCurs' in currency: |
| 18 | + return None |
| 19 | + char_code = cleaner(currency, 'CharCode') |
| 20 | + name = cleaner(currency, 'Name') |
| 21 | + value = cleaner(currency, 'Value') |
| 22 | + '''decimal создан специально для финансовых расчетов''' |
| 23 | + value = Decimal(value) |
| 24 | + if char_code == find_currency.upper(): |
| 25 | + print(f'{char_code} один {name} стоит {value} рублей') |
| 26 | + return value, res_date |
| 27 | + else: |
| 28 | + print('bad connection') |
| 29 | + |
| 30 | + |
| 31 | +def cleaner(currency, val): |
| 32 | + '''clean values''' |
| 33 | + try: |
| 34 | + val = currency.split(val)[1] |
| 35 | + except IndexError as e: |
| 36 | + # pass |
| 37 | + print(e) |
| 38 | + li = ['<', '>', '/'] |
| 39 | + for i in li: |
| 40 | + val = val.replace(i, '') |
| 41 | + val = val.replace(',', '.') |
| 42 | + val = val.strip() |
| 43 | + return val |
| 44 | + |
| 45 | + |
| 46 | +if __name__ == '__main__': |
| 47 | + if len(argv) > 1: |
| 48 | + res = currency_rates(argv[1]) |
| 49 | + print(str(res)) |
| 50 | + elif 2 < len(argv): |
| 51 | + for i in argv[1:]: |
| 52 | + res = currency_rates(argv[1]) |
| 53 | + print(str(res)) |
0 commit comments