我正在尝试编写一个简单的http服务器来处理在数据结构中查找响应或超时的异步请求:

>请求到达

>时间

>如果回复,请将其退回

>如果超时,则返回超时消息

我是新手,我想知道做异步响应的最佳方法是什么.我看了some twisted Deferred docs和callLater,但我不清楚到底应该做些什么.现在我使用deferToThread运行阻塞方法并等待超时.我的延迟方法得到一个字符串不可调用的错误:

Unhandled error in Deferred:

Traceback (most recent call last):

File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/threading.py", line 497, in __bootstrap

self.__bootstrap_inner()

File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/threading.py", line 522, in __bootstrap_inner

self.run()

File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/threading.py", line 477, in run

self.__target(*self.__args, **self.__kwargs)

--- ---

File "/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/twisted/python/threadpool.py", line 210, in _worker

result = context.call(ctx, function, *args, **kwargs)

File "/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/twisted/python/context.py", line 59, in callWithContext

return self.currentContext().callWithContext(ctx, func, *args, **kw)

File "/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/twisted/python/context.py", line 37, in callWithContext

return func(*args,**kw)

exceptions.TypeError: 'str' object is not callable

这是我的代码:

from twisted.web import server, resource

from twisted.internet import reactor, threads

import json

import time

connectedClients = {}

responseCollector = {}

# add fake data to the collector

class FakeData(resource.Resource):

isLeaf = True

def render_GET(self, request):

request.setHeader("content-type", "application/json")

if 'rid' in request.args and 'data' in request.args:

rid = request.args['rid'][0]

data = request.args['data'][0]

responseCollector[str(rid)] = data

return json.dumps(responseCollector)

return "{}"

class RequestHandler(resource.Resource):

isLeaf = True

def render_GET(self, request):

#request.setHeader("content-type", "application/json")

if not ('rid' in request.args and and 'json' in request.args):

return '{"success":"false","response":"invalid request"}'

rid = request.args['rid'][0]

json = request.args['id'][0]

# TODO: Wait for data to show up in the responseCollector with same rid

# as our request without blocking other requests OR timeout

d = threads.deferToThread(self.blockingMethod(rid))

d.addCallback(self.ret)

d.addErrback(self.err)

def blockingMethod(self,rid):

timeout = 5.0

timeElapsed = 0.0

while timeElapsed

if rid in responseCollector:

return responseCollector[rid]

else:

timeElapsed+=0.01

time.sleep(0.01)

return "timeout"

def ret(self, hdata):

return hdata

def err(self, failure):

return failure

reactor.listenTCP(8080, server.Site(RequestHandler()))

reactor.listenTCP(9080, server.Site(FakeData()))

reactor.run()

发出请求(当前没有返回任何有用的内容):

http://localhost:8080/?rid=1234&json={%22foo%22:%22bar%22}

添加一些假数据以用于请求:

http://localhost:9080/?rid=1234&data=foo

更新了工作版本

from twisted.web import server, resource

from twisted.internet import reactor, threads

import json

import time

connectedClients = {}

responseCollector = {}

# add fake data to the collector

class FakeData(resource.Resource):

isLeaf = True

def render_GET(self, request):

request.setHeader("content-type", "application/json")

if 'rid' in request.args and 'data' in request.args:

rid = request.args['rid'][0]

data = request.args['data'][0]

responseCollector[str(rid)] = data

return json.dumps(responseCollector)

return "{}"

class RequestHandler(resource.Resource):

isLeaf = True

def render_GET(self, request):

if not ('rid' in request.args and 'data' in request.args):

return '{"success":"false","response":"invalid request"}'

rid = request.args['rid'][0]

json = request.args['data'][0]

# TODO: Wait for data to show up in the responseCollector with same rid

# as our request without blocking other requests OR timeout

d = threads.deferToThread(self.blockingMethod,rid)

d.addCallback(self.ret, request)

d.addErrback(self.err)

return server.NOT_DONE_YET

def blockingMethod(self,rid):

timeout = 5.0

timeElapsed = 0.0

while timeElapsed

if rid in responseCollector:

return responseCollector[rid]

else:

timeElapsed+=0.01

time.sleep(0.01)

return "timeout"

def ret(self, result, request):

request.write(result)

request.finish()

def err(self, failure):

return failure

reactor.listenTCP(8080, server.Site(RequestHandler()))

reactor.listenTCP(9080, server.Site(FakeData()))

reactor.run()

解决方法:

在render_GET()中,您应该返回twisted.web.server.NOT_DONE_YET.您应该将请求对象传递给ret方法:d.addCallback(self.ret,request)

然后在ret(请求)中,您应该使用request.write(hdata)编写异步数据并关闭与request.finish()的连接.

def ret(self, result, request):

request.write(result)

request.finish()

Resource rendering occurs when Twisted Web locates a leaf Resource

object to handle a web request. A Resource’s render method may do

various things to produce output which will be sent back to the

browser:

Return a string

Request a Deferred, return server.NOT_DONE_YET,

and call request.write(“stuff”) and request.finish() later, in a

callback on the Deferred.

标签:python,twisted,twisted-web

来源: https://codeday.me/bug/20190729/1573193.html

http服务器异步响应,python – 具有异步响应的Twisted http服务器,其中请求必须等待数据变为可用或超时...相关推荐

  1. python 简单web音频_Python Twisted web服务器音频fi

    我尝试用python中的twisted创建一个简单的web服务器.不过,我无法提供m4a音频文件.在 在当前程序中,当我加载http://localhost:8880/mp3.html时,它可以正常工 ...

  2. python下载文件传到服务器_windows上python上传下载文件到linux服务器指定路径【转】...

    从windows上传文件到linux,目录下的文件夹自动创建 #!/usr/bin/env python # coding: utf-8 import paramiko import datetime ...

  3. python写tcp服务器_用Python实现一个简单的多线程TCP服务器的教程

    最近看<python核心编程>,书中实现了一个简单的1对1的TCPserver,但是在实际使用中1对1的形势明显是不行的,所以研究了一下如何在server端通过启动不同的线程(进程)来实现 ...

  4. php session 异步,Ajax异步请求PHP服务器,如何做到无阻塞响应 原创 学习与分享 PHP自学...

    最近发现了一个ajax异步请求的问题,用$.post.$.get.$.ajax请求PHP服务器时,总是无法异步返回数据. 经多次测试才发现: -- 不同浏览器,请求不同域名-不阻塞:无需实验 -- 不 ...

  5. Python 中 异步协程 的 使用方法介绍

    静觅 崔庆才的个人博客:Python中异步协程的使用方法介绍:https://cuiqingcai.com/6160.html Python 异步 IO .协程.asyncio.async/await ...

  6. python爬虫-异步爬虫

    注:本文章为学习过程中对知识点的记录,供自己复习使用,也给大家做个参考,如有错误,麻烦指出,大家共同探讨,互相进步. 借鉴出处: 该文章的路线和主要内容:崔庆才(第2版)python3网络爬虫开发实战 ...

  7. python异步爬虫_Python实战异步爬虫(协程)+分布式爬虫(多进程)

    转自:https://blog.csdn.net/SL_World/article/details/86633611 在讲解之前,我们先来通过一幅图看清多进程和协程的爬虫之间的原理及其区别.(图片来源 ...

  8. 啥是Python的异步编程

    Python的异步编程是指利用异步IO(Asynchronous Input/Output)技术来实现高效的事件驱动程序,以提高程序的响应速度和并发能力.在Python中,异步编程通常通过asynci ...

  9. python 异步io_Python中的异步IO:完整的演练

    python 异步io Async IO is a concurrent programming design that has received dedicated support in Pytho ...

最新文章

  1. QPainter使用整理
  2. Addin and Automation Development In VB.NET 2003 (3)
  3. php imagick手册,PHP中使用Imagick实现各种图片效果实例
  4. hibernate之多对多关联映射
  5. qt中QHBoxLayout或QVBoxLayout布局内控件的动态生成与显示
  6. python绝对值函数fabs_Python中abs()和math.fabs()区别
  7. 觉得Win 10不如WP好?微软确认可以降级
  8. 关于软件测试的5个误传
  9. 最详细版本|UI2Code智能生成Flutter代码——版面分析篇...
  10. python元胞转list_python元胞自动机的简单实现
  11. property_自己编写一个读取Property文件的Util类
  12. vmware linux ssh密码,从 CLI 重置 Linux VM 密码和 SSH 密钥 - Azure Virtual Machines | Microsoft Docs...
  13. 数字信号处理第二章:Z变换及离散时间系统系统分析
  14. 【计算机网络】一篇文章带你分清波特率和比特率~
  15. flume(三):常见source、channel和sink总结
  16. python取值范围_python 数据库取值范围
  17. [转]抽象基类与接口,共性与个性的选择!
  18. Unity中制作动画
  19. 初中计算机卡片的制作教案,卡片的制作教案..doc
  20. python_speech_features库学习

热门文章

  1. 利用Helm简化Kubernetes应用部署(2)
  2. Async,Await和ConfigureAwait的关系
  3. Ocelot(五)- 流量限制、服务质量
  4. .NET Core/Framework 创建委托以大幅度提高反射调用的性能
  5. Abp框架准备加入.NET Foundation
  6. 为什么我的会话状态在ASP.NET Core中不工作了?
  7. ASP.NET Core 集成测试
  8. Azure 部署 Asp.NET Core Web App
  9. MySQL-01:下载安装配置及初始化命令
  10. ipados 文件 连接服务器,iPadOS更新指南,总有一个功能是你需要的