You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何加密数据并将其作为表单数据POST到Flask应用端点

问题原因

报错的核心原因是你将Fernet加密后得到的bytes对象转换为了纯整数组成的列表encrypted_list,直接传入requests.post的data参数。requests库处理非字典/非键值对元组列表的可迭代对象时,会默认尝试将每个元素拆分为(key, value)格式的键值对,而你传入的列表中每个元素都是单个整数,无法完成拆包操作,因此触发TypeError。

修复方案

你完全可以将加密数据封装为表单提交给Flask接口,只需给加密数据绑定一个表单字段名即可,不需要将加密结果转成列表。客户端修改后的代码如下:

import pandas as pd
import requests
from cryptography.fernet import Fernet

# 注意:读取xlsx文件需要用read_excel,read_csv只能读csv格式文件
df = pd.read_excel('event_schedule.xlsx', index_col='Time Block',parse_dates=True)
print(df)

post_this_data = df.to_json(orient="index")
print(post_this_data)

with open('secret.key','rb') as file:
    key = file.read()

fernet = Fernet(key)
encrypted = fernet.encrypt(post_this_data.encode())
print('Encrypted Success')

# 封装为表单键值对,Fernet加密结果本身是URL安全的Base64编码,可直接转字符串传输
form_data = {
    "encrypted_payload": encrypted.decode()
}
r = requests.post('http://192.168.0.105:5000/update/data', data=form_data)
print(r.text)
Flask服务端接收解密示例
from flask import Flask, request
from cryptography.fernet import Fernet
import pandas as pd

app = Flask(__name__)
# 提前加载和客户端完全一致的密钥
with open('secret.key', 'rb') as f:
    secret_key = f.read()
fernet = Fernet(secret_key)

@app.route('/update/data', methods=['POST'])
def handle_encrypted_data():
    encrypted_str = request.form.get('encrypted_payload')
    if not encrypted_str:
        return "缺少加密数据", 400
    # 解密流程
    decrypted_json = fernet.decrypt(encrypted_str.encode()).decode()
    df = pd.read_json(decrypted_json, orient="index")
    # 此处添加你的业务处理逻辑
    print(df)
    return "数据接收处理完成"

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)
注意事项
  • 客户端和服务端必须使用完全相同的密钥文件,密钥不可泄露给第三方
  • 若不需要兼容表单提交场景,你也可以直接将加密后的bytes放入request的body中传输,表单封装是兼容性最好的方式之一

内容的提问来源于stack exchange,提问作者bbartling

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 15:48:04