请求URL后推送数据

时间:2010-04-05 02:58:48

标签: python wsgi

当用户在我的服务器上请求/foo时,我发送以下HTTP响应(不关闭连接):

Content-Type: multipart/x-mixed-replace; boundary=-----------------------

-----------------------
Content-Type: text/html

<a href="/bar">foo</a>

当用户转到/bar(将发送204 No Content以便视图不会更改时),我想在初始响应中发送以下数据。

-----------------------
Content-Type: text/html

bar

如何从初始响应中获取第二个触发此请求的请求?我计划可能创建一个花哨的[引擎支持multipart / x-mixed-replace(目前只有Gecko)] - 只提供服务器推送和无需任何JavaScript的Ajax效果的webapp,只是为了好玩。

4 个答案:

答案 0 :(得分:1)

如果问题是将一些命令从/ bar应用程序传递给/ foo应用程序并且你正在使用类似servlet的方法(Python代码加载一次而不是像CGI中那样为每个请求加载),你可以改变一些/ foo应用程序的class属性,并准备好对/ foo实例中的更改作出反应(通过检查属性状态)。

显然,/ foo应用程序不应该在第一个请求之后立即返回并逐行生成内容。

认为这只是理论,我自己没有尝试过。

答案 1 :(得分:1)

没有完整答案,但是:

在您的问题中,您正在描述Comet式的架构。关于Python / WSGI中对Comet风格技术的支持,有一个StackOverflow question,它讨论了各种Python服务器,支持长期运行的请求。

同样有趣的是Python Web-SIG中的这个邮件线程:"Could WSGI handle Asynchronous response?"。 2008年5月,Web-SIG就asynchronous requests in WSGI的主题进行了广泛的讨论。

最近的一个开发是evserver,一个轻量级的WSGI服务器,它实现了Christopher Stawarz在2008年5月在Web-SIG中提出的Asynchronous WSGI extension

最后,Tornado web server支持non-blocking asynchronous requests。它有一个使用长轮询的聊天示例应用程序,它与您的要求有相似之处。

答案 2 :(得分:1)

我创建了一些小例子(只是为了好玩,你知道:))

import threading

num = 0
cond = threading.Condition()

def app(environ, start_response):
    global num

    cond.acquire()
    num += 1
    cond.notifyAll()
    cond.release()

    start_response("200 OK", [("Content-Type", "multipart/x-mixed-replace; boundary=xxx")])
    while True:
        n = num    
        s = "--xxx\r\nContent-Type: text/html\r\n\r\n%s\n" % n
        yield s
        # wait for num change:
        cond.acquire()
        while num == n:
            cond.wait()
        cond.release()


from cherrypy.wsgiserver import CherryPyWSGIServer
server = CherryPyWSGIServer(("0.0.0.0", 3000), app)

try:
    server.start()
except KeyboardInterrupt:
    server.stop()

# Now whenever you visit http://127.0.0.1:3000/, the number increases.
# It also automatically increases in all previously opened windows/tabs.

共享变量和线程同步(使用条件变量对象)的想法是基于CherryPyWSGIServer提供的WSGI服务器是线程化的。

答案 3 :(得分:-1)

不确定这是否是您正在寻找的东西,但是使用mast内容multipart / x-mixed-replace进行服务器推送有一种相当古老的方式

基本上,您将响应编写为内容类型为multipart / x-mixed-replace的mime对象,并将文档的第一个“版本”发送下来。浏览器将保持套接字打开。

然后,当服务器决定推送更多数据时,将从服务器发送文档的新“版本”,并且浏览器将智能地替换(在任何帧/ iframe中包含内容的内容)内容。

这是做网络摄像头的早期方式,服务器会在图像之后向下发送(推送)图像,浏览器会一遍又一遍地替换文档中的图像。这也是通过单个HTTP请求执行“正在加载...”消息的一种方式。