如何从 go to python 返回 mongodb 的文档

问题描述

我正在尝试使用 golang 扩展我的 python 代码以使用 goroutines。我想从多个 goroutine 中的 mongo 获取文档并将其发送回 python 模块。现在我的主要问题是在 go 和 python 之间转换数据类型。例如,我如何将 fetchModelInstances 结果发送到 python?

ma​​in.py

from ctypes import *
from pathlib import Path

here = Path(__file__).absolute().parent
so = cdll.LoadLibrary(str(here / "fetch.so"))
fetchObjects = so.fetchObjects
p = fetchObjects()

ma​​in.go

package main

import "C"
import (
    "context"
    "fmt"
    "go.mongodb.org/mongo-driver/bson"
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
    "time"
)

//export fetchObjects
func fetchObjects() {
    ids := []int{86,971526}
    fetchModelInstances(ids)
}

func fetchModelInstances(value []int) []bson.M {
    ctx,cancel := context.WithTimeout(context.Background(),10*time.Second)
    defer cancel()
    client,_ := mongo.Connect(ctx,options.Client().ApplyURI("mongodb://localhost:27017"))
    collection := client.Database("blog").Collection("post")
    cur,_ := collection.Find(ctx,bson.M{"_id": bson.M{"$in": value}})
    var res []bson.M
    err := cur.All(ctx,&res)
    if err != nil {
        fmt.Println(err.Error())
    }
    return res
}
func main() {}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)