如何以字典的形式向我的烧瓶主服务器发送POST请求

问题描述 投票:0回答:1

[好,所以我正在做一个有关使用python查找远程服务器的运行状况详细信息的项目,而我正在使用flask托管主服务器。但是idk如何将我使用python创建的运行状况报告发送到flask应用程序。运行状况报告以字典的形式出现,我需要将字典的值传递到数据库中字典的关键字列中。有人可以帮助我将运行状况报告发送到Flask应用程序吗?此运行状况报告在另一个系统上,我需要将其发送到我的主服务器。

import psutil
import time
import json
import requests

'''
This program will be loaded on to the target server.
A flask app will transmit health data to the main flask app.
''' 

SERVER_NAME="test_local_server"

def getHealth():  # function for generating health report. Returns a json object.
    print('generating health report')
    report={}
    report['sever_name']=SERVER_NAME
    report['cpupercent']=psutil.cpu_percent(interval=2.0)
    report['ctime']=psutil.cpu_times()
    report['cpu_total']=report['ctime'].user+report['ctime'].system    
    report['disk_usages']=psutil.disk_usage("/")
    report['net']=psutil.net_io_counters()
    report['bytes_sent']=report['net'].bytes_sent
    report['bytes_received']=report['net'].bytes_recv
    report['packets_sent']=report['net'].packets_sent
    report['packets_received']=report['net'].packets_recv
    report['mem']=psutil.virtual_memory()
    report['memory_Free']=report['mem'].free
    json_report=json.dumps(report)
    return(json_report)

if __name__=='__main__':
    print(f'starting health report stream for server :\t{SERVER_NAME}')
    while True:
        getHealth()

这是用于生成运行状况详细信息的代码。如何将其以字典的形式发送回我的烧瓶应用程序?

python sqlite post flask python-requests
1个回答
0
投票

客户

我将从简化该代码开始:

import psutil

STATS_URL = 'http://localhost:5000/'
SERVER_NAME="test_local_server"

def get_health(): 

    print('generating health report')

    cpu_percent = psutil.cpu_percent(interval=2.0)
    cpu_times = psutil.cpu_times()
    disk_usage = psutil.disk_usage("/")
    net_io_counters = psutil.net_io_counters()
    virtual_memory = psutil.virtual_memory()    

    # The keys in this dict should match the db cols
    report = dict (
        sever_name = SERVER_NAME
        ctime = cpu_times.__str__(),
        disk_usages = disk_usage.__str__(),
        net = net_io_counters.__str__(),
        mem = virtual_memory.__str__(),

        cpupercent = cpu_percent,
        cpu_total = cpu_times.user + cpu_times.system,
        bytes_sent = net_io_counters.bytes_sent,
        bytes_received = net_io_counters.bytes_recv,
        packets_sent = net_io_counters.packets_sent,
        packets_received = net_io_counters.packets_recv,

        memory_Free = virtual_memory.free,
        )

    return report

get_health函数将生成并返回一个report字典。注意,对于psutil函数的某些返回值,我使用了内置的__str__方法。这样可以确保将友好类型插入数据库中。

如果您想自己检查类型,可以执行以下操作:

for item in report:
    print (item, type(report[item]), report[item])

接下来使该功能循环运行,在两次请求之间需要一个期望的时间延迟:

if __name__=='__main__':

    import time
    import requests

    print(f'starting health report stream for server :\t{SERVER_NAME}')

    while True:
        report = get_health()
        r = requests.post(STATS_URL, json=report)
        print (r, r.json())
        time.sleep(1)

注意,此操作使用jsonrequest.post参数,该参数会自动设置Flask的request.get_json函数期望的正确内容类型。

服务器

这很容易收到:

from flask import Flask, request
app = Flask(__name__)

@app.route('/', methods=['POST'])
def index():
    incoming_report = request.get_json()

    add_to_db(incoming_report) # We'll build this in a sec.

    return {'message': 'success'}

您现在可以使用作为字典的incoming_report

这还会向客户端发送成功消息,因此在客户端上您会看到输出:

starting health report stream for server :  test_local_server
generating health report
<Response [200]> {'message': 'success'}
# Repeats until killed

数据库

并且我需要将字典的值传递到列中,这些列是数据库中字典的键

现在您有了字典incoming_report,如果使用的是ORM,应该很容易将其添加到数据库中。

this answer中的内容应该可以使您简单地解压缩该字典。因此,假设您的模型名为Report,您可以简单地执行以下操作:

def add_to_db(d):
    report  = Report(**d)
    db.session.add(report)
    db.session.commit()

请注意,如果您的部署需要这样做,可能会使用一些验证和身份验证。

© www.soinside.com 2019 - 2024. All rights reserved.