树莓派与Flask项目通信【一对一】(一)

树莓派与flask项目传输数据

1防火墙设置

  1. 首先打开防火墙

image-20231226142904937

  1. 点击左侧image-20231226142946816

  2. 关闭防火墙

image-20231226143009659

2.flask端口放行

本项目所使用的端口是5000

  1. 点击防火墙左侧的高级设置

    image-20231226143238674

  2. 点击入站规则右键新建规则选择端口

    image-20231226143336363

  3. 进行选择TCP,填写端口

    image-20231226143438127

  4. 点击下一步,进行给自己的端口服务起一个名字,最后结束

    image-20231226143522616

3.Flask项目设置

if __name__ == '__main__':
    app.run(host="0.0.0.0", port=5000)

image-20231226143629333

这两个都要设置host,缺一不可

4.客户端代码

from flask import Flask, render_template, request, jsonify
import base64

app = Flask(__name__)

# 存储接收的数据
received_images = [" "]
received_texts = [" "]

@app.route('/', methods=['GET'])
def index():
    # 显示接收到的图片和文本
    return render_template('clickindex.html', images=received_images, texts=received_texts)


@app.route('/upload-image', methods=['POST'])
def upload_image():
    # 接收并存储图片
    image = request.files['image']
    image_string = base64.b64encode(image.read()).decode('utf-8')
    received_images[0]=(f'data:image/png;base64,{image_string}')

    return jsonify({'status': 'successupload_image'})

@app.route('/send-text', methods=['POST'])
def send_text():
    # 接收并存储文本
    text = request.form['text']
    received_texts[0]=(text)
    print(received_texts)
    return jsonify({'status': 'success'})

@app.route('/get-updates', methods=['GET'])
def get_updates():
    # 发送存储的图片和文本
    return jsonify({'images': received_images, 'texts': str(received_texts)})

if __name__ == '__main__':
    app.run(host="0.0.0.0", port=5000)

index.html

<!DOCTYPE html>
<html>
<head>
    <title>Image and Text Display</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <style>
        .info-box {
            width: 200px;
            height: 200px;
            background-color: #ddd;
            margin: 10px;
            display: inline-block;
            vertical-align: top;
            cursor: pointer;
        }

        .modal {
            display: none;
            position: fixed;
            z-index: 1;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgba(0, 0, 0, 0.4);
        }

        .modal-content {
            background-color: #fefefe;
            margin: 15% auto;
            padding: 20px;
            border: 1px solid #888;
            width: 80%;
        }

        .close {
            color: #aaa;
            float: right;
            font-size: 28px;
            font-weight: bold;
        }

        .close:hover,
        .close:focus {
            color: black;
            text-decoration: none;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <div id="image-box" class="info-box"></div>
    <div id="text-box" class="info-box"></div>

    <div id="myModal" class="modal">
        <div class="modal-content">
            <span class="close">&times;</span>
            <div id="modal-content"></div>
        </div>
    </div>

    <script>
        var modalIsOpen = false;

        function showModal() {
            $('#myModal').show();
            modalIsOpen = true;
            updateModalContent();
        }

        function hideModal() {
            $('#myModal').hide();
            modalIsOpen = false;
        }

        function updateContent() {
            $.ajax({
                url: '/get-updates',
                type: 'GET',
                success: function(response) {
                    var imageContent = response.images.length > 0 ? '<img src="' + response.images + '" alt="Received image">' : '';
                    var textContent = response.texts.length > 0 ? '<p>' + response.texts+ '</p>' : '';

                    if (modalIsOpen) {
                        $('#modal-content').html(imageContent + textContent);
                    }
                }
            });
        }

        function updateModalContent() {
            if (modalIsOpen) {
                updateContent();
            }
        }

        $('.info-box').click(function() {
            showModal();
        });

        $('.close').click(function() {
            hideModal();
        });

        window.onclick = function(event) {
            if (event.target === $('#myModal')[0]) {
                hideModal();
            }
        }

        // 定时更新内容,无论模态窗口是否打开
        setInterval(updateContent, 500); // 每2秒更新一次

    </script>
</body>
</html>

5. 服务段代码

import requests

def send_text(text, url):
    response = requests.post(url, data={'text': text})
    print(f'Status: {response.status_code}, Response: {response.text}')

# 模拟发送文本
i=0
while True :

    i+=1
    send_text(f'Hello {i} from Server 2!', 'http://localhost:5000/send-text')
    # time.sleep(1)

其中localhost改为要访问的flask项目的IP地址

6.效果展示

image-20231226144154641

  • 9
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值