扭曲的网络-响应客户端后保留请求数据 [英] Twisted web - Keep request data after responding to client

查看:99
本文介绍了扭曲的网络-响应客户端后保留请求数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用Twisted Web编写的前端Web服务器,它与另一个Web服务器连接.客户端将文件上传到我的前端服务器,然后我的前端服务器将文件发送到后端服务器.我想接收上传的文件,然后在将文件发送到后端服务器之前,先向客户端发送立即响应.这样,客户端不必等待两次上传都可以得到响应.

I have a front-end web server written in Twisted Web, that interfaces with another web server. Clients upload files to my front-end server, which then sends the files along to the back-end server. I'd like to receive the uploaded file, and then send an immediate response to the client before sending the file on to the back-end server. That way the client doesn't have to wait for both uploads to occur before getting a response.

我正在尝试通过在单独的线程中开始将文件上传到后端服务器来做到这一点.问题是,在向客户端发送响应后,我不再能够从Request对象访问上载的文件.这是一个示例:

I'm trying to do this by starting the upload to the back-end server in a separate thread. The problem is, after sending a response to the client, I'm no longer able to access the uploaded file from the Request object. Here's an example:

class PubDir(Resource):

    def render_POST(self, request):
        if request.args["t"][0] == 'upload':
            thread.start_new_thread(self.upload, (request,))

        ### Send response to client while the file gets uploaded to the back-end server:
        return redirectTo('http://example.com/uploadpage')

    def upload(self, request):
        postheaders = request.getAllHeaders()
        try:
            postfile = cgi.FieldStorage(
                fp = request.content,
                headers = postheaders,
                environ = {'REQUEST_METHOD':'POST',
                         'CONTENT_TYPE': postheaders['content-type'],
                        }
                )
        except Exception as e:
            print 'something went wrong: ' + str(e)

        filename = postfile["file"].filename

        file = request.args["file"][0]

        #code to upload file to back-end server goes here...

尝试此操作时,出现错误:I/O operation on closed file.

When I try this, I get an error: I/O operation on closed file.

推荐答案

在完成请求对象之前,您需要将文件实际复制到内存中的缓冲区中或磁盘上的tempfile中(重定向时会发生这种情况)

You need to actually copy the file into a buffer in memory or into a tempfile on disk before you finish the request object (which is what happens when you redirect).

因此,您正在启动线程并向其发送请求对象,这可能是在打开与后端服务器的连接并在您重定向时开始复制,从而完成了请求并关闭了所有关联的临时文件,并且您遇到了麻烦.

So you are starting your thread and handing it the request object, it's maybe opening a connection to your backend server and beginning to copy when you redirect which finishes the request and closes any associated tempfiles and you're in trouble.

与其将整个请求传递给您的线程,不如进行快速测试,而是尝试将请求的内容传递给您的线程:

Instead of passing the whole request to your thread a quick test would be trying to just pass the content of the request to your thread:

thread.start_new_thread(self.upload, (request.content.read(),))

这篇关于扭曲的网络-响应客户端后保留请求数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆