Skip to content

Commit e8758ce

Browse files
authored
Merge pull request #118 from TTWShell/enhance/support-respone-msg-conf
support conf HOBBIT_RESPONSE_MESSAGE_MAPS
2 parents f15af98 + d2fecf3 commit e8758ce

File tree

7 files changed

+51
-9
lines changed

7 files changed

+51
-9
lines changed

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,3 +20,5 @@ build/*
2020

2121
tests/tst_app.sqlite
2222
models.csv
23+
24+
.coverage*

docs/changelog.rst

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,11 @@
11
Change history
22
==============
33

4+
2.0.4 (2021-07-13)
5+
******************
6+
7+
* Support set `HOBBIT_RESPONSE_MESSAGE_MAPS` to use self-defined response message.
8+
49
2.0.3 (2021-07-08)
510
******************
611

docs/index.rst

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -192,6 +192,23 @@ tests
192192
所有的测试case. 推荐使用 `pytest <https://docs.pytest.org/en/latest/>`_ 测试,项目也会自动生成基本的pytest配置。
193193

194194

195+
配置
196+
====
197+
198+
.. list-table:: Configuration
199+
:widths: 25 25 50
200+
:header-rows: 1
201+
202+
* - Key
203+
- Value
204+
- Description
205+
* - HOBBIT_USE_CODE_ORIGIN_TYPE
206+
- `True` or `False`
207+
- Return origin type of code in response. Default is `False`.
208+
* - HOBBIT_RESPONSE_MESSAGE_MAPS
209+
- `dict`, `{code: message}`
210+
- Self-defined response message. Set to `{200: "success"}` will return `{"code": 200, "message": "success"}` in response.
211+
195212
Others
196213
======
197214

hobbit_core/response.py

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77

88
RESP_MSGS = {
99
200: 'ok',
10+
1011
400: 'failed',
1112
401: '未登录',
1213
403: '未授权',
@@ -23,7 +24,7 @@ class RespType(TypedDict):
2324
detail: Any
2425

2526

26-
def gen_response(code: int, message: str = '', detail: Optional[str] = None,
27+
def gen_response(code: int, message: str = None, detail: Optional[str] = None,
2728
data=None) -> RespType:
2829
"""Func for generate response body.
2930
@@ -40,12 +41,24 @@ def gen_response(code: int, message: str = '', detail: Optional[str] = None,
4041
2021-07-08 Updated:
4142
Default type of `code` in response is force conversion to `str`, now
4243
support set `HOBBIT_USE_CODE_ORIGIN_TYPE = True` to return origin type.
44+
45+
2021-07-13 Updated:
46+
Support set `HOBBIT_RESPONSE_MESSAGE_MAPS` to use self-defined
47+
response message. `HOBBIT_RESPONSE_MESSAGE_MAPS` must be dict.
4348
"""
4449
use_origin_type = current_app.config.get(
4550
'HOBBIT_USE_CODE_ORIGIN_TYPE', False)
51+
52+
resp_msgs = current_app.config.get('HOBBIT_RESPONSE_MESSAGE_MAPS', {})
53+
assert isinstance(resp_msgs, dict), \
54+
'HOBBIT_RESPONSE_MESSAGE_MAPS must be dict type.'
55+
if not message:
56+
message = resp_msgs.get(code)
57+
if message is None:
58+
message = RESP_MSGS.get(code, 'unknown')
4659
return {
4760
'code': str(code) if use_origin_type is False else code,
48-
'message': message or RESP_MSGS.get(code, '未知错误'), # type: ignore
61+
'message': message, # type: ignore
4962
'data': data,
5063
'detail': detail,
5164
}

setup.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ def gen_data(data_root='static'):
3232

3333
setup(
3434
name='hobbit-core',
35-
version='2.0.3',
35+
version='2.0.4',
3636
python_requires='>=3.6, <4',
3737
description='Hobbit - A flask project generator.',
3838
long_description=long_description,

tests/test_err_handler.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,13 @@
1010

1111
class TestErrHandler(BaseTest):
1212

13-
def test_assertion_error(self):
13+
def test_assertion_error(self, app):
1414
resp = ErrHandler.handler(AssertionError('message'))
1515
assert resp.status_code == 422
1616
data = json.loads(resp.get_data())
1717
assert data['message'] == 'message'
1818

19-
def test_sqlalchemy_orm_exc(self):
19+
def test_sqlalchemy_orm_exc(self, app):
2020
resp = ErrHandler.handler(orm_exc.NoResultFound())
2121
assert resp.status_code == 404
2222
data = json.loads(resp.get_data())
@@ -27,13 +27,13 @@ def test_sqlalchemy_orm_exc(self):
2727
data = json.loads(resp.get_data())
2828
assert data['message'] == u'服务器内部错误'
2929

30-
def test_werkzeug_exceptions(self):
30+
def test_werkzeug_exceptions(self, app):
3131
resp = ErrHandler.handler(wkz_exc.Unauthorized())
3232
assert resp.status_code == 401
3333
data = json.loads(resp.get_data())
3434
assert data['message'] == u'未登录'
3535

36-
def test_others(self):
36+
def test_others(self, app):
3737
resp = ErrHandler.handler(Exception('msg'))
3838
assert resp.status_code == 500
3939
data = json.loads(resp.get_data())

tests/test_response.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ class TestResponse(BaseTest):
1212

1313
@pytest.mark.parametrize('input_, excepted', [
1414
((1, ), {
15-
'code': '1', 'message': '未知错误', 'detail': None, 'data': None}),
15+
'code': '1', 'message': 'unknown', 'detail': None, 'data': None}),
1616
((1, '测试', ['1'], {}), {
1717
'code': '1', 'message': '测试', 'detail': ['1'], 'data': {}}),
1818
((1, '测试', ['1'], []), {
@@ -27,7 +27,7 @@ def test_result(self):
2727
Result({})
2828

2929
response = {
30-
'code': '1', 'message': u'未知错误', 'detail': None, 'data': None}
30+
'code': '1', 'message': u'unknown', 'detail': None, 'data': None}
3131
result = Result(response)
3232
assert result.status_code == 200
3333

@@ -53,6 +53,11 @@ def test_success_result(self, app):
5353
result = SuccessResult(code=0)
5454
assert b'"code":"0"' in result.data
5555

56+
app.config['HOBBIT_RESPONSE_MESSAGE_MAPS'] = {100: 'testmsg'}
57+
result = SuccessResult(code=100)
58+
assert b'"message":"testmsg"' in result.data
59+
app.config['HOBBIT_RESPONSE_MESSAGE_MAPS'] = {}
60+
5661
def test_failed_result(self):
5762
result = FailedResult()
5863
assert result.status_code == 400

0 commit comments

Comments
 (0)