如何将JSON作为python龙卷风“ post”方法的输入

时间:2019-05-09 13:30:51

标签: python tornado

我正在尝试使用龙卷风做一个简单的获取和发布方法。龙卷风框架相当新。对于我想以json作为输入的帖子,请使用该输入输入另一个必须执行另一部分代码的函数。但是,即使使用简单的self.write(),我也无法使龙卷风过帐方法起作用。

对于我的get方法,我正在从SQL数据库读取以获取传感器的状态并将其以json格式写入。 get方法完美地工作!当我转到localhost:port#时,它会读出我的get json文件。对于我的post方法,我想只接受一个key:value的简单json,它是一个浮点数。我想获取用户在json中指定的浮点数,并将其用在我的flowMKS.set()函数中,该函数将更改传感器的设定值参数。我不确定如何将json输入到post方法中并将其读取到变量中。我在下面尝试了一些#commented代码,但没有成功。但是我回到了基础知识,只是做了一个self.write(“ Hello World”)来看看帖子是否正常工作。我也无法使self.write正常工作。当我转到localhost:port#/ flow_post时,不断收到500条错误消息。我的get方法中使用了flow_status变量。

预期结果是将json {“ setpoint”:45.5}放入post方法。使用该数字并将其插入我的flowMKS方法中以更改传感器上的参数。

您如何将json放入post方法中,并从json输入中获取数字并将其存储在变量中?

class Current(tornado.web.RequestHandler):
    def get(self): 
        global flow_status
        time = flow_status[0]
        ip = flow_status[1]
        rate = flow_status[2]
        setp = flow_status[3]
        tempc = flow_status[4]

        status = {"flow_controller":{
                "time":time,
                "ip":ip,
                "rate_sccm":rate,
                "setpoint":setp,
                "temperature_c":tempc,
                }
        }

        self.write(status)


class Update(tornado.web.RequestHandler):

#    def prepare(self):
#        if self.request.haders["Content-Type"].startswith("application/json"):
#            self.json_args = json.loads(self.request.body)
#        else:
#            self.json_args = None



    def post(self):

#        #expecting body data to contain JSON so we use json.loads to decrypt the JSON into a dict
#        data = json.loads(self.request.body)
#        
#        #Getting what the setpoint should be
#        setpoint = self.json_args["setpoint"]
#        
#        #making the input a float
#        setpoint = float(setpoint)
#    
#        #setting up connection with sensor
#        flowMKS = FlowController(flow_status[1])
#            
#        #sending setpoint to sensor
#        flowMKS.set(setpoint)

        self.write("Hello World")





if __name__ == '__main__':
#    global flow_status

    #Below is creating the Tornado based API for get and post methods
    tornado.options.parse_command_line()
    app = tornado.web.Application(
            handlers=[(r'/',Current), (r'/flow_post', Update)])
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(options.port)


    #using PeriodicCallback to get info from the SQL database every 500 ms
    PeriodicCallback(get_sql_status,500).start()
    #starting the entire Tornado IOLoop
    tornado.ioloop.IOLoop.current().start()

1 个答案:

答案 0 :(得分:0)

要使用Tornado上载文件,可以使用此功能tornado.httputil.parse_body_arguments,该功能将在file_dict中的字典数据args_dict和FormData中的其他参数中拆分上载的文件内容。

示例代码:

import tornado.httputil
import tornado.web
import tornado.escape
import json
import os
import sys
import traceback

class FileHandler(tornado.web.RequestHandler):

    def _return_response(self, request, message_to_be_returned: dict, status_code):
        """
        Returns formatted response back to client
        """
        try:
            request.set_header("Content-Type", "application/json; charset=UTF-8")
            request.set_status(status_code)

            #If dictionary is not empty then write the dictionary directly into
            if(bool(message_to_be_returned)):
                request.write(message_to_be_returned)

            request.finish()
        except Exception:
            raise

    def set_default_headers(self, *args, **kwargs):
        self.set_header('Content-Type','text/csv')
        self.set_header("Access-Control-Allow-Origin", "*")
        self.set_header("Access-Control-Allow-Headers", "x-requested-with")
        self.set_header("Access-Control-Allow-Methods", "*")

    def post(self):
        """
        This function reads an uploaded file
        """    
        try:
            arg_dict = {}
            file_dict = {}

            tornado.httputil.parse_body_arguments(self.request.headers["Content-Type"], self.request.body, arg_dict, file_dict)
            uploaded_file = file_dict['TestFile'][0]

            if not uploaded_file:
                return self._return_response(self, { 'message': 'No test file uploaded, please upload a test file' }, 400)

            # File contents here
            file_contents = str(uploaded_file['body'], "utf-8")

            self.set_status(200)
            self.finish()

        except Exception as ex:
            return self._return_response(self, { "message": 'Could not complete the request because of some error at the server!', "cause": ex.args[0], "stack_trace": traceback.format_exc(sys.exc_info()) }, 500)

您也可以使用tornado.escape.json_decode将请求主体反序列化为字典并对其进行处理。

示例代码:

import tornado.gen
import tornado.web
import tornado.escape
import json
import os
import sys
import traceback

class JSONHandler(tornado.web.RequestHandler):

    def _return_response(self, request, message_to_be_returned: dict, status_code):
        """
        Returns formatted response back to client
        """
        try:
            request.set_header("Content-Type", "application/json; charset=UTF-8")
            request.set_status(status_code)

            #If dictionary is not empty then write the dictionary directly into
            if(bool(message_to_be_returned)):
                request.write(message_to_be_returned)

            request.finish()
        except Exception:
            raise

    def set_default_headers(self, *args, **kwargs):
        self.set_header("Content-Type", "application/json")
        self.set_header("Access-Control-Allow-Origin", "*")
        self.set_header("Access-Control-Allow-Headers", "x-requested-with")
        self.set_header("Access-Control-Allow-Methods", "*")

    def post(self):
        """
        This function parses the request body and does something
        """    
        try:
            # Do something with request body
            request_payload = tornado.escape.json_decode(self.request.body)

            return self._return_response(self, request_payload, 200)

        except json.decoder.JSONDecodeError:
            return self._return_response(self, { "message": 'Cannot decode request body!' }, 400)

        except Exception as ex:
            return self._return_response(self, { "message": 'Could not complete the request because of some error at the server!', "cause": ex.args[0], "stack_trace": traceback.format_exc(sys.exc_info()) }, 500)