Skip to content

数据导出示例

以下是用python3创建行程数据的导出任务,并轮训任务状态的示例。

 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
import time
import requests


class UbiOpenApiExportClient(object):
    EXPORT_USER_API = 'v1/export/users'
    EXPORT_TRIP_API = 'v1/export/trips'
    EXPORT_EVENT_API = 'v1/export/event'
    EXPORT_SCORE_API = 'v1/export/safety-score'
    JOB_STATUS_API = 'v1/job/{jobId}/status'

    def __init__(self, host, app_code):
        self.HOST = host
        self._create_session(app_code)

    def _create_session(self, app_code):
        self.session = requests.Session()
        self.session.headers.update({'Authorization': 'APPCODE ' + app_code})

    def export_users(self):
        d = self.session.get(self.HOST + self.EXPORT_USER_API)
        jobId = d.json()['jobId']
        return jobId

    def export_trips(self, startTime='2022-01-01'):
        d = self.session.get(self.HOST + self.EXPORT_TRIP_API, params={'startTime': startTime})
        jobId = d.json()['jobId']
        return jobId

    def export_events(self, startTime='2022-01-01'):
        d = self.session.get(self.HOST + self.EXPORT_EVENT_API,  params={'startTime': startTime})
        jobId = d.json()['jobId']
        return jobId

    def export_scores(self, startTime='2022-01-01'):
        d = self.session.get(self.HOST + self.EXPORT_SCORE_API, params={'startTime': startTime})
        jobId = d.json()['jobId']
        return jobId

    def job_status(self, jobId, timeout=7200):
        t0 = time.time()
        while time.time() - t0 < timeout:
            data = self.session.get(self.HOST + self.JOB_STATUS_API.format(jobId=jobId)).json()
            jobStatus = data.get('status')
            if jobStatus == "SUCCESS":
                print("行程数据导出成功, 导出参数为: ", data.get("param"))
                return data
            if jobStatus == "FAIL":
                print("行程数据导出失败: ", data)
                return data
            time.sleep(120) # 每120秒查询一次
        t1 = time.time()
        print("time cost: %.2fs" % (t1 - t0))


app_code = 'xxx'
online = UbiOpenApiExportClient('http://driver-behavior-api.haochezhu.club/', app_code)
jobId = client.export_trip()
print('jobId: ', jobId)
client.job_status(jobId=jobId)