如何接受JSON作为pythonTornado“post”方法的输入

2024-09-29 06:29:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用tornado来做一个简单的get和post方法。tornado框架相当新。对于我想接受json作为输入的post,使用该输入输入到另一个函数中,我必须执行另一部分代码。但是我不能让龙卷风后的方法工作,即使是一个简单的自写(). 在

对于get方法,我从SQL数据库中读取以获取传感器的状态,并将其写入json格式。get方法非常有效!当我去的时候本地主机:端口它读取我的get json文件。对于post方法,我希望接受一个只有一个的简单json关键:值哪个是一个浮点数。我想获取用户在json中指定的浮点数,并在我的flowMKS.set()改变传感器设定点参数的功能。我不知道如何将json输入post方法并将其读入变量。我在下面有一些注释过的代码,我尝试过了,但没有成功。但是我回到了最基本的地方自写(“Hello World”)查看帖子是否有效。我不能得到自写也可以工作。当我转到时一直收到500条错误消息本地主机:端口#/flow_post。变量flow_status在我的get方法中使用。在

预期的结果是在post方法中引入一个json{“setpoint”:45.5}。使用数字并插入到我的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()


Tags: theto方法selfwebjsongetdef
1条回答
网友
1楼 · 发布于 2024-09-29 06:29:59

要使用Tornado上载文件,可以使用此函数^{},该函数将在字典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)

您也可以使用^{}将请求正文反序列化到字典中并对其执行某些操作。在

示例代码:

^{pr2}$

相关问题 更多 >