Skip to content

Commit e449721

Browse files
committed
finished api doc
1 parent 3bccafc commit e449721

File tree

9 files changed

+221
-17
lines changed

9 files changed

+221
-17
lines changed

.gitignore

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,10 @@ __pycache__/*
88
.pytest_cache/*
99
.tox/*
1010

11+
docs/_build/*
12+
docs/_static/*
13+
docs/_templates/*
14+
1115
hobbit_core.egg-info/*
1216
dist/*
1317
build/*

docs/conf.py

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,12 @@
1111
# If extensions (or modules to document with autodoc) are in another directory,
1212
# add these directories to sys.path here. If the directory is relative to the
1313
# documentation root, use os.path.abspath to make it absolute, like shown here.
14-
#
15-
# import os
16-
# import sys
17-
# sys.path.insert(0, os.path.abspath('.'))
14+
15+
import os
16+
import sys
17+
18+
ROOT_PATH = os.path.split(os.path.abspath('.'))[0]
19+
sys.path.insert(0, os.path.join(ROOT_PATH, 'hobbit_core'))
1820

1921

2022
# -- Project information -----------------------------------------------------
@@ -48,6 +50,7 @@
4850
'sphinx.ext.ifconfig',
4951
'sphinx.ext.viewcode',
5052
'sphinx.ext.githubpages',
53+
'sphinx.ext.napoleon',
5154
]
5255

5356
# Add any paths that contain templates here, relative to this directory.
@@ -83,13 +86,16 @@
8386
# The theme to use for HTML and HTML Help pages. See the documentation for
8487
# a list of builtin themes.
8588
#
86-
html_theme = 'alabaster'
89+
# https://pypi.org/project/Flask-Sphinx-Themes/
90+
html_theme = 'flask'
8791

8892
# Theme options are theme-specific and customize the look and feel of a theme
8993
# further. For a list of options available for each theme, see the
9094
# documentation.
91-
#
92-
# html_theme_options = {}
95+
96+
html_theme_options = {
97+
'github_fork': 'TTWShell/hobbit-core',
98+
}
9399

94100
# Add any paths that contain custom static files (such as style sheets) here,
95101
# relative to this directory. They are copied after the builtin static files,
@@ -187,9 +193,11 @@
187193
# -- Options for intersphinx extension ---------------------------------------
188194

189195
# Example configuration for intersphinx: refer to the Python standard library.
190-
intersphinx_mapping = {'https://docs.python.org/': None}
196+
intersphinx_mapping = {'python': ('https://docs.python.org/3', None)}
191197

192198
# -- Options for todo extension ----------------------------------------------
193199

194200
# If true, `todo` and `todoList` produce output, else they produce nothing.
195-
todo_include_todos = True
201+
todo_include_todos = True
202+
203+
autodoc_member_order = 'bysource'

docs/index.rst

Lines changed: 49 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,15 +6,59 @@
66
Welcome to hobbit-core's documentation!
77
=======================================
88

9-
.. toctree::
10-
:maxdepth: 2
11-
:caption: Contents:
9+
hobbit_core.hobbit
10+
==================
11+
12+
hobbit - A flask project generator.
13+
14+
.. autofunction:: hobbit_core.hobbit.bootstrap.startproject
15+
16+
hobbit_core.flask_hobbit
17+
========================
18+
19+
A flask extension that take care of base utils.
20+
21+
.. automodule:: hobbit_core.flask_hobbit
22+
:members:
23+
:undoc-members:
24+
25+
flask_hobbit.db
26+
---------------
27+
28+
.. automodule:: hobbit_core.flask_hobbit.db
29+
:members:
30+
:undoc-members:
31+
:exclude-members: SurrogatePK
32+
33+
.. autoclass:: SurrogatePK
34+
:members: __repr__
35+
36+
flask_hobbit.pagination
37+
-----------------------
38+
39+
.. automodule:: hobbit_core.flask_hobbit.pagination
40+
:members:
41+
:undoc-members:
42+
43+
flask_hobbit.schemas
44+
--------------------
45+
46+
.. automodule:: hobbit_core.flask_hobbit.schemas
47+
:members:
48+
:undoc-members:
49+
:exclude-members: PagedSchema
50+
51+
.. autoclass:: PagedSchema
52+
:members:
1253

54+
flask_hobbit.response
55+
---------------------
1356

57+
.. automodule:: hobbit_core.flask_hobbit.response
58+
:members:
59+
:undoc-members:
1460

1561
Indices and tables
1662
==================
1763

18-
* :ref:`genindex`
19-
* :ref:`modindex`
2064
* :ref:`search`

hobbit_core/flask_hobbit/__init__.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@
99

1010

1111
class HobbitManager:
12+
"""Customizable utils management.
13+
"""
1214

1315
def __init__(self, app=None, **kwargs):
1416
"""
@@ -19,6 +21,9 @@ def __init__(self, app=None, **kwargs):
1921
self.init_app(app, **kwargs)
2022

2123
def init_app(self, app, **kwargs):
24+
"""
25+
app: The Flask application instance.
26+
"""
2227
if not isinstance(app, Flask):
2328
raise TypeError(
2429
'flask_hobbit.HobbitManager.init_app(): '

hobbit_core/flask_hobbit/db.py

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,16 @@
44

55

66
class SurrogatePK:
7-
"""Base model."""
7+
"""A mixin that add ``id``、``created_at`` and ``updated_at`` columns
8+
to any declarative-mapped class.
9+
10+
**id**: A surrogate integer 'primary key' column.
11+
12+
**created_at**: Auto save ``datetime.now()`` when row created.
13+
14+
**updated_at**: Auto save ``datetime.now()`` when row updated.
15+
"""
16+
817
__table_args__ = {'extend_existing': True}
918

1019
id = Column(Integer, primary_key=True)
@@ -15,15 +24,41 @@ class SurrogatePK:
1524
onupdate=func.now())
1625

1726
def __repr__(self):
27+
"""You can set label property.
28+
29+
Returns:
30+
str: ``<{classname}({pk}:{label!r})>``
31+
"""
1832
return '<{classname}({pk}:{label!r})>'.format(
1933
classname=type(self).__name__, pk=self.id, label=self.label or '')
2034

2135

2236
def reference_col(tablename, nullable=False, pk_name='id', **kwargs):
37+
"""Column that adds primary key foreign key reference.
38+
39+
Args:
40+
tablename (str): Model.__table_name__.
41+
nullable (bool): Default is False.
42+
pk_name (str): Primary column's name.
43+
44+
Others:
45+
46+
See ``sqlalchemy.Column``
47+
48+
Examples::
49+
50+
role_id = reference_col('role')
51+
role = relationship('Role', backref='users', cascade='all, delete')
52+
"""
53+
2354
return Column(
2455
ForeignKey('{0}.{1}'.format(tablename, pk_name)),
2556
nullable=nullable, **kwargs)
2657

2758

2859
class EnumExt(enum.Enum):
60+
"""
61+
TODO:
62+
* extension.
63+
"""
2964
pass

hobbit_core/flask_hobbit/pagination.py

Lines changed: 35 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,26 +6,59 @@
66

77

88
class ParamsDict(dict):
9-
def __init__(self, **kwargs):
10-
super().__init__(**kwargs)
9+
"""Just available update func.
10+
11+
Example::
12+
13+
@use_kwargs(PageParams.update({...}))
14+
def list_users(page, page_size, order_by):
15+
pass
16+
17+
"""
1118

1219
def update(self, other=None):
20+
"""Update self by other Mapping and return self.
21+
"""
1322
ret = self.copy()
1423
if other is not None:
1524
for k, v in other.items() if isinstance(other, Mapping) else other:
1625
ret[k] = v
1726
return ret
1827

1928

29+
#: Base params for list view func.
2030
PageParams = ParamsDict(
2131
page=fields.Int(missing=1, required=False),
2232
page_size=fields.Int(missing=10, required=False),
2333
order_by=DelimitedList(
2434
fields.String(missing='id'), required=False, missing=['id']),
2535
)
36+
"""Base params for list view func which contains ``page``、``page_size``、\
37+
``order_by`` params.
38+
39+
Example::
40+
41+
@use_kwargs(PageParams)
42+
def list_users(page, page_size, order_by):
43+
pass
44+
"""
2645

2746

2847
def pagination(obj, page, page_size, order_by='id', query_exp=None):
48+
"""A pagination for sqlalchemy query.
49+
50+
Args:
51+
obj (db.Model): Model class like User.
52+
page (int): Page index.
53+
page_size (int): Row's count per page.
54+
order_by (str, list): Example: 'id'、['-id', 'column_name'].
55+
query_exp (flask_sqlalchemy.BaseQuery): Query like \
56+
``User.query.filter_by(id=1)``.
57+
58+
Returns:
59+
class: Class that contains ``items``、``page``、``page_size`` and \
60+
``total`` fileds.
61+
"""
2962
if not isinstance(obj, model.DefaultMeta):
3063
raise Exception('first arg obj must be model.')
3164

hobbit_core/flask_hobbit/response.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,18 @@
1212

1313

1414
def gen_response(code, message='', detail=None):
15+
"""Func for generate response body.
16+
17+
Args:
18+
code (string, int): Extension to interact with web pages. Default is \
19+
http response ``status_code`` like 200、404.
20+
message (string): For popup windows.
21+
detail (object): For debug, detail server error msg.
22+
23+
Returns:
24+
dict: A dict contains args.
25+
26+
"""
1527
return {
1628
'code': str(code),
1729
'message': message or RESP_MSGS.get(code, '未知错误'),
@@ -20,6 +32,8 @@ def gen_response(code, message='', detail=None):
2032

2133

2234
class Result(Response):
35+
"""Base json response.
36+
"""
2337
status = 200
2438

2539
def __init__(self, response=None, status=None, headers=None,
@@ -34,6 +48,8 @@ def __init__(self, response=None, status=None, headers=None,
3448

3549

3650
class SuccessResult(Result):
51+
"""Success response. Default status is 200, you can cover it by status arg.
52+
"""
3753
status = 200
3854

3955
def __init__(self, code=None, message='', detail=None, status=None):
@@ -43,6 +59,8 @@ def __init__(self, code=None, message='', detail=None, status=None):
4359

4460

4561
class FailedResult(Result):
62+
"""Failed response. status always 400.
63+
"""
4664
status = 400
4765

4866
def __init__(self, code=None, message='', detail=None):

hobbit_core/flask_hobbit/schemas.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,30 @@
22

33

44
class PagedSchema(Schema):
5+
"""Base schema for list api pagination.
6+
7+
Example::
8+
9+
from marshmallow import fields
10+
11+
from hobbit_core.flask_hobbit.schemas import PagedSchema
12+
13+
from . import models
14+
from .exts import ma
15+
16+
17+
class UserSchema(ma.ModelSchema):
18+
19+
class Meta:
20+
model = models.User
21+
22+
23+
class PagedUserSchema(PagedSchema):
24+
items = fields.Nested('UserSchema', many=True)
25+
26+
27+
paged_user_schemas = PagedUserSchema()
28+
"""
529
total = fields.Int()
630
page = fields.Int(missing=1, default=1)
731
page_size = fields.Int(missing=10, default=10)

hobbit_core/hobbit/bootstrap.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,39 @@ def cli(ctx, force):
2626
@click.pass_context
2727
def startproject(ctx, name, dist, template, force):
2828
"""Create a new flask project, render from different template.
29+
30+
Examples::
31+
32+
hobbit --echo startproject -n demo -d /tmp/test
33+
34+
Proj tree::
35+
36+
.
37+
├── demo
38+
│   ├── __init__.py
39+
│   ├── config.py
40+
│   ├── exts.py
41+
│   ├── models
42+
│   │   ├── __init__.py
43+
│   │   └── example.py
44+
│   ├── run.py
45+
│   ├── schemas
46+
│   │   ├── __init__.py
47+
│   │   └── example.py
48+
│   ├── utils.py
49+
│   └── views
50+
│   ├── __init__.py
51+
│   └── example.py
52+
├── docs
53+
├── requirements.txt
54+
└── tests
55+
├── __init__.py
56+
├── conftest.py
57+
└── test_example.py
58+
59+
Other tips::
60+
61+
hobbit --help
2962
"""
3063
dist = os.getcwd() if dist is None else dist
3164
ctx.obj['FORCE'] = force

0 commit comments

Comments
 (0)