Python-通过TCP连接读取json对象(使用正则表达式?)
我的客户端通过TCP发送json对象。每个对象具有以下形式:Python-通过TCP连接读取json对象(使用正则表达式?),python,json,tcp,Python,Json,Tcp,我的客户端通过TCP发送json对象。每个对象具有以下形式: { "message" => "{\"timestamp\":\"2016-07-21T01:20:04.392799-0400\",\"in_iface\":\"docker0\",\"event_type\":\"alert\",\"src_ip\":\"172.17.0.2\",\"dest_ip\":\"172.17.0.3\",\"proto\":\"ICMP\",\"icmp_type\":0,\"ic
{
"message" => "{\"timestamp\":\"2016-07-21T01:20:04.392799-0400\",\"in_iface\":\"docker0\",\"event_type\":\"alert\",\"src_ip\":\"172.17.0.2\",\"dest_ip\":\"172.17.0.3\",\"proto\":\"ICMP\",\"icmp_type\":0,\"icmp_code\":0,\"alert\":{\"action\":\"allowed\",\"gid\":2,\"signature_id\":2,\"rev\":0,\"signature\":\"ICMP msg\",\"category\":\"\",\"severity\":3},\"payload\":\"hFuQVwAA\",\"payload_printable\":\"kk\"}",
"@version" => "1",
"@timestamp" => "2016-07-25T04:41:11.980Z",
"path" => "/etc/logstash/jsonSample.log",
"host" => "baklava",
"doc" => {
"timestamp" => "2016-07-21T01:20:04.392799-0400",
"in_iface" => "docker0",
"event_type" => "alert",
"src_ip" => "172.17.0.2",
"dest_ip" => "172.17.0.3",
"proto" => "ICMP",
"icmp_type" => 0,
"icmp_code" => 0,
"alert" => {
"action" => "allowed",
"gid" => 2,
"signature_id" => 2,
"rev" => 0,
"signature" => "ICMP msg",
"category" => "",
"severity" => 3
},
"payload" => "hFuQVwAA",
"payload_printable" => "kk"
},
"alert.gid" => 2,
"tags" => [
[0] "tagName_2"
]
}
我想编写一个python服务器,它监听端口11111,并且能够获取这样的对象并分别解析它们
有人能帮我写一个完整的代码吗
非常感谢 您可以使用该软件包。文档中给出了一些可能对您有用的小示例。以下是tcp服务器的扩展示例:
import SocketServer
import os
import logging
import json
FORMAT = '[%(asctime)-15s] %(message)s'
logging.basicConfig(format=FORMAT, level=logging.DEBUG)
class MyServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
# By setting this we allow the server to re-bind to the address by
# setting SO_REUSEADDR, meaning you don't have to wait for
# timeouts when you kill the server and the sockets don't get
# closed down correctly.
allow_reuse_address = True
request_queue_size = 10
def __init__(self, port):
self.host = os.uname()[1]
self.port = port
SocketServer.TCPServer.__init__(self, (self.host,self.port), MyTCPHandler)
logging.info( "Server has been started on {h}:{p}".format(h=self.host,p=self.port) )
class MyTCPHandler(SocketServer.BaseRequestHandler):
"""
The RequestHandler class for our server.
It is instantiated once per connection to the server, and must
override the handle() method to implement communication to the
client.
"""
def handle(self):
# self.request is the TCP socket connected to the client
# max length is here 2048 chars
s = self.request.recv(2048).strip()
logging.info( "received: {d}".format(d=s) )
# here you may parse the received string
obj = json.loads( s )
# here just send something back to server
self.request.sendall("got it")
PORT = 11111
if __name__ == "__main__":
# Create the server, binding to localhost on port 11111
#server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)
server = MyServer( PORT )
# Activate the server; this will keep running until you
# interrupt the program with Ctrl-C
server.serve_forever()
你可以用瓶装的。请随意翻阅文档: 特别是完整的示例为您提供了实现目标所需的足够信息:()
从烧瓶导入烧瓶
从flask_restful导入请求解析、中止、Api、资源
app=烧瓶(名称)
api=api(应用程序)
待办事项={
'todo1':{'task':'BUILDAAPI'},
'todo2':{'task':'??},
‘todo3’:{‘任务’:‘利润!'},
}
如果待办事项不存在(待办事项id),则def中止待办事项:
如果todo\u id不在todo中:
中止(404,message=“Todo{}不存在”。格式(Todo_id))
parser=reqparse.RequestParser()
parser.add_参数('task'))
#待办事项
#显示单个待办事项,并允许您删除待办事项
类待办事项(资源):
def get(自身、待办事项id):
如果todo不存在,则中止(todo id)
返回待办事项[待办事项id]
def delete(自我,待办事项id):
如果todo不存在,则中止(todo id)
待办事项[待办事项id]
返回“”,204
def put(自身、待办事项id):
args=parser.parse_args()
任务={'task':args['task']}
TODOS[todo_id]=任务
返回任务,201
#托多利斯特
#显示所有待办事项的列表,并允许您发布以添加新任务
类TodoList(资源):
def get(自我):
返回待办事项
def post(自我):
args=parser.parse_args()
todo_id=int(max(TODOS.keys()).lstrip('todo'))+1
todo\u id='todo%i'%todo\u id
TODOS[todo_id]={'task':args['task']}
返回todo[todo_id],201
##
##实际上,在这里设置Api资源路由
##
api.add_资源(TodoList,“/todos”)
api.add_资源(Todo,“/todos/”)
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
app.run(debug=True)
请注意,此平台不提供包含电池的编码服务。请自己尝试,向我们展示您的代码,获取帮助,然后重试。这样,您将在继续学习的过程中不断学习。
from flask import Flask
from flask_restful import reqparse, abort, Api, Resource
app = Flask(__name__)
api = Api(app)
TODOS = {
'todo1': {'task': 'build an API'},
'todo2': {'task': '?????'},
'todo3': {'task': 'profit!'},
}
def abort_if_todo_doesnt_exist(todo_id):
if todo_id not in TODOS:
abort(404, message="Todo {} doesn't exist".format(todo_id))
parser = reqparse.RequestParser()
parser.add_argument('task')
# Todo
# shows a single todo item and lets you delete a todo item
class Todo(Resource):
def get(self, todo_id):
abort_if_todo_doesnt_exist(todo_id)
return TODOS[todo_id]
def delete(self, todo_id):
abort_if_todo_doesnt_exist(todo_id)
del TODOS[todo_id]
return '', 204
def put(self, todo_id):
args = parser.parse_args()
task = {'task': args['task']}
TODOS[todo_id] = task
return task, 201
# TodoList
# shows a list of all todos, and lets you POST to add new tasks
class TodoList(Resource):
def get(self):
return TODOS
def post(self):
args = parser.parse_args()
todo_id = int(max(TODOS.keys()).lstrip('todo')) + 1
todo_id = 'todo%i' % todo_id
TODOS[todo_id] = {'task': args['task']}
return TODOS[todo_id], 201
##
## Actually setup the Api resource routing here
##
api.add_resource(TodoList, '/todos')
api.add_resource(Todo, '/todos/<todo_id>')
if __name__ == '__main__':
app.run(debug=True)