keyboard.py 文件源码

python
阅读 19 收藏 0 点赞 0 评论 0

项目:ckb-water-vapor 作者: Drummersbrother 项目源码 文件源码
def on_get(self, req, resp):
        """This method handles all get requests to our API."""

        # The requester has to be able to accept json
        if req.client_accepts_json:

            # We check if the user used a command or not
            if req.content_length in (0, None):
                # Everything went ok
                resp.status = falcon.HTTP_200

                # We return the string representation of the keyboard
                resp.body = json.dumps({"keyboard": str(self.keyboard)})

            else:
                # We check if the user want/tries to use a command
                try:
                    # Store the request body
                    req_body = req.stream.read().decode("utf-8")

                    # We try to parse the request as json
                    post_params = json.loads(req_body)

                    # We check that the arguments exist and are valid
                    if post_params["command"]:
                        # We check what command was used
                        for command in self.get_commands:
                            # We check if the current request matches the command
                            if post_params["command"] == command["command"]:
                                # We call the command method with the request object, response object, and the parsed request dictionary
                                command["method"](req, resp, post_params)

                                # No more than one command shall be executed per request
                                break
                        else:
                            # If no command was found we return bad request
                            resp.status = falcon.HTTP_400
                            resp.body = json.dumps({"message": "Invalid command"})

                    else:
                        # Invalid arguments
                        resp.status = falcon.HTTP_400
                        resp.body = json.dumps({"message": "Invalid arguments"})

                    # We're done now
                    return

                except json.JSONDecodeError:
                    resp.status = falcon.HTTP_400
                    resp.body = json.dumps({"message": "Invalid JSON"})
        else:
            # Fuck you user
            resp.status = falcon.HTTP_417
            resp.body = json.dumps({"message": "Client doesn't accept JSON"})
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号