| Conditions | 9 |
| Total Lines | 57 |
| Code Lines | 43 |
| 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 | from tabpy.tabpy_server.handlers import BaseHandler |
||
| 43 | @gen.coroutine |
||
| 44 | def _post_impl(self): |
||
| 45 | body = json.loads(self.request.body.decode("utf-8")) |
||
| 46 | self.logger.log(logging.DEBUG, f"Processing POST request '{body}'...") |
||
| 47 | if "script" not in body: |
||
| 48 | self.error_out(400, "Script is empty.") |
||
| 49 | return |
||
| 50 | |||
| 51 | # Transforming user script into a proper function. |
||
| 52 | user_code = body["script"] |
||
| 53 | arguments = None |
||
| 54 | arguments_str = "" |
||
| 55 | if "data" in body: |
||
| 56 | arguments = body["data"] |
||
| 57 | |||
| 58 | if arguments is not None: |
||
| 59 | if not isinstance(arguments, dict): |
||
| 60 | self.error_out( |
||
| 61 | 400, "Script parameters need to be provided as a dictionary." |
||
| 62 | ) |
||
| 63 | return |
||
| 64 | args_in = sorted(arguments.keys()) |
||
| 65 | n = len(arguments) |
||
| 66 | if sorted('_arg'+str(i+1) for i in range(n)) == args_in: |
||
| 67 | arguments_str = ", " + ", ".join(args_in) |
||
| 68 | else: |
||
| 69 | self.error_out( |
||
| 70 | 400, |
||
| 71 | "Variables names should follow " |
||
| 72 | "the format _arg1, _arg2, _argN", |
||
| 73 | ) |
||
| 74 | return |
||
| 75 | |||
| 76 | function_to_evaluate = f"def _user_script(tabpy{arguments_str}):\n" |
||
| 77 | for u in user_code.splitlines(): |
||
| 78 | function_to_evaluate += " " + u + "\n" |
||
| 79 | |||
| 80 | self.logger.log( |
||
| 81 | logging.INFO, f"function to evaluate={function_to_evaluate}" |
||
| 82 | ) |
||
| 83 | |||
| 84 | try: |
||
| 85 | result = yield self._call_subprocess(function_to_evaluate, arguments) |
||
| 86 | except ( |
||
| 87 | gen.TimeoutError, |
||
| 88 | requests.exceptions.ConnectTimeout, |
||
| 89 | requests.exceptions.ReadTimeout, |
||
| 90 | ): |
||
| 91 | self.logger.log(logging.ERROR, self._error_message_timeout) |
||
| 92 | self.error_out(408, self._error_message_timeout) |
||
| 93 | return |
||
| 94 | |||
| 95 | if result is not None: |
||
| 96 | self.write(simplejson.dumps(result, ignore_nan=True)) |
||
| 97 | else: |
||
| 98 | self.write("null") |
||
| 99 | self.finish() |
||
| 100 | |||
| 146 |