def click_information(): arguments = docopt(__doc__) from_station = station.get(arguments['<from>']) to_station = station.get(arguments['<to>']) date = arguments['<date>'] #判断日期和车站是否合法 if station_vaild(arguments['<from>'], arguments['<to>']): if date_format(date): if date_vaild(date): if date_scope(date): #设置查询余票的url url = 'https://kyfw.12306.cn/otn/lcxxcx/query?purpose_codes=ADULT&queryDate={}&from_station={}&to_station={}'.format( date, from_station, to_station) #设置http头信息 headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.110 Safari/537.36", "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "Accept-Encoding": "gzip, deflate, sdch", "Accept-Language": "zh-CN,zh;q=0.8", "Cache-Control": "max-age=0", "Connection": "keep-alive" } #获取数据 try: r = requests.get(url, headers=headers, verify=False) rows = r.json()['data']['datas'] except: print '无法得到数据,可能票已售完。' else: #创建类info_analysis的对象 train_data = info_analysis(rows) result = train_data.pretty_table() return result
def get_room_info(room): resp = hue_requests.get('sensors/' + domostats.sensor_id[room]) temperature = round(resp['state']['temperature'] / 100 + TEMP_OFFSET[room], 1) time_hue = resp['state']['lastupdated'] time_str = utils.date_format(utils.date_diff_hours(time_hue), '%Y-%m-%dT%H:%M:%S') return temperature, time_str
def race_calendar(year=None): """ Get information on the current Formula 1 calendar. :return race_list: A list of the races this F1 season. """ # If year is None or invalid, request current standings. try: year = int(year) url = 'https://ergast.com/api/f1/{}.json'.format(year) except ValueError: url = 'https://ergast.com/api/f1/current.json' except TypeError: url = 'https://ergast.com/api/f1/current.json' response = requests.get(url) if not response.ok: return [] try: data = json.loads(response.text) race_dict = {'year': data['MRData']['RaceTable']['season']} race_list = [] for race in data['MRData']['RaceTable']['Races']: date_text = race['date'] date_datetime = utils.return_datetime(date_text) date_text = utils.date_format(date_text) round_n = race['round'] circuit = race['Circuit']['circuitName'] circuit_url = race['Circuit']['url'] locality = race['Circuit']['Location']['locality'] race = race['raceName'] race_info = { 'round': round_n, 'circuit': circuit, 'url': circuit_url, 'locality': locality, 'race': race, 'date': { 'text': date_text, 'datetime': date_datetime } } race_list.append(race_info) race_dict['Races'] = race_list return race_dict except ValueError: return []
def jsonify_order(data): order = data['order'] line_items = [] for line_item in order.line_items: line_items.append({ 'seq': line_item.line_item_seq, 'id': line_item.id, 'title': line_item.item.title, 'description': line_item.item.description.text, 'final_amount': line_item.final_amount, 'assignee_details': line_item.item.assignee_details, 'assignee': jsonify_assignee(line_item.current_assignee), 'is_confirmed': line_item.is_confirmed, 'is_cancelled': line_item.is_cancelled, 'cancelled_at': date_format(line_item.cancelled_at) if line_item.cancelled_at else "", }) return jsonify(order_id=order.id, access_token=order.access_token, item_collection_name=order.item_collection.description_text, buyer_name=order.buyer_fullname, buyer_email=order.buyer_email, buyer_phone=order.buyer_phone, line_items=line_items)
def get_rates(currency, start_date, end_date): csv_file_path = generate_file_path(currency, start_date, end_date) if os.path.isfile(csv_file_path): return url = "http://www.nbrb.by/API/ExRates/Rates/Dynamics/{}?startDate={}&endDate={}" request = url.format( currency, "-".join(start_date.split("-")[::-1]), "-".join(end_date.split("-")[::-1]), ) data = json.loads(safe_request(request).text) df = pd.DataFrame({ "day": [date_format(i["Date"]) for i in data], "rate": [i["Cur_OfficialRate"] for i in data], }) with open(generate_file_path(currency, start_date, end_date), "w") as csv_file: csv_file.write(df.to_csv(index=False))
def qualifying_results(round_n=None, season=None): """ Get relevant information for a current-year Formula 1 qualifying session. If no round number is passed, the most-recent qualifying data is provided. :param round_n: Round number for the qualifying session. :param season: The year of the qualifying session. :return driver_dict: A dict containing driver results and round info. """ if round_n is None: if season is None: # Most-recent qualifying, current season. url = 'https://ergast.com/api/f1/current/last/qualifying.json' else: # Most-recent qualifying, specific season. url = 'https://ergast.com/api/f1/{}/last/qualifying.json'.format( season) else: if season is None: # Specific qualifying, current season. url = 'https://ergast.com/api/f1/current/{}/qualifying.json'.format( round_n) else: # Specific qualifying, specific season. url = 'https://ergast.com/api/f1/{}/{}/qualifying.json'.format( season, round_n) response = requests.get(url) if not response.ok: return {} try: data = json.loads(response.text) # If the race has not happened yet. if not data['MRData']['RaceTable']['Races']: return {} """ The loop uses range instead of foreach because it references the previous driver's qualifying time by index[i-1] to compare them. """ driver_list = [] for i in range( len(data['MRData']['RaceTable']['Races'][0] ['QualifyingResults'])): fn = data['MRData']['RaceTable']['Races'][0]['QualifyingResults'][ i]['Driver']['givenName'] ln = data['MRData']['RaceTable']['Races'][0]['QualifyingResults'][ i]['Driver']['familyName'] url = data['MRData']['RaceTable']['Races'][0]['QualifyingResults'][ i]['Driver']['url'] pos = data['MRData']['RaceTable']['Races'][0]['QualifyingResults'][ i]['position'] try: # Drivers may not partake in Q1. q1_text = data['MRData']['RaceTable']['Races'][0][ 'QualifyingResults'][i]['Q1'] q1_secs = total_seconds(q1_text) except KeyError: q1_text = '-' q1_secs = '-' try: # Drivers eliminated in Q1 won't be in Q2. q2_text = data['MRData']['RaceTable']['Races'][0][ 'QualifyingResults'][i]['Q2'] q2_secs = total_seconds(q2_text) except KeyError: q2_text = '-' q2_secs = '-' try: # Drivers eliminated in Q2 won't be in Q3. q3_text = data['MRData']['RaceTable']['Races'][0][ 'QualifyingResults'][i]['Q3'] q3_secs = total_seconds(q3_text) # Check the driver position. Cannot reference the previous driver if they are position 1. if int(data['MRData']['RaceTable']['Races'][0] ['QualifyingResults'][i]['position']) > 1: # Subtract the faster driver's time from the current driver to find the delta. q3_delta = round( q3_secs - total_seconds(data['MRData']['RaceTable']['Races'][0] ['QualifyingResults'][i - 1]['Q3']), 4) else: q3_delta = '' except KeyError: q3_text = '-' q3_secs = '-' q3_delta = '' driver_qualifying = { 'fn': fn, 'ln': ln, 'url': url, 'pos': pos, 'q1': { 'text': q1_text, 'seconds': q1_secs }, 'q2': { 'text': q2_text, 'seconds': q2_secs }, 'q3': { 'text': q3_text, 'seconds': q3_secs, 'delta': q3_delta } } driver_list.append(driver_qualifying) driver_dict = {'Driver': driver_list} round_n = data['MRData']['RaceTable']['Races'][0]['round'] season = data['MRData']['RaceTable']['Races'][0]['season'] date = date_format( data['MRData']['RaceTable']['Races'][0]['date']) # Format date. race = data['MRData']['RaceTable']['Races'][0]['raceName'] circuit = data['MRData']['RaceTable']['Races'][0]['Circuit'][ 'circuitName'] circuit_url = data['MRData']['RaceTable']['Races'][0]['Circuit']['url'] driver_dict['RoundInfo'] = { 'race': race, 'circuit': circuit, 'url': circuit_url, 'round': round_n, 'season': season, 'date': date } return driver_dict except ValueError: return {}
def race_results(round_n=None, season=None): """ Get relevant information for a current-year Formula 1 race. If no round number is passed, the most-recent race data is provided. :param round_n: Round number for the race. :param season: The year of the race. :return driver_dict: A dict containing driver results and round info. """ if round_n is None: if season is None: # Most-recent race, current season. url = 'https://ergast.com/api/f1/current/last/results.json' else: # Most-recent race, specific season. url = 'https://ergast.com/api/f1/{}/last/results.json'.format( season) else: if season is None: # Specific race, current season. url = 'https://ergast.com/api/f1/current/{}/results.json'.format( round_n) else: # Specific race, specific season. url = 'https://ergast.com/api/f1/{}/{}/results.json'.format( season, round_n) response = requests.get(url) if not response.ok: return {} try: data = json.loads(response.text) # If the race has not happened yet. if not data['MRData']['RaceTable']['Races']: return {} driver_list = [] for driver in data['MRData']['RaceTable']['Races'][0]['Results']: fn = driver['Driver']['givenName'] ln = driver['Driver']['familyName'] url = driver['Driver']['url'] cons = driver['Constructor']['name'] points = driver['points'] pos = driver['position'] try: time = driver['Time']['time'] except KeyError: # Times are only given for un-lapped drivers. time = driver[ 'status'] # Make time the number of laps behind or retired. try: best_lap = driver['FastestLap']['Time']['time'] rank = driver['FastestLap']['rank'] except KeyError: best_lap = '-' rank = None driver_race_info = { 'fn': fn, 'ln': ln, 'url': url, 'cons': cons, 'points': points, 'pos': pos, 'time': time, 'bestLap': { 'text': best_lap, 'rank': rank } } driver_list.append(driver_race_info) driver_dict = {'Driver': driver_list} round_n = data['MRData']['RaceTable']['Races'][0]['round'] season = data['MRData']['RaceTable']['Races'][0]['season'] date = date_format( data['MRData']['RaceTable']['Races'][0]['date']) # Format date. race = data['MRData']['RaceTable']['Races'][0]['raceName'] circuit = data['MRData']['RaceTable']['Races'][0]['Circuit'][ 'circuitName'] circuit_url = data['MRData']['RaceTable']['Races'][0]['Circuit']['url'] driver_dict['RoundInfo'] = { 'race': race, 'circuit': circuit, 'url': circuit_url, 'round': round_n, 'season': season, 'date': date } return driver_dict except ValueError: return {}
def cancel_line_item(line_item): if not line_item.is_cancellable(): return make_response(jsonify(status='error', error='non_cancellable', error_description='This ticket is not cancellable'), 403) refund_amount = process_line_item_cancellation(line_item) send_line_item_cancellation_mail.delay(line_item.id, refund_amount) return make_response(jsonify(status='ok', result={'message': 'Ticket cancelled', 'cancelled_at': date_format(line_item.cancelled_at)}), 200)
def room_status(room): temperature, time = get_room_info(room) return '{:.1f}ºC'.format( temperature) + ' in the ' + room + ' at ' + utils.date_format( time, '%H:%M on %d/%m/%Y')