-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtickets.py
111 lines (93 loc) · 3.42 KB
/
tickets.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# coding: utf-8
"""命令行火车票查看器
Usage:
tickets [-dgktz] <from> <to> <date>
Options:
-h, --help 查看帮助
-d 动车
-g 高铁
-k 快速
-t 特快
-z 直达
Examples:
tickets 上海 北京 2017-03-24
tickets -dg 成都 南京 2017-03-24
"""
import requests
from docopt import docopt
from prettytable import PrettyTable
from colorama import init, Fore
from stations import stations
"""
docopt --creates beautiful command-line interfaces //格式化命令行参数
prettytable -- beautiful table format //输出标准的table格式
colorama -- colored text can then be done using //着色
"""
init()
class TrainsCollection:
header = '车次 车站 时间 历时 一等 二等 软卧 硬卧 硬座 无座'.split()
def __init__(self, available_trains, options):
"""查询到的火车班次集合
:param available_trains: 一个列表, 包含可获得的火车班次, 每个火车班次是一个字典
:param options: 查询的选项, 如高铁, 动车, etc...
"""
self.available_trains = available_trains
self.options = options
def _get_duration(self, raw_train):
duration = raw_train.get('lishi').replace(':', '小时') + '分'
if duration.startswith('00'):
return duration[4:]
if duration.startswith('0'):
return duration[1:]
return duration
@property
def trains(self):
for raw_train in self.available_trains:
raw_train = raw_train['queryLeftNewDTO']
train_no = raw_train['station_train_code']
initial = train_no[0].lower()
if not self.options or initial in self.options:
train = [
train_no,
'\n'.join([Fore.GREEN + raw_train['from_station_name'] + Fore.RESET,
Fore.RED + raw_train['to_station_name'] + Fore.RESET]),
'\n'.join([Fore.GREEN + raw_train['start_time'] + Fore.RESET,
Fore.RED + raw_train['arrive_time'] + Fore.RESET]),
self._get_duration(raw_train),
raw_train['zy_num'],
raw_train['ze_num'],
raw_train['rw_num'],
raw_train['yw_num'],
raw_train['yz_num'],
raw_train['wz_num'],
]
yield train
def pretty_print(self):
pt = PrettyTable()
pt._set_field_names(self.header)
for train in self.trains:
pt.add_row(train)
print(pt)
def cli():
"""Command-line interface"""
arguments = docopt(__doc__)
from_station = stations.get(arguments['<from>'])
to_station = stations.get(arguments['<to>'])
date = arguments['<date>']
url = ('https://kyfw.12306.cn/otn/leftTicket/query?'
'leftTicketDTO.train_date={}&'
'leftTicketDTO.from_station={}&leftTicketDTO.to_station={}&purpose_codes=ADULT').format(
date, from_station, to_station
)
options = ''.join([
key for key, value in arguments.items() if value is True
])
r = requests.get(url, verify=False)
res = r.json()
if 'data' in res.keys():
available_trains = res['data']
TrainsCollection(available_trains, options).pretty_print()
else:
print('没有数据')
if __name__ == '__main__':
cli()