Python HTTP服务器发送JSON响应

时间:2023-01-21 21:18:30

What im doing

Im trying to get my hands dirty with python and im making a very simple http server so i can send commands to my arduino via serial. Im validating the commands as i sgould and everything works as it ahould be.

我试着用python弄脏我的手,我做了一个非常简单的http服务器,这样我就可以通过串行方式向我的arduino发送命令。我按自己的方式验证命令,一切都按自己的方式运行。

The concept

Im using the HTTP server in order to recieve POST requests from remote computers and smartphones and execute code with my arduino via Serial. It has few cool features like users and user permission levels.

我使用HTTP服务器接收来自远程计算机和智能手机的请求,并通过串行方式使用arduino执行代码。它没有像用户和用户权限级别这样的酷功能。

The problem

I would like to give feedback when a request arrives. Specificaly JSON feedback with the outcome of the execution like error, notes and success. Im thinking to make a dictionary in python and add whatever i want to send back the the frontend then enclode it in json and send it as a response. (Something like php's json_encode() which takes an array and outputs json)

我想在收到请求时给予反馈。具体来说,JSON是对执行结果的反馈,比如错误、注释和成功。我在考虑用python编写一个字典,并添加我想要发送回的任何内容,然后用json封装并作为响应发送。(比如php的json_encode(),它接受一个数组并输出json)

The code

import SimpleHTTPServer
import SocketServer
import logging
import cgi
import time
import sys

class ServerHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):

def do_GET(self):
    logging.warning("======= GET STARTED =======")
    logging.warning(self.headers)
    SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)

def do_POST(self):
    form = cgi.FieldStorage(
        fp=self.rfile,
        headers=self.headers,
        environ={'REQUEST_METHOD':'POST',
                 'CONTENT_TYPE':self.headers['Content-Type'],
                 })

    if self.check_auth(username, passcode):
        self.send_response(200)
        self.send_header('Content-Type', 'application/json')
        self.end_headers()
    else:
        print cur_time + "failed to login " + form.list[0].name + form.list[0].value
        self.send_response(500)
        self.send_header('Content-Type', 'application/json')
        self.end_headers()

SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)
Handler = ServerHandler
httpd = SocketServer.TCPServer(("", PORT), Handler)
httpd.serve_forever()

I've tried to minimize the code so you can see the clear HTTP part.

我试着最小化代码,这样您就可以看到HTTP部分。

As you can see im sending the headers and the response type (200 for successful login and 500 for unsuccessful login)

如您所见,我发送了标题和响应类型(成功登录200个,失败登录500个)

Objectives i need to accomplish

  • Pass inside a dictionary the stuff i want to encode

    把我要编码的东西放进字典里

    • Exemple: out = {'status': 'ok', 'executed': 'yes'}
    • 例:= {“状态”:“ok”,“执行”:'是的' }
  • Respond with json
  • 应对json https://www.dropbox.com/s/uhxezdeqmvr0804/screen%2018 - 33 - 01. png

The complet code as a gist: https://gist.github.com/FlevasGR/1170d2ea47d851bfe024

本文的代码主要是:https://gist.github.com/FlevasGR/1170d2ea47d851bfe024

I know this might not be the best you you've ever seens in your life but its my first time writing in Python :)

我知道这可能不是你一生中见过的最好的,但这是我第一次用Python写作:

1 个解决方案

#1


7  

The json module of Python's standard library offers exactly the functionality you're asking for. import json at the top of your module and json.dumps(whatever) to get the json string to send in the response.

Python标准库的json模块提供了您所要求的功能。在模块顶部导入json和json.dumps(随便什么),以便在响应中发送json字符串。

As a side note, failing authorization is most definitely not a 500 error: 500 means "server error" and the server is making absolutely no error in rejecting unauthorized users!-) Use a 403 ("forbidden") or other security-related 400-code to reject unauthorized users -- see http://en.wikipedia.org/wiki/HTTP_403 and more generally http://en.wikipedia.org/wiki/List_of_HTTP_status_codes#4xx_Client_Error for more.

作为补充说明,失败的授权绝对不是500个错误:500表示“服务器错误”,服务器在拒绝未经授权的用户时绝对不会出错!

This latter bit isn't what you're asking about, but maintaining semantic integrity of HTTP status codes is important -- it's violated often enough on the web today to give headaches to maintainers of HTTP clients, servers, proxies, caches, &c... let's make their life easier, not harder, by sticking to the standards!_)

后面这一点不是您要问的,但是维护HTTP状态码的语义完整性是很重要的——它在web上经常被违反,给HTTP客户端、服务器、代理、缓存等的维护者带来麻烦……让我们坚持标准,让他们的生活更轻松,而不是更艰难!

#1


7  

The json module of Python's standard library offers exactly the functionality you're asking for. import json at the top of your module and json.dumps(whatever) to get the json string to send in the response.

Python标准库的json模块提供了您所要求的功能。在模块顶部导入json和json.dumps(随便什么),以便在响应中发送json字符串。

As a side note, failing authorization is most definitely not a 500 error: 500 means "server error" and the server is making absolutely no error in rejecting unauthorized users!-) Use a 403 ("forbidden") or other security-related 400-code to reject unauthorized users -- see http://en.wikipedia.org/wiki/HTTP_403 and more generally http://en.wikipedia.org/wiki/List_of_HTTP_status_codes#4xx_Client_Error for more.

作为补充说明,失败的授权绝对不是500个错误:500表示“服务器错误”,服务器在拒绝未经授权的用户时绝对不会出错!

This latter bit isn't what you're asking about, but maintaining semantic integrity of HTTP status codes is important -- it's violated often enough on the web today to give headaches to maintainers of HTTP clients, servers, proxies, caches, &c... let's make their life easier, not harder, by sticking to the standards!_)

后面这一点不是您要问的,但是维护HTTP状态码的语义完整性是很重要的——它在web上经常被违反,给HTTP客户端、服务器、代理、缓存等的维护者带来麻烦……让我们坚持标准,让他们的生活更轻松,而不是更艰难!