使用Flask向web服务器发送POST请求

-3 投票
1 回答
1358 浏览
提问于 2025-04-18 09:31

当你运行这个Python脚本时,你会看到一个网络连接的功能,它会在127.0.0.1:5000/这个地址上显示。

但是,我不知道怎么才能在脚本运行开始时打印出所有的网络特性。我是说,我丢失了之前的数据,所以在刷新页面时,我只能打印出网络的某一个特性到我的网页服务器上。

我在Flask的文档中没有找到具体的内容。有些人说urllib2或者post.request对这个有帮助,但我对Flask和Python在网页方面都很陌生。

提前谢谢大家!

代码:

import socket, sys
from struct import *
from flask import Flask

app = Flask(__name__)

@app.route('/')

def hello_world():  

s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_TCP)

while True:

        packet = s.recvfrom(65536)

        packet = packet[0]

        ip_header = packet[0:20]

        iph = unpack('!2B3H2BH4s4s' , ip_header)    

        t_length = iph[2] 
        protocol = iph[6]

        s_addr = socket.inet_ntoa(iph[8]);
        d_addr = socket.inet_ntoa(iph[9]);

        protocol_s = protocol    

        if protocol == 1:
            protocol_s = 'ICMP'
        if protocol == 6:
            protocol_s = 'TCP'
        if protocol == 17:
            protocol_s = 'UDP'

        tcp_header = packet[20:40]

        tcph = unpack('!HHLLBBHHH' , tcp_header)

        dest_port = tcph[1]     

    test = 'Protocol : ' + protocol_s + ' | Source Address : ' + str(s_addr) + ' | Destination Address : ' + str(d_addr) + ' | Dest Port : ' + str(dest_port) + ' | Packet Length : ' + str(t_length)

    return test

if __name__ == '__main__':
    app.run()

1 个回答

1

首先,Flask是一个WSGI框架。它只能在TCP/IP上运行,而HTTP是你在大多数情况下会使用的协议。你可能会使用websockets和其他协议,但它们也都是在TCP上工作的。关于socket的处理,服务器已经帮你搞定了,所以你不需要担心这个。

至于获取连接的信息,我不太确定你能得到多少。你可以看看flask.Requestwerkzeug.wrappers.Request这两个对象。

举个例子,你可以从request中获取远程地址:

from flask import request

@app.route('/')
def hello():
    print request.remote_addr

撰写回答