python分配buffer_Node.js中的buffer如何和python中的buffer相对应
我的整個需求可以分解為下面幾步:
step1.Node.js發送Buffer類型數據:
因為Node.js中fs文件系統讀取文件后的回掉中均返回的為Buffer類型的數據,
直接通過queryString會使其數據丟失,故先采用JSON.stringify(chunk)對其進行
格式化,然后再通過queryString將其通過post發送請求出去。
代碼如下:
var fs = require('fs');
var http = require("http");
var queryString = require("querystring")
// var filepath = "登陸注冊.png";
var filepath = "mmp.txt";
var readSteam = fs.createReadStream(filepath);
readSteam.on("data",(chunk) => {
let chunkjson = JSON.stringify(chunk);
console.log(chunkjson);
let mydata = {"name":filepath, data: chunkjson};
doapost(mydata);
})
function doapost(data) {
let contents = queryString.stringify(data);
console.log("here");
console.log(contents);
let options = {
host: "localhost",
path: "/mytestpost/",
port: 8000,
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': contents.length
}
};
let req = http.request(options, function (res) {
res.on("data", function (chunk) {
});
res.on("end", function (d) {
console.log("end")
});
res.on("error", function (e) {
console.log(e);
})
});
req.write(contents);
req.end();
}
step2.Django中通過bson.binary.Binary將其數據二進制化存入mongodb中:
代碼如下
def mytestpost(request):
filename = request.POST['name']
data = request.POST['data']
# return HttpResponse(data)
client = pymongo.MongoClient('localhost', 27017)
db = client.cloudfiledb
coll = db.image
coll.save(dict(
content=bson.binary.Binary(bytes(data)),
filename='115.txt'
))
return HttpResponse(json.loads(data)["data"])
step3獲取文件,請求該接口直接將該接口的返回chunk數據寫入文件:
代碼如下:
def getFile(request):
client = pymongo.MongoClient('localhost', 27017)
db = client.cloudfiledb
coll = db.image
data = coll.find_one({'filename':'115.txt'})
return HttpResponse(data['content'])
現在的問題是直接按上面的方式操作,寫出來的文件內容為:
(因圖片上傳不了,我直接把圖片內容貼出來)
{"type":"Buffer","data":[97,98,99,100,228,189,160,229,165,189]}
可以看出此數據即為上傳時讀取文件的chunk通過JSON.stringtify后的數據,也即就是bson.binary.Binary(bytes(data))中的data數據,而python中的bytes的構造函數也可接受python中的buffer類型
//~~~~
以下是 bytes 的語法:
class bytes([source[, encoding[, errors]]])
參數
如果 source 為整數,則返回一個長度為 source 的初始化數組;
如果 source 為字符串,則按照指定的 encoding 將字符串轉換為字節序列;
如果 source 為可迭代類型,則元素必須為[0 ,255] 中的整數;
如果 source 為與 buffer 接口一致的對象,則此對象也可以被用于初始化 bytearray。
如果沒有輸入任何參數,默認就是初始化數組為0個元素。
//~~
所以現在的問題就轉化為如何在python中將Node.js中buffer通過JSON.stringtify的到的數據轉化為python中的buffer類型的數據希望各位碼友不吝賜教
總結
以上是生活随笔為你收集整理的python分配buffer_Node.js中的buffer如何和python中的buffer相对应的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python双循环zip_Python如
- 下一篇: python网页运行环境_Python小