che168-api 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- che168_api-0.1.0/.gitignore +24 -0
- che168_api-0.1.0/CHANGELOG.md +6 -0
- che168_api-0.1.0/LICENSE +21 -0
- che168_api-0.1.0/PKG-INFO +169 -0
- che168_api-0.1.0/README.md +138 -0
- che168_api-0.1.0/pyproject.toml +70 -0
- che168_api-0.1.0/src/che168_api/__init__.py +72 -0
- che168_api-0.1.0/src/che168_api/_client.py +285 -0
- che168_api-0.1.0/src/che168_api/_version.py +1 -0
- che168_api-0.1.0/src/che168_api/py.typed +0 -0
- che168_api-0.1.0/src/che168_api/types.py +54 -0
- che168_api-0.1.0/tests/test_client.py +151 -0
- che168_api-0.1.0/tests/test_live.py +22 -0
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
# Python
|
|
2
|
+
__pycache__/
|
|
3
|
+
*.py[cod]
|
|
4
|
+
*.egg-info/
|
|
5
|
+
build/
|
|
6
|
+
dist/
|
|
7
|
+
.venv/
|
|
8
|
+
venv/
|
|
9
|
+
.pytest_cache/
|
|
10
|
+
.mypy_cache/
|
|
11
|
+
.ruff_cache/
|
|
12
|
+
|
|
13
|
+
# JavaScript
|
|
14
|
+
node_modules/
|
|
15
|
+
*.tgz
|
|
16
|
+
coverage/
|
|
17
|
+
|
|
18
|
+
# Secrets, editors, OS
|
|
19
|
+
.env
|
|
20
|
+
.env.*
|
|
21
|
+
.idea/
|
|
22
|
+
.vscode/
|
|
23
|
+
.DS_Store
|
|
24
|
+
Thumbs.db
|
che168_api-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 apiauto.space
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: che168-api
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Che168 API client for Python: Chinese used-car listings from Che168 as JSON, from the apiauto.space team
|
|
5
|
+
Project-URL: Homepage, https://apiauto.space/en/che168-api/
|
|
6
|
+
Project-URL: Documentation, https://apiauto.space/en/docs/
|
|
7
|
+
Project-URL: Repository, https://github.com/apiauto-space/che168-api
|
|
8
|
+
Project-URL: Issues, https://github.com/apiauto-space/che168-api/issues
|
|
9
|
+
Project-URL: Changelog, https://github.com/apiauto-space/che168-api/blob/main/python/CHANGELOG.md
|
|
10
|
+
Project-URL: Get a demo key, https://t.me/apiautospace_bot?start=demo
|
|
11
|
+
Author: apiauto.space
|
|
12
|
+
License-Expression: MIT
|
|
13
|
+
License-File: LICENSE
|
|
14
|
+
Keywords: api client,car listings,che168,che168 api,china used cars,chinese cars,used cars,vehicle data
|
|
15
|
+
Classifier: Development Status :: 4 - Beta
|
|
16
|
+
Classifier: Intended Audience :: Developers
|
|
17
|
+
Classifier: Operating System :: OS Independent
|
|
18
|
+
Classifier: Programming Language :: Python :: 3
|
|
19
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
23
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
24
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
25
|
+
Classifier: Topic :: Internet :: WWW/HTTP
|
|
26
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
27
|
+
Classifier: Typing :: Typed
|
|
28
|
+
Requires-Python: >=3.10
|
|
29
|
+
Requires-Dist: apiauto-space<0.2,>=0.1.1
|
|
30
|
+
Description-Content-Type: text/markdown
|
|
31
|
+
|
|
32
|
+
# che168-api — Che168 API client for Python
|
|
33
|
+
|
|
34
|
+
[](https://pypi.org/project/che168-api/)
|
|
35
|
+
[](https://pypi.org/project/che168-api/)
|
|
36
|
+
[](https://github.com/apiauto-space/che168-api/blob/main/LICENSE)
|
|
37
|
+
|
|
38
|
+
`che168-api` gives you Chinese used-car listings from Che168 as clean JSON through the [apiauto.space](https://apiauto.space/en/che168-api/)
|
|
39
|
+
REST API, without writing or maintaining a scraper. Search by make, model, year, price and mileage, page
|
|
40
|
+
through the whole catalog, fetch one listing by its number and follow a feed of new cars, cars taken off sale
|
|
41
|
+
and price changes.
|
|
42
|
+
|
|
43
|
+
It is a thin layer over the general [`apiauto-space`](https://pypi.org/project/apiauto-space/) client with
|
|
44
|
+
the market preset to `cn`, plus types for the Che168-only fields. It comes from the apiauto.space team;
|
|
45
|
+
the project is not affiliated with Che168 or Autohome.
|
|
46
|
+
|
|
47
|
+
- Sync `Client` and `AsyncClient`, retries on 429 and 5xx, one exception class per API error
|
|
48
|
+
- `car("59997075")` takes the Che168 listing number as well as the record id
|
|
49
|
+
- `Che168Raw` types for the Che168-only fields in `car["raw"]`
|
|
50
|
+
- Python 3.10+, `py.typed`, checked with `mypy --strict`
|
|
51
|
+
|
|
52
|
+
## Install
|
|
53
|
+
|
|
54
|
+
```bash
|
|
55
|
+
pip install che168-api
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
The module you import is `che168_api`.
|
|
59
|
+
|
|
60
|
+
## Get a key
|
|
61
|
+
|
|
62
|
+
Open the Telegram bot [@apiautospace_bot](https://t.me/apiautospace_bot?start=demo) and take a free demo
|
|
63
|
+
key: one day, 100 data requests, up to 20 cars per request. Paid plans are on the
|
|
64
|
+
[pricing page](https://apiauto.space/en/#pricing).
|
|
65
|
+
|
|
66
|
+
Save the key in the `APIAUTO_KEY` environment variable — the client reads it from there:
|
|
67
|
+
|
|
68
|
+
```bash
|
|
69
|
+
export APIAUTO_KEY="your-key"
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
Keep the key on your server: the API does not accept browser requests.
|
|
73
|
+
|
|
74
|
+
## Quick start
|
|
75
|
+
|
|
76
|
+
```python
|
|
77
|
+
import che168_api
|
|
78
|
+
|
|
79
|
+
with che168_api.Client() as client: # reads APIAUTO_KEY
|
|
80
|
+
page = client.cars(brand="BYD", year_min=2020, limit=20)
|
|
81
|
+
for car in page["items"]:
|
|
82
|
+
print(car["id"], car["title"], car["price"]["amount"], car["price"]["currency"])
|
|
83
|
+
|
|
84
|
+
one = client.car("59997075") # a listing number or "che168:59997075"
|
|
85
|
+
print(one["listing_url"], one["photos"][:1])
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
A record looks like this (shortened; real values from the catalog):
|
|
89
|
+
|
|
90
|
+
```json
|
|
91
|
+
{
|
|
92
|
+
"id": "che168:59997075",
|
|
93
|
+
"market": "cn",
|
|
94
|
+
"source": "che168",
|
|
95
|
+
"source_id": "59997075",
|
|
96
|
+
"title": "2023 Lincoln Navigator",
|
|
97
|
+
"brand": "Lincoln",
|
|
98
|
+
"model": "Navigator",
|
|
99
|
+
"year": 2023,
|
|
100
|
+
"mileage_km": 80000,
|
|
101
|
+
"fuel": "gasoline",
|
|
102
|
+
"transmission": "automatic",
|
|
103
|
+
"body_type": "suv",
|
|
104
|
+
"price": {
|
|
105
|
+
"amount": "136000.00",
|
|
106
|
+
"currency": "CNY"
|
|
107
|
+
},
|
|
108
|
+
"price_usd": "20298.27",
|
|
109
|
+
"location": {
|
|
110
|
+
"country": "CN",
|
|
111
|
+
"region": null,
|
|
112
|
+
"city": "Shenzhen"
|
|
113
|
+
},
|
|
114
|
+
"listing_url": "https://www.che168.com/dealer/534107/59997075.html",
|
|
115
|
+
"is_active": true,
|
|
116
|
+
"first_seen_at": "2026-09-22T16:29:11.202005Z",
|
|
117
|
+
"photos": [
|
|
118
|
+
"https://api.apiauto.space/img/che168:59997075/1.jpg?exp=...&sig=..."
|
|
119
|
+
],
|
|
120
|
+
"raw": {
|
|
121
|
+
"che168_infoid": "59997075",
|
|
122
|
+
"power_hp": 261,
|
|
123
|
+
"drive": "awd",
|
|
124
|
+
"first_registration": "2023-09-01",
|
|
125
|
+
"imported": false
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
Every record has the same keys as in the other apiauto.space markets; a value the source does not provide is
|
|
131
|
+
`None`. Prices are decimal strings in CNY, `price_usd` is converted at the ECB daily rate.
|
|
132
|
+
|
|
133
|
+
## Methods
|
|
134
|
+
|
|
135
|
+
| Method | What it does | Quota |
|
|
136
|
+
|---|---|---|
|
|
137
|
+
| `cars(**filters)` | One page of Che168 cars: `brand`, `model`, `year_min`, `year_max`, `price_min`, `price_max`, `mileage_max`, `fuel`, `body_type`, `sort`, `limit`, `cursor` | Cars returned |
|
|
138
|
+
| `iter_cars(max_items=None, **filters)` | Every matching car, page after page | Cars returned |
|
|
139
|
+
| `car(listing)` | One car by listing number or id, including cars taken off sale in the last 14 days | 1 record |
|
|
140
|
+
| `changes(since, type=None)` / `iter_changes(...)` | Feed of `added`, `disappeared`, `price_drop`, `price_up` events | Events returned |
|
|
141
|
+
| `brands()` / `models(brand)` | Makes and models with car counts | Free |
|
|
142
|
+
| `status()` | Plan access, data age and the number of active cars of the market | Free |
|
|
143
|
+
| `usage()` | Your plan, its term and the quota spent | Free |
|
|
144
|
+
|
|
145
|
+
The general client is at `client.core` for anything else. Errors are the `apiauto` exceptions, re-exported
|
|
146
|
+
here: `QuotaExceededError`, `RateLimitError`, `NotFoundError`, `AuthenticationError` and the rest.
|
|
147
|
+
|
|
148
|
+
## Che168-only fields
|
|
149
|
+
|
|
150
|
+
```python
|
|
151
|
+
from che168_api import raw
|
|
152
|
+
|
|
153
|
+
extra = raw(car) # typed as Che168Raw
|
|
154
|
+
print(extra.get("source_values"))
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
`Che168Raw` lists the keys with comments; every key is optional, so read them with `.get`.
|
|
158
|
+
|
|
159
|
+
## Links
|
|
160
|
+
|
|
161
|
+
- [Che168 API on apiauto.space](https://apiauto.space/en/che168-api/) and the [API documentation](https://apiauto.space/en/docs/)
|
|
162
|
+
- [`apiauto-space`](https://pypi.org/project/apiauto-space/): the general client for all markets
|
|
163
|
+
- Clients for the other sources: [`encar-api-client`](https://pypi.org/project/encar-api-client/), [`copart-api`](https://pypi.org/project/copart-api/), [`iaai-api`](https://pypi.org/project/iaai-api/)
|
|
164
|
+
- [Examples in curl, Python, JavaScript and PHP](https://github.com/apiauto-space/che168-api-examples)
|
|
165
|
+
- The JavaScript version of this client: [`che168-api` on npm](https://www.npmjs.com/package/che168-api)
|
|
166
|
+
|
|
167
|
+
## License
|
|
168
|
+
|
|
169
|
+
MIT. Che168 is a trademark of its owner; it is named here only to say which listings the client returns.
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
# che168-api — Che168 API client for Python
|
|
2
|
+
|
|
3
|
+
[](https://pypi.org/project/che168-api/)
|
|
4
|
+
[](https://pypi.org/project/che168-api/)
|
|
5
|
+
[](https://github.com/apiauto-space/che168-api/blob/main/LICENSE)
|
|
6
|
+
|
|
7
|
+
`che168-api` gives you Chinese used-car listings from Che168 as clean JSON through the [apiauto.space](https://apiauto.space/en/che168-api/)
|
|
8
|
+
REST API, without writing or maintaining a scraper. Search by make, model, year, price and mileage, page
|
|
9
|
+
through the whole catalog, fetch one listing by its number and follow a feed of new cars, cars taken off sale
|
|
10
|
+
and price changes.
|
|
11
|
+
|
|
12
|
+
It is a thin layer over the general [`apiauto-space`](https://pypi.org/project/apiauto-space/) client with
|
|
13
|
+
the market preset to `cn`, plus types for the Che168-only fields. It comes from the apiauto.space team;
|
|
14
|
+
the project is not affiliated with Che168 or Autohome.
|
|
15
|
+
|
|
16
|
+
- Sync `Client` and `AsyncClient`, retries on 429 and 5xx, one exception class per API error
|
|
17
|
+
- `car("59997075")` takes the Che168 listing number as well as the record id
|
|
18
|
+
- `Che168Raw` types for the Che168-only fields in `car["raw"]`
|
|
19
|
+
- Python 3.10+, `py.typed`, checked with `mypy --strict`
|
|
20
|
+
|
|
21
|
+
## Install
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
pip install che168-api
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
The module you import is `che168_api`.
|
|
28
|
+
|
|
29
|
+
## Get a key
|
|
30
|
+
|
|
31
|
+
Open the Telegram bot [@apiautospace_bot](https://t.me/apiautospace_bot?start=demo) and take a free demo
|
|
32
|
+
key: one day, 100 data requests, up to 20 cars per request. Paid plans are on the
|
|
33
|
+
[pricing page](https://apiauto.space/en/#pricing).
|
|
34
|
+
|
|
35
|
+
Save the key in the `APIAUTO_KEY` environment variable — the client reads it from there:
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
export APIAUTO_KEY="your-key"
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
Keep the key on your server: the API does not accept browser requests.
|
|
42
|
+
|
|
43
|
+
## Quick start
|
|
44
|
+
|
|
45
|
+
```python
|
|
46
|
+
import che168_api
|
|
47
|
+
|
|
48
|
+
with che168_api.Client() as client: # reads APIAUTO_KEY
|
|
49
|
+
page = client.cars(brand="BYD", year_min=2020, limit=20)
|
|
50
|
+
for car in page["items"]:
|
|
51
|
+
print(car["id"], car["title"], car["price"]["amount"], car["price"]["currency"])
|
|
52
|
+
|
|
53
|
+
one = client.car("59997075") # a listing number or "che168:59997075"
|
|
54
|
+
print(one["listing_url"], one["photos"][:1])
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
A record looks like this (shortened; real values from the catalog):
|
|
58
|
+
|
|
59
|
+
```json
|
|
60
|
+
{
|
|
61
|
+
"id": "che168:59997075",
|
|
62
|
+
"market": "cn",
|
|
63
|
+
"source": "che168",
|
|
64
|
+
"source_id": "59997075",
|
|
65
|
+
"title": "2023 Lincoln Navigator",
|
|
66
|
+
"brand": "Lincoln",
|
|
67
|
+
"model": "Navigator",
|
|
68
|
+
"year": 2023,
|
|
69
|
+
"mileage_km": 80000,
|
|
70
|
+
"fuel": "gasoline",
|
|
71
|
+
"transmission": "automatic",
|
|
72
|
+
"body_type": "suv",
|
|
73
|
+
"price": {
|
|
74
|
+
"amount": "136000.00",
|
|
75
|
+
"currency": "CNY"
|
|
76
|
+
},
|
|
77
|
+
"price_usd": "20298.27",
|
|
78
|
+
"location": {
|
|
79
|
+
"country": "CN",
|
|
80
|
+
"region": null,
|
|
81
|
+
"city": "Shenzhen"
|
|
82
|
+
},
|
|
83
|
+
"listing_url": "https://www.che168.com/dealer/534107/59997075.html",
|
|
84
|
+
"is_active": true,
|
|
85
|
+
"first_seen_at": "2026-09-22T16:29:11.202005Z",
|
|
86
|
+
"photos": [
|
|
87
|
+
"https://api.apiauto.space/img/che168:59997075/1.jpg?exp=...&sig=..."
|
|
88
|
+
],
|
|
89
|
+
"raw": {
|
|
90
|
+
"che168_infoid": "59997075",
|
|
91
|
+
"power_hp": 261,
|
|
92
|
+
"drive": "awd",
|
|
93
|
+
"first_registration": "2023-09-01",
|
|
94
|
+
"imported": false
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
Every record has the same keys as in the other apiauto.space markets; a value the source does not provide is
|
|
100
|
+
`None`. Prices are decimal strings in CNY, `price_usd` is converted at the ECB daily rate.
|
|
101
|
+
|
|
102
|
+
## Methods
|
|
103
|
+
|
|
104
|
+
| Method | What it does | Quota |
|
|
105
|
+
|---|---|---|
|
|
106
|
+
| `cars(**filters)` | One page of Che168 cars: `brand`, `model`, `year_min`, `year_max`, `price_min`, `price_max`, `mileage_max`, `fuel`, `body_type`, `sort`, `limit`, `cursor` | Cars returned |
|
|
107
|
+
| `iter_cars(max_items=None, **filters)` | Every matching car, page after page | Cars returned |
|
|
108
|
+
| `car(listing)` | One car by listing number or id, including cars taken off sale in the last 14 days | 1 record |
|
|
109
|
+
| `changes(since, type=None)` / `iter_changes(...)` | Feed of `added`, `disappeared`, `price_drop`, `price_up` events | Events returned |
|
|
110
|
+
| `brands()` / `models(brand)` | Makes and models with car counts | Free |
|
|
111
|
+
| `status()` | Plan access, data age and the number of active cars of the market | Free |
|
|
112
|
+
| `usage()` | Your plan, its term and the quota spent | Free |
|
|
113
|
+
|
|
114
|
+
The general client is at `client.core` for anything else. Errors are the `apiauto` exceptions, re-exported
|
|
115
|
+
here: `QuotaExceededError`, `RateLimitError`, `NotFoundError`, `AuthenticationError` and the rest.
|
|
116
|
+
|
|
117
|
+
## Che168-only fields
|
|
118
|
+
|
|
119
|
+
```python
|
|
120
|
+
from che168_api import raw
|
|
121
|
+
|
|
122
|
+
extra = raw(car) # typed as Che168Raw
|
|
123
|
+
print(extra.get("source_values"))
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
`Che168Raw` lists the keys with comments; every key is optional, so read them with `.get`.
|
|
127
|
+
|
|
128
|
+
## Links
|
|
129
|
+
|
|
130
|
+
- [Che168 API on apiauto.space](https://apiauto.space/en/che168-api/) and the [API documentation](https://apiauto.space/en/docs/)
|
|
131
|
+
- [`apiauto-space`](https://pypi.org/project/apiauto-space/): the general client for all markets
|
|
132
|
+
- Clients for the other sources: [`encar-api-client`](https://pypi.org/project/encar-api-client/), [`copart-api`](https://pypi.org/project/copart-api/), [`iaai-api`](https://pypi.org/project/iaai-api/)
|
|
133
|
+
- [Examples in curl, Python, JavaScript and PHP](https://github.com/apiauto-space/che168-api-examples)
|
|
134
|
+
- The JavaScript version of this client: [`che168-api` on npm](https://www.npmjs.com/package/che168-api)
|
|
135
|
+
|
|
136
|
+
## License
|
|
137
|
+
|
|
138
|
+
MIT. Che168 is a trademark of its owner; it is named here only to say which listings the client returns.
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.27"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "che168-api"
|
|
7
|
+
dynamic = ["version"]
|
|
8
|
+
description = "Che168 API client for Python: Chinese used-car listings from Che168 as JSON, from the apiauto.space team"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
license-files = ["LICENSE"]
|
|
13
|
+
authors = [{ name = "apiauto.space" }]
|
|
14
|
+
keywords = ["che168", "che168 api", "chinese cars", "china used cars", "used cars", "car listings", "vehicle data", "api client"]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Development Status :: 4 - Beta",
|
|
17
|
+
"Intended Audience :: Developers",
|
|
18
|
+
"Operating System :: OS Independent",
|
|
19
|
+
"Programming Language :: Python :: 3",
|
|
20
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
21
|
+
"Programming Language :: Python :: 3.10",
|
|
22
|
+
"Programming Language :: Python :: 3.11",
|
|
23
|
+
"Programming Language :: Python :: 3.12",
|
|
24
|
+
"Programming Language :: Python :: 3.13",
|
|
25
|
+
"Programming Language :: Python :: 3.14",
|
|
26
|
+
"Topic :: Internet :: WWW/HTTP",
|
|
27
|
+
"Topic :: Software Development :: Libraries :: Python Modules",
|
|
28
|
+
"Typing :: Typed",
|
|
29
|
+
]
|
|
30
|
+
dependencies = ["apiauto-space>=0.1.1,<0.2"]
|
|
31
|
+
|
|
32
|
+
[project.urls]
|
|
33
|
+
Homepage = "https://apiauto.space/en/che168-api/"
|
|
34
|
+
Documentation = "https://apiauto.space/en/docs/"
|
|
35
|
+
Repository = "https://github.com/apiauto-space/che168-api"
|
|
36
|
+
Issues = "https://github.com/apiauto-space/che168-api/issues"
|
|
37
|
+
Changelog = "https://github.com/apiauto-space/che168-api/blob/main/python/CHANGELOG.md"
|
|
38
|
+
"Get a demo key" = "https://t.me/apiautospace_bot?start=demo"
|
|
39
|
+
|
|
40
|
+
[dependency-groups]
|
|
41
|
+
dev = ["pytest>=8", "ruff>=0.15", "mypy>=1.15", "typing_extensions>=4.12"]
|
|
42
|
+
|
|
43
|
+
[tool.hatch.version]
|
|
44
|
+
path = "src/che168_api/_version.py"
|
|
45
|
+
|
|
46
|
+
[tool.hatch.build.targets.sdist]
|
|
47
|
+
include = ["src", "tests", "CHANGELOG.md", "README.md", "LICENSE"]
|
|
48
|
+
|
|
49
|
+
[tool.hatch.build.targets.wheel]
|
|
50
|
+
packages = ["src/che168_api"]
|
|
51
|
+
|
|
52
|
+
[tool.pytest.ini_options]
|
|
53
|
+
testpaths = ["tests"]
|
|
54
|
+
addopts = "-ra"
|
|
55
|
+
|
|
56
|
+
[tool.ruff]
|
|
57
|
+
line-length = 110
|
|
58
|
+
target-version = "py310"
|
|
59
|
+
src = ["src", "tests"]
|
|
60
|
+
|
|
61
|
+
[tool.ruff.lint]
|
|
62
|
+
select = ["E", "W", "F", "I", "UP", "B", "A", "C4", "SIM", "PT", "RUF", "S", "T20"]
|
|
63
|
+
|
|
64
|
+
[tool.ruff.lint.per-file-ignores]
|
|
65
|
+
"tests/*" = ["S101", "S105", "S106"]
|
|
66
|
+
|
|
67
|
+
[tool.mypy]
|
|
68
|
+
strict = true
|
|
69
|
+
python_version = "3.10"
|
|
70
|
+
files = ["src", "tests"]
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"""Che168 API client for Python: Chinese used-car listings from Che168 as JSON.
|
|
2
|
+
|
|
3
|
+
A thin layer over the apiauto.space client (``apiauto``) with the market preset::
|
|
4
|
+
|
|
5
|
+
import che168_api
|
|
6
|
+
|
|
7
|
+
with che168_api.Client() as client: # the key comes from APIAUTO_KEY
|
|
8
|
+
for car in client.cars(brand="BYD", year_min=2020, limit=20)["items"]:
|
|
9
|
+
print(car["id"], car["title"], car["price"]["amount"])
|
|
10
|
+
|
|
11
|
+
From the apiauto.space team. Not affiliated with Che168 or Autohome.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from apiauto import (
|
|
15
|
+
ApiautoError,
|
|
16
|
+
APIConnectionError,
|
|
17
|
+
AuthenticationError,
|
|
18
|
+
BadRequestError,
|
|
19
|
+
Car,
|
|
20
|
+
CarFilters,
|
|
21
|
+
CarsPage,
|
|
22
|
+
Change,
|
|
23
|
+
ChangesPage,
|
|
24
|
+
ChangeType,
|
|
25
|
+
Market,
|
|
26
|
+
NotFoundError,
|
|
27
|
+
PermissionDeniedError,
|
|
28
|
+
Price,
|
|
29
|
+
QuotaExceededError,
|
|
30
|
+
RateLimitError,
|
|
31
|
+
ReferenceItem,
|
|
32
|
+
ServerError,
|
|
33
|
+
ServiceUnavailableError,
|
|
34
|
+
Usage,
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
from ._client import MARKET, SHARED_MARKET, SOURCE, AsyncClient, Client, car_id
|
|
38
|
+
from ._version import __version__
|
|
39
|
+
from .types import Che168Raw, FxQuote, raw
|
|
40
|
+
|
|
41
|
+
__all__ = [
|
|
42
|
+
"MARKET",
|
|
43
|
+
"SHARED_MARKET",
|
|
44
|
+
"SOURCE",
|
|
45
|
+
"APIConnectionError",
|
|
46
|
+
"ApiautoError",
|
|
47
|
+
"AsyncClient",
|
|
48
|
+
"AuthenticationError",
|
|
49
|
+
"BadRequestError",
|
|
50
|
+
"Car",
|
|
51
|
+
"CarFilters",
|
|
52
|
+
"CarsPage",
|
|
53
|
+
"Change",
|
|
54
|
+
"ChangeType",
|
|
55
|
+
"ChangesPage",
|
|
56
|
+
"Che168Raw",
|
|
57
|
+
"Client",
|
|
58
|
+
"FxQuote",
|
|
59
|
+
"Market",
|
|
60
|
+
"NotFoundError",
|
|
61
|
+
"PermissionDeniedError",
|
|
62
|
+
"Price",
|
|
63
|
+
"QuotaExceededError",
|
|
64
|
+
"RateLimitError",
|
|
65
|
+
"ReferenceItem",
|
|
66
|
+
"ServerError",
|
|
67
|
+
"ServiceUnavailableError",
|
|
68
|
+
"Usage",
|
|
69
|
+
"__version__",
|
|
70
|
+
"car_id",
|
|
71
|
+
"raw",
|
|
72
|
+
]
|
|
@@ -0,0 +1,285 @@
|
|
|
1
|
+
"""Che168 clients: the apiauto clients with the market preset to ``cn``."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import AsyncIterator, Iterator, Sequence
|
|
6
|
+
from datetime import datetime
|
|
7
|
+
from decimal import Decimal
|
|
8
|
+
from types import TracebackType
|
|
9
|
+
from typing import TYPE_CHECKING, Any, Literal
|
|
10
|
+
|
|
11
|
+
import apiauto
|
|
12
|
+
from apiauto import (
|
|
13
|
+
Car,
|
|
14
|
+
CarsPage,
|
|
15
|
+
Change,
|
|
16
|
+
ChangesPage,
|
|
17
|
+
ChangeType,
|
|
18
|
+
Dictionaries,
|
|
19
|
+
Market,
|
|
20
|
+
ReferenceItem,
|
|
21
|
+
Usage,
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
if TYPE_CHECKING:
|
|
25
|
+
import httpx
|
|
26
|
+
from apiauto import CarFilters
|
|
27
|
+
from typing_extensions import Self, Unpack
|
|
28
|
+
|
|
29
|
+
MARKET: Literal["cn"] = "cn"
|
|
30
|
+
"""The apiauto.space market of Che168."""
|
|
31
|
+
SOURCE: Literal["che168"] = "che168"
|
|
32
|
+
"""The ``source`` of every record this package returns."""
|
|
33
|
+
SHARED_MARKET = False
|
|
34
|
+
"""``True`` when the market also holds another source and records are filtered on the client."""
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def car_id(listing: str | int) -> str:
|
|
38
|
+
"""The full record id for a Che168 listing number: ``59997075`` -> ``che168:59997075``.
|
|
39
|
+
|
|
40
|
+
An id that already has the ``che168:`` prefix is returned as is; another
|
|
41
|
+
source's prefix raises ``ValueError``.
|
|
42
|
+
"""
|
|
43
|
+
text = str(listing).strip()
|
|
44
|
+
if not text:
|
|
45
|
+
raise ValueError("listing must not be empty")
|
|
46
|
+
prefix, sep, number = text.partition(":")
|
|
47
|
+
if not sep:
|
|
48
|
+
return f"{SOURCE}:{text}"
|
|
49
|
+
if prefix != SOURCE or not number:
|
|
50
|
+
raise ValueError(f"not a Che168 id: {text!r}")
|
|
51
|
+
return text
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _ours(car: Car) -> bool:
|
|
55
|
+
return car.get("source") == SOURCE
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _our_change(change: Change) -> bool:
|
|
59
|
+
return change["car_id"].startswith(SOURCE + ":")
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _core_options(base_url: str | None) -> dict[str, Any]:
|
|
63
|
+
return {} if base_url is None else {"base_url": base_url}
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _own_market(markets: list[Market]) -> Market:
|
|
67
|
+
for market in markets:
|
|
68
|
+
if market["market"] == MARKET:
|
|
69
|
+
return market
|
|
70
|
+
raise apiauto.ApiautoError(f"the API did not list the {MARKET} market")
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class Client:
|
|
74
|
+
"""Che168 client of the apiauto.space API, synchronous.
|
|
75
|
+
|
|
76
|
+
Args:
|
|
77
|
+
api_key: Your key; defaults to the ``APIAUTO_KEY`` environment variable.
|
|
78
|
+
base_url: The API root; ``https://api.apiauto.space/v1`` when omitted.
|
|
79
|
+
timeout: Seconds to wait for a response.
|
|
80
|
+
max_retries: Retries after 429, 5xx or a network error.
|
|
81
|
+
http_client: Your own ``httpx.Client``; the client does not close it.
|
|
82
|
+
|
|
83
|
+
Use it as a context manager or call :meth:`close`::
|
|
84
|
+
|
|
85
|
+
with che168_api.Client() as client:
|
|
86
|
+
page = client.cars(brand="BYD", limit=20)
|
|
87
|
+
|
|
88
|
+
The general client is available as :attr:`core` for anything this one does not wrap.
|
|
89
|
+
"""
|
|
90
|
+
|
|
91
|
+
def __init__(
|
|
92
|
+
self,
|
|
93
|
+
api_key: str | None = None,
|
|
94
|
+
*,
|
|
95
|
+
base_url: str | None = None,
|
|
96
|
+
timeout: float = 30.0,
|
|
97
|
+
max_retries: int = 2,
|
|
98
|
+
http_client: httpx.Client | None = None,
|
|
99
|
+
) -> None:
|
|
100
|
+
self.core = apiauto.Client(
|
|
101
|
+
api_key,
|
|
102
|
+
timeout=timeout,
|
|
103
|
+
max_retries=max_retries,
|
|
104
|
+
http_client=http_client,
|
|
105
|
+
**_core_options(base_url),
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
def close(self) -> None:
|
|
109
|
+
"""Close the HTTP connections (unless the ``http_client`` was yours)."""
|
|
110
|
+
self.core.close()
|
|
111
|
+
|
|
112
|
+
def __enter__(self) -> Self:
|
|
113
|
+
return self
|
|
114
|
+
|
|
115
|
+
def __exit__(
|
|
116
|
+
self,
|
|
117
|
+
exc_type: type[BaseException] | None,
|
|
118
|
+
exc: BaseException | None,
|
|
119
|
+
tb: TracebackType | None,
|
|
120
|
+
) -> None:
|
|
121
|
+
self.close()
|
|
122
|
+
|
|
123
|
+
def cars(self, **filters: Unpack[CarFilters]) -> CarsPage:
|
|
124
|
+
"""One page of Che168 cars: ``GET /cars?market=cn``.
|
|
125
|
+
|
|
126
|
+
Takes the filters of :meth:`apiauto.Client.cars`: ``brand``, ``model``, ``year_min``,
|
|
127
|
+
``year_max``, ``price_min``, ``price_max`` (in CNY), ``mileage_max``, ``sort``,
|
|
128
|
+
``limit``, ``cursor`` and more. Every car returned counts against the quota.
|
|
129
|
+
"""
|
|
130
|
+
page = self.core.cars(MARKET, **filters)
|
|
131
|
+
return page
|
|
132
|
+
|
|
133
|
+
def iter_cars(self, *, max_items: int | None = None, **filters: Unpack[CarFilters]) -> Iterator[Car]:
|
|
134
|
+
"""Every Che168 car matching the filters, following ``next_cursor``.
|
|
135
|
+
|
|
136
|
+
Args:
|
|
137
|
+
max_items: Stop after this many cars.
|
|
138
|
+
**filters: The filters of :meth:`cars`; ``limit`` sets the page size.
|
|
139
|
+
"""
|
|
140
|
+
yield from self.core.iter_cars(MARKET, max_items=max_items, **filters)
|
|
141
|
+
|
|
142
|
+
def car(self, listing: str | int) -> Car:
|
|
143
|
+
"""One car by listing number (``59997075``) or record id (``che168:59997075``).
|
|
144
|
+
|
|
145
|
+
Cars taken off sale stay available for 14 days with ``is_active=False``.
|
|
146
|
+
"""
|
|
147
|
+
return self.core.car(car_id(listing))
|
|
148
|
+
|
|
149
|
+
def changes(
|
|
150
|
+
self,
|
|
151
|
+
since: datetime | str,
|
|
152
|
+
*,
|
|
153
|
+
type: ChangeType | Sequence[ChangeType] | None = None, # noqa: A002
|
|
154
|
+
min_pct: float | Decimal | None = None,
|
|
155
|
+
limit: int | None = None,
|
|
156
|
+
cursor: str | None = None,
|
|
157
|
+
) -> ChangesPage:
|
|
158
|
+
"""One page of the change feed: new cars, cars taken off sale and price changes since a moment."""
|
|
159
|
+
page = self.core.changes(MARKET, since, type=type, min_pct=min_pct, limit=limit, cursor=cursor)
|
|
160
|
+
return page
|
|
161
|
+
|
|
162
|
+
def iter_changes(
|
|
163
|
+
self,
|
|
164
|
+
since: datetime | str,
|
|
165
|
+
*,
|
|
166
|
+
type: ChangeType | Sequence[ChangeType] | None = None, # noqa: A002
|
|
167
|
+
min_pct: float | Decimal | None = None,
|
|
168
|
+
limit: int | None = None,
|
|
169
|
+
max_items: int | None = None,
|
|
170
|
+
) -> Iterator[Change]:
|
|
171
|
+
"""Every event of the change feed since a moment, following ``next_cursor``."""
|
|
172
|
+
yield from self.core.iter_changes(
|
|
173
|
+
MARKET, since, type=type, min_pct=min_pct, limit=limit, max_items=max_items
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
def brands(self) -> list[ReferenceItem]:
|
|
177
|
+
"""Makes of the cn market with car counts, most frequent first. Free."""
|
|
178
|
+
return self.core.brands(MARKET)
|
|
179
|
+
|
|
180
|
+
def models(self, brand: str) -> list[ReferenceItem]:
|
|
181
|
+
"""Models of a make with car counts. Free."""
|
|
182
|
+
return self.core.models(MARKET, brand)
|
|
183
|
+
|
|
184
|
+
def dictionaries(self) -> Dictionaries:
|
|
185
|
+
"""Canonical values of ``fuel``, ``transmission``, ``body_type`` and more. Free."""
|
|
186
|
+
return self.core.dictionaries()
|
|
187
|
+
|
|
188
|
+
def status(self) -> Market:
|
|
189
|
+
"""The cn market: plan access, data age and the number of active cars. Free."""
|
|
190
|
+
return _own_market(self.core.markets())
|
|
191
|
+
|
|
192
|
+
def usage(self) -> Usage:
|
|
193
|
+
"""The plan, its term and how much of the quota is spent. Free."""
|
|
194
|
+
return self.core.usage()
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
class AsyncClient:
|
|
198
|
+
"""Che168 client of the apiauto.space API for asyncio; the methods of :class:`Client`.
|
|
199
|
+
|
|
200
|
+
::
|
|
201
|
+
|
|
202
|
+
async with che168_api.AsyncClient() as client:
|
|
203
|
+
page = await client.cars(brand="BYD", limit=20)
|
|
204
|
+
"""
|
|
205
|
+
|
|
206
|
+
def __init__(
|
|
207
|
+
self,
|
|
208
|
+
api_key: str | None = None,
|
|
209
|
+
*,
|
|
210
|
+
base_url: str | None = None,
|
|
211
|
+
timeout: float = 30.0,
|
|
212
|
+
max_retries: int = 2,
|
|
213
|
+
http_client: httpx.AsyncClient | None = None,
|
|
214
|
+
) -> None:
|
|
215
|
+
self.core = apiauto.AsyncClient(
|
|
216
|
+
api_key,
|
|
217
|
+
timeout=timeout,
|
|
218
|
+
max_retries=max_retries,
|
|
219
|
+
http_client=http_client,
|
|
220
|
+
**_core_options(base_url),
|
|
221
|
+
)
|
|
222
|
+
|
|
223
|
+
async def close(self) -> None:
|
|
224
|
+
"""Close the HTTP connections (unless the ``http_client`` was yours)."""
|
|
225
|
+
await self.core.close()
|
|
226
|
+
|
|
227
|
+
async def __aenter__(self) -> Self:
|
|
228
|
+
return self
|
|
229
|
+
|
|
230
|
+
async def __aexit__(
|
|
231
|
+
self,
|
|
232
|
+
exc_type: type[BaseException] | None,
|
|
233
|
+
exc: BaseException | None,
|
|
234
|
+
tb: TracebackType | None,
|
|
235
|
+
) -> None:
|
|
236
|
+
await self.close()
|
|
237
|
+
|
|
238
|
+
async def cars(self, **filters: Unpack[CarFilters]) -> CarsPage:
|
|
239
|
+
"""One page of Che168 cars; see :meth:`Client.cars`."""
|
|
240
|
+
page = await self.core.cars(MARKET, **filters)
|
|
241
|
+
return page
|
|
242
|
+
|
|
243
|
+
async def iter_cars(
|
|
244
|
+
self, *, max_items: int | None = None, **filters: Unpack[CarFilters]
|
|
245
|
+
) -> AsyncIterator[Car]:
|
|
246
|
+
"""Every Che168 car matching the filters; see :meth:`Client.iter_cars`."""
|
|
247
|
+
async for car in self.core.iter_cars(MARKET, max_items=max_items, **filters):
|
|
248
|
+
yield car
|
|
249
|
+
|
|
250
|
+
async def car(self, listing: str | int) -> Car:
|
|
251
|
+
"""One car by listing number or record id; see :meth:`Client.car`."""
|
|
252
|
+
return await self.core.car(car_id(listing))
|
|
253
|
+
|
|
254
|
+
async def changes(
|
|
255
|
+
self,
|
|
256
|
+
since: datetime | str,
|
|
257
|
+
*,
|
|
258
|
+
type: ChangeType | Sequence[ChangeType] | None = None, # noqa: A002
|
|
259
|
+
min_pct: float | Decimal | None = None,
|
|
260
|
+
limit: int | None = None,
|
|
261
|
+
cursor: str | None = None,
|
|
262
|
+
) -> ChangesPage:
|
|
263
|
+
"""One page of the change feed; see :meth:`Client.changes`."""
|
|
264
|
+
page = await self.core.changes(MARKET, since, type=type, min_pct=min_pct, limit=limit, cursor=cursor)
|
|
265
|
+
return page
|
|
266
|
+
|
|
267
|
+
async def brands(self) -> list[ReferenceItem]:
|
|
268
|
+
"""Makes of the cn market with car counts. Free."""
|
|
269
|
+
return await self.core.brands(MARKET)
|
|
270
|
+
|
|
271
|
+
async def models(self, brand: str) -> list[ReferenceItem]:
|
|
272
|
+
"""Models of a make with car counts. Free."""
|
|
273
|
+
return await self.core.models(MARKET, brand)
|
|
274
|
+
|
|
275
|
+
async def dictionaries(self) -> Dictionaries:
|
|
276
|
+
"""Canonical values of ``fuel``, ``transmission``, ``body_type`` and more. Free."""
|
|
277
|
+
return await self.core.dictionaries()
|
|
278
|
+
|
|
279
|
+
async def status(self) -> Market:
|
|
280
|
+
"""The cn market: plan access, data age and the number of active cars. Free."""
|
|
281
|
+
return _own_market(await self.core.markets())
|
|
282
|
+
|
|
283
|
+
async def usage(self) -> Usage:
|
|
284
|
+
"""The plan, its term and how much of the quota is spent. Free."""
|
|
285
|
+
return await self.core.usage()
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.0"
|
|
File without changes
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"""Types of the Che168-only fields of a record.
|
|
2
|
+
|
|
3
|
+
Every record has the same common keys in every market (see :class:`apiauto.Car`);
|
|
4
|
+
the fields only Che168 has are in ``car["raw"]``. :func:`raw` returns them typed::
|
|
5
|
+
|
|
6
|
+
from che168_api import raw
|
|
7
|
+
|
|
8
|
+
extra = raw(car)
|
|
9
|
+
print(extra.get("source_values"))
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
from typing import TypedDict, cast
|
|
15
|
+
|
|
16
|
+
from apiauto import Car
|
|
17
|
+
|
|
18
|
+
__all__ = ["Che168Raw", "FxQuote", "raw"]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class FxQuote(TypedDict):
|
|
22
|
+
"""The ECB daily rate behind ``price_usd``."""
|
|
23
|
+
|
|
24
|
+
currency: str
|
|
25
|
+
usd_per_unit: str
|
|
26
|
+
"""Decimal string: US dollars for one unit of ``currency``."""
|
|
27
|
+
date: str
|
|
28
|
+
source: str
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class Che168Raw(TypedDict, total=False):
|
|
32
|
+
"""Che168-only fields of a record (``car["raw"]``). Keys can be missing; read them with ``.get``."""
|
|
33
|
+
|
|
34
|
+
che168_infoid: str
|
|
35
|
+
"""The listing number on Che168."""
|
|
36
|
+
dealer_id: str | None
|
|
37
|
+
image_count: int
|
|
38
|
+
drive: str | None
|
|
39
|
+
"""``fwd``, ``rwd``, ``awd`` or ``4wd``."""
|
|
40
|
+
power_hp: int | None
|
|
41
|
+
power_kw: int | None
|
|
42
|
+
seats: int | None
|
|
43
|
+
first_registration: str | None
|
|
44
|
+
"""First registration date, ``YYYY-MM-DD``."""
|
|
45
|
+
imported: bool | None
|
|
46
|
+
"""``True`` for an imported car, ``False`` for one made in China."""
|
|
47
|
+
source_values: dict[str, str | None]
|
|
48
|
+
"""Che168's own Chinese spellings of make, model, fuel and transmission."""
|
|
49
|
+
fx: FxQuote | None
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def raw(car: Car) -> Che168Raw:
|
|
53
|
+
"""The Che168-only fields of a record, typed as :class:`Che168Raw`."""
|
|
54
|
+
return cast(Che168Raw, car.get("raw") or {})
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import json
|
|
5
|
+
from collections.abc import Callable
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
import httpx
|
|
9
|
+
import pytest
|
|
10
|
+
|
|
11
|
+
import che168_api
|
|
12
|
+
|
|
13
|
+
KEY = "test-key-1234567890"
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def car(car_id: str) -> dict[str, Any]:
|
|
17
|
+
source = car_id.split(":", 1)[0]
|
|
18
|
+
return {"id": car_id, "market": "cn", "source": source, "title": "car", "price": {"amount": "1.00"}}
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def page(ids: list[str], next_cursor: str | None = None, count: int | None = None) -> dict[str, Any]:
|
|
22
|
+
return {"items": [car(i) for i in ids], "next_cursor": next_cursor, "count": count}
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class Recorder:
|
|
26
|
+
"""Replays queued JSON bodies and records the requests."""
|
|
27
|
+
|
|
28
|
+
def __init__(self, *bodies: Any) -> None:
|
|
29
|
+
self.bodies = list(bodies)
|
|
30
|
+
self.requests: list[httpx.Request] = []
|
|
31
|
+
|
|
32
|
+
def __call__(self, request: httpx.Request) -> httpx.Response:
|
|
33
|
+
self.requests.append(request)
|
|
34
|
+
return httpx.Response(200, json=self.bodies.pop(0))
|
|
35
|
+
|
|
36
|
+
def params(self, index: int = -1) -> dict[str, str]:
|
|
37
|
+
return dict(self.requests[index].url.params)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def client(recorder: Callable[[httpx.Request], httpx.Response]) -> che168_api.Client:
|
|
41
|
+
http = httpx.Client(transport=httpx.MockTransport(recorder))
|
|
42
|
+
return che168_api.Client(KEY, http_client=http, max_retries=0)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def test_constants() -> None:
|
|
46
|
+
assert che168_api.MARKET == "cn"
|
|
47
|
+
assert che168_api.SOURCE == "che168"
|
|
48
|
+
assert che168_api.SHARED_MARKET is False
|
|
49
|
+
assert che168_api.__version__ == "0.1.0"
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def test_cars_presets_the_market() -> None:
|
|
53
|
+
rec = Recorder(page(["che168:1", "che168:2"], count=2))
|
|
54
|
+
with client(rec) as api:
|
|
55
|
+
result = api.cars(brand="BYD", year_min=2020, limit=2)
|
|
56
|
+
assert [c["id"] for c in result["items"]] == ["che168:1", "che168:2"]
|
|
57
|
+
assert rec.requests[0].url.path == "/v1/cars"
|
|
58
|
+
assert rec.params() == {"market": "cn", "brand": "BYD", "year_min": "2020", "limit": "2"}
|
|
59
|
+
assert rec.requests[0].headers["x-api-key"] == KEY
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def test_unknown_filter_is_rejected() -> None:
|
|
63
|
+
with client(Recorder()) as api, pytest.raises(TypeError):
|
|
64
|
+
api.cars(market="kr") # type: ignore[call-arg]
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
@pytest.mark.parametrize(
|
|
68
|
+
("listing", "path"),
|
|
69
|
+
[
|
|
70
|
+
("59997075", "/v1/cars/che168:59997075"),
|
|
71
|
+
(59997075, "/v1/cars/che168:59997075"),
|
|
72
|
+
("che168:59997075", "/v1/cars/che168:59997075"),
|
|
73
|
+
],
|
|
74
|
+
)
|
|
75
|
+
def test_car_accepts_number_or_id(listing: str | int, path: str) -> None:
|
|
76
|
+
rec = Recorder(car("che168:59997075"))
|
|
77
|
+
with client(rec) as api:
|
|
78
|
+
assert api.car(listing)["id"] == "che168:59997075"
|
|
79
|
+
assert rec.requests[0].url.path == path
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
@pytest.mark.parametrize("bad", ["", " ", "other:123", "che168:"])
|
|
83
|
+
def test_car_id_rejects_foreign_ids(bad: str) -> None:
|
|
84
|
+
with pytest.raises(ValueError, match=r"\S"):
|
|
85
|
+
che168_api.car_id(bad)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def test_brands_models_and_status() -> None:
|
|
89
|
+
markets = {
|
|
90
|
+
"items": [
|
|
91
|
+
{"market": "kr", "source": "encar", "active_cars": 1},
|
|
92
|
+
{"market": "cn", "source": "che168", "active_cars": 2},
|
|
93
|
+
{"market": "us", "source": "copart+iaai", "active_cars": 3},
|
|
94
|
+
]
|
|
95
|
+
}
|
|
96
|
+
rec = Recorder([{"name": "BYD", "count": 5}], [{"name": "Han", "count": 2}], markets)
|
|
97
|
+
with client(rec) as api:
|
|
98
|
+
assert api.brands()[0]["name"] == "BYD"
|
|
99
|
+
assert rec.params(0) == {"market": "cn"}
|
|
100
|
+
assert api.models("BYD")[0]["count"] == 2
|
|
101
|
+
assert rec.params(1) == {"market": "cn", "brand": "BYD"}
|
|
102
|
+
assert api.status()["market"] == "cn"
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def test_raw_is_typed_view() -> None:
|
|
106
|
+
record: Any = {"id": "che168:59997075", "raw": {"source_values": {"brand": "x"}}}
|
|
107
|
+
assert che168_api.raw(record).get("source_values") == {"brand": "x"}
|
|
108
|
+
assert che168_api.raw({"id": "che168:59997075"}) == {} # type: ignore[typeddict-item]
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def test_iter_cars_passes_max_items_to_the_last_page() -> None:
|
|
112
|
+
rec = Recorder(page(["che168:1", "che168:2"], next_cursor="c2"), page(["che168:3"]))
|
|
113
|
+
with client(rec) as api:
|
|
114
|
+
ids = [c["id"] for c in api.iter_cars(max_items=3, limit=2)]
|
|
115
|
+
assert ids == ["che168:1", "che168:2", "che168:3"]
|
|
116
|
+
assert rec.params(1)["cursor"] == "c2"
|
|
117
|
+
assert rec.params(1)["limit"] == "1"
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def test_changes_presets_the_market() -> None:
|
|
121
|
+
rec = Recorder({"items": [{"id": 1, "car_id": "che168:1", "type": "added"}], "next_cursor": None})
|
|
122
|
+
with client(rec) as api:
|
|
123
|
+
result = api.changes("2026-11-01T00:00:00Z", type=["added", "price_drop"])
|
|
124
|
+
assert result["items"][0]["car_id"] == "che168:1"
|
|
125
|
+
assert rec.requests[0].url.params.get_list("type") == ["added", "price_drop"]
|
|
126
|
+
assert rec.params()["market"] == "cn"
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def test_async_client() -> None:
|
|
130
|
+
rec = Recorder(page(["che168:1"]), car("che168:59997075"), page(["che168:1"]))
|
|
131
|
+
|
|
132
|
+
async def run() -> list[str]:
|
|
133
|
+
http = httpx.AsyncClient(transport=httpx.MockTransport(rec))
|
|
134
|
+
async with che168_api.AsyncClient(KEY, http_client=http, max_retries=0) as api:
|
|
135
|
+
first = await api.cars(limit=1)
|
|
136
|
+
one = await api.car("59997075")
|
|
137
|
+
more = [c["id"] async for c in api.iter_cars(max_items=1, limit=1)]
|
|
138
|
+
await http.aclose()
|
|
139
|
+
return [first["items"][0]["id"], one["id"], *more]
|
|
140
|
+
|
|
141
|
+
assert asyncio.run(run()) == ["che168:1", "che168:59997075", "che168:1"]
|
|
142
|
+
assert all(r.url.params.get("market") in (None, "cn") for r in rec.requests)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def test_errors_are_the_apiauto_ones() -> None:
|
|
146
|
+
def handler(request: httpx.Request) -> httpx.Response:
|
|
147
|
+
body = {"error": {"code": "not_found", "message": "no such car"}}
|
|
148
|
+
return httpx.Response(404, content=json.dumps(body), headers={"content-type": "application/json"})
|
|
149
|
+
|
|
150
|
+
with client(handler) as api, pytest.raises(che168_api.NotFoundError):
|
|
151
|
+
api.car("1")
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""Smoke test against the live API; runs only when APIAUTO_KEY is set and spends a few records."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
|
|
7
|
+
import pytest
|
|
8
|
+
|
|
9
|
+
import che168_api
|
|
10
|
+
|
|
11
|
+
pytestmark = pytest.mark.skipif(not os.environ.get("APIAUTO_KEY"), reason="set APIAUTO_KEY to run")
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def test_live_cars_and_car() -> None:
|
|
15
|
+
with che168_api.Client() as api:
|
|
16
|
+
assert api.status()["market"] == "cn"
|
|
17
|
+
cars = list(api.iter_cars(max_items=3, limit=3))
|
|
18
|
+
assert cars, "the catalog returned no Che168 cars"
|
|
19
|
+
assert all(car["source"] == "che168" for car in cars)
|
|
20
|
+
one = api.car(cars[0]["source_id"])
|
|
21
|
+
assert one["id"] == cars[0]["id"]
|
|
22
|
+
assert isinstance(che168_api.raw(one), dict)
|