一、前言
Tornado是一个基于非阻塞I/O的Web框架,具有可以处理大量并发连接,适用于高并发的场景的高性能,轻量级和异步支持的优点。
本篇主要展示了使用 tornado http post 和 get 服务
二、代码
tornado http post 和 get 服务
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 2 09:52:49 2022
@author: junyang.zhang
"""
import tornado.ioloop
from tornado.web import RequestHandler , Application
from tornado.httpserver import HTTPServer
from tornado.options import options,define
import json
import time
class ClassA( RequestHandler ):
def get(self):
value1 = self.get_argument('key1')
value2 = self.get_argument('key2')
print( "class A get receive" , value1 , value2 )
self.write( "class A get response" )
def post(self):
data = json.loads( self.request.body )
print( "class A post receive " , data )
result = {
"ok":0,
"message": "class A post response!",
}
self.write(json.dumps(result))
class ClassB( RequestHandler ):
def get(self):
#这个实际是从url 获取参数
query_data = {}
for key in self.request.arguments.keys():
query_data[key] = self.get_argument(key)
print( "class B get receive" , query_data )
self.write( "class B get response" )
def post(self):
#对应客户端的
#这个实际可以从 body 获取
data = tornado.escape.json_decode(self.request.body)
print( "class B post receive " , data )
result = {
"ok":0,
"message": "class B post response!",
}
self.write(json.dumps(result))
if __name__=="__main__":
options.parse_command_line()
handlers_routes = [
( r"/a" , ClassA ) , ( r"/b" , ClassB )
]
app = Application( handlers= handlers_routes )
http_server = HTTPServer(app)
address = '127.0.0.1'
#address = '10.2.3.118'
port = 20437
#port = 80
http_server.listen( port )
print("Listening: %s:%s" % (address, port))
#tornado.ioloop.IOLoop.current().start() #暂时没办法,只能是啥端口的进程
try:
tornado.ioloop.IOLoop.instance().start()
# signal : CTRL + BREAK on windows or CTRL + C on linux
except KeyboardInterrupt:
tornado.ioloop.IOLoop.instance().stop()
下面的client端向分别向2个服务发送get请求和post请求,服务将处理请求并返回
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 25 15:17:09 2022
@author: junyang.zhang
"""
#这是个 post 请求的例子
import requests
payload = {'key1': 1 , 'key2': 'value2'}
resp = requests.get('http://127.0.0.1:20437/a', params=payload , timeout=0.5)
print(resp.text )
data = {
'name': 'lucy',
'age': 12 ,
"a" : {"a" : "1" , "b" :2 } #比较复杂,则用post
}
res = requests.post('http://127.0.0.1:20437/a', json=data)
print(res.text)
payload = {'key1': 3 , 'key2': 'value4'}
resp = requests.get('http://127.0.0.1:20437/b', params=payload , timeout=0.5)
print(resp.text )
data = {
'name': 'lili',
'age': 22 ,
"a" : {"a" : "2" , "b" :3 } #比较复杂,则用post
}
res = requests.post('http://127.0.0.1:20437/b', json=data)
print(res.text)
三、结果
服务端输出:
客户端输出
文章来源:https://www.toymoban.com/news/detail-534950.html
文章来源地址https://www.toymoban.com/news/detail-534950.html
到了这里,关于python--tornado服务的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!