You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

BaseHTTPRequestHandler中无法返回列表的问题求助及相关疑问

BaseHTTPRequestHandler中无法返回列表的问题求助及相关疑问

我现在碰到个棘手的问题,在BaseHTTPRequestHandler类里没办法返回列表。我的思路是把收到的带JSON数据的POST请求转发给另一个函数处理,填充新的列表或字典之后再返回给请求方。另外我还有个疑问:是不是requests.post根本就没法返回这类对象?

下面是我的代码,附带注释:

from http.server import BaseHTTPRequestHandler, HTTPServer
import os
import time
import threading
import requests
import json
import calendar

def calculate(Event_dictionary_list, cached_timestamp):
    Event_dictionary_list.clear() #- empty Event_dictionary_list
    cached_timestamp = 0

def Async_func(Event_dictionary_list, cached_timestamp):
    calculate(Event_dictionary_list, cached_timestamp)

def handler(event, Event_dictionary_list, cached_timestamp):
    if not Event_dictionary_list: #Checking if Event_dictionary_list is empty
        cached_timestamp = event['time']
        threading.Timer(60,Async_func, [Event_dictionary_list, cached_timestamp]).start()
    # make decision as to when to calculate
    if event['time'] - cached_timestamp < 60*1000: #- in milliseconds
        Event_dictionary_list.append(event)

class server(BaseHTTPRequestHandler):
    def __init__(self, *args, **kwargs):
        self.Event_dictionary_list = []
        self.cached_timestamp = 0
        super().__init__(*args, **kwargs)

    def do_POST(self):
        print("post msg received");
        self.data_string = self.rfile.read(int(self.headers['Content-Length']))
        self.event_time = calendar.timegm(time.gmtime())
        self.send_response(200) # 200 = success - thanks for message response
        self.send_header("Content-type", "application/json")
        self.end_headers()
        data = json.loads(self.data_string)
        data['time'] = self.event_time
        # we assume json will be decoded as object, eg:
        if type(data) is dict:
            handler(data, self.Event_dictionary_list, self.cached_timestamp)
        #Trying to return object, but no luck
        return self.Event_dictionary_list

def run():
    print('http server is starting...')
    port = 8000
    server_address = ('localhost', port)
    httpd = HTTPServer(server_address, server)
    print('http server is listening on port %d' % port)
    httpd.serve_forever()

if __name__ == '__main__':
    run()

我用来测试的请求代码是这样的:

requests.post(url = 'http://localhost:8000', json = {'key': 'value'})

备注:内容来源于stack exchange,提问作者Vladislav

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.21 09:49:37