| Conditions | 3 |
| Total Lines | 53 |
| Code Lines | 47 |
| Lines | 0 |
| Ratio | 0 % |
| Changes | 0 | ||
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
| 1 | import functools |
||
| 78 | def paginate(max_per_page=10): |
||
| 79 | def decorator(f): |
||
| 80 | @functools.wraps(f) |
||
| 81 | def wrapped(*args, **kwargs): |
||
| 82 | page = request.args.get('page', 1, type=int) |
||
| 83 | per_page = min( |
||
| 84 | request.args.get('per_page', max_per_page, type=int), max_per_page) |
||
| 85 | query = f(*args, **kwargs) |
||
| 86 | p = query.paginate(page, per_page) |
||
| 87 | pages = { |
||
| 88 | 'page': page, |
||
| 89 | 'per_page': per_page, |
||
| 90 | 'total': p.total, |
||
| 91 | 'pages': p.pages |
||
| 92 | } |
||
| 93 | if p.has_prev: |
||
| 94 | pages['prev'] = url_for( |
||
| 95 | request.endpoint, |
||
| 96 | page=p.prev_num, |
||
| 97 | per_page=per_page, |
||
| 98 | _external=True, |
||
| 99 | **kwargs) |
||
| 100 | else: |
||
| 101 | pages['prev'] = None |
||
| 102 | if p.has_next: |
||
| 103 | pages['next'] = url_for( |
||
| 104 | request.endpoint, |
||
| 105 | page=p.next_num, |
||
| 106 | per_page=per_page, |
||
| 107 | _external=True, |
||
| 108 | **kwargs) |
||
| 109 | else: |
||
| 110 | pages['next'] = None |
||
| 111 | pages['first'] = url_for( |
||
| 112 | request.endpoint, |
||
| 113 | page=1, |
||
| 114 | per_page=per_page, |
||
| 115 | _external=True, |
||
| 116 | **kwargs) |
||
| 117 | pages['last'] = url_for( |
||
| 118 | request.endpoint, |
||
| 119 | page=p.pages, |
||
| 120 | per_page=per_page, |
||
| 121 | _external=True, |
||
| 122 | **kwargs) |
||
| 123 | return jsonify({ |
||
| 124 | 'urls': [item.get_url() for item in p.items], |
||
| 125 | 'meta': pages |
||
| 126 | }) |
||
| 127 | |||
| 128 | return wrapped |
||
| 129 | |||
| 130 | return decorator |
||
| 131 | |||
| 174 |