python - 如何访问 POST 请求中嵌入的键值

标签 python rest go post

我正在 Golang 中制作轮盘赌 REST API:

package main

import (
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
    "github.com/gorilla/mux"
)

func handleRequests() {
    // creates a new instance of a mux router
    myRouter := mux.NewRouter().StrictSlash(true)
    
    myRouter.HandleFunc("/spin/", handler).Methods("POST")
    log.Fatal(http.ListenAndServe(":10000", myRouter))
}

func handler(w http.ResponseWriter, r *http.Request) {

    reqBody, _ := ioutil.ReadAll(r.Body)

    s := string(reqBody)
    fmt.Println(s)
}

func main() {
    fmt.Println("Rest API v2.0 - Mux Routers")
    handleRequests()
}

main.go

我正在使用 Python 脚本测试 POST 方法:

import requests

url = 'http://localhost:10000/spin/'

myobj = {'bets':[
                {
                    'amount' : 10,
                    'position' : [0,1,2]
                },
                {
                    'amount' : 20,
                    'position' : [10]
                }
            ]
}

x = requests.post(url, data = myobj)

print(x.text)

test.py

当我运行测试脚本时。服务器收到我的 POST 请求。请求正文是: 投注=金额&投注=位置&投注=金额&投注=位置

问题是 'amount''position' 键的值不存在。

我的问题是 - 如何发出/处理 POST 请求,以便能够访问嵌入键 'amount''position' 的值我在 Go 服务器上的处理程序函数,以便我可以将此信息放入结构体的实例中。

最佳答案

问题出在 python 端,如果你打印出请求的正文/ header :

print requests.Request('POST', url, data=myobj).prepare().body
print requests.Request('POST', url, data=myobj).prepare().headers


# bets=position&bets=amount&bets=position&bets=amount
# {'Content-Length': '51', 'Content-Type': 'application/x-www-form-urlencoded'}

data 使用 x-www-form-urlencoded 编码,因此需要一个键/值对的平面列表。

您可能希望 json 来表示您的数据:

print requests.Request('POST', url, json=myobj).prepare().body
print requests.Request('POST', url, json=myobj).prepare().headers

# {"bets": [{"position": [0, 1, 2], "amount": 10}, {"position": [10], "amount": 20}]}
# {'Content-Length': '83', 'Content-Type': 'application/json'}

修复:

x = requests.post(url, json = myobj) // `json` not `data`

最后,值得检查 Go 服务器端的 Content-Type header ,以确保获得所需的编码(在本例中为 application/json)。

关于python - 如何访问 POST 请求中嵌入的键值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63831980/

相关文章:

go - 如何解码嵌套的未知字段

python - 在没有 aux.xml 文件的情况下使用更新的元数据标记创建 geotiff 文件

python - 测试需要 Flask 应用程序或请求上下文的代码

python - 试图找出 Python 中的 except 语句

java - REST Web 服务 - 如何像单例一样使用服务?

postgresql - 当我尝试连接到 Postgresql 时出现 panic

python - 在 __init__ 调用中使用 self.tr 时出现 "RuntimeError: super-class __init__() of %S was never called"

javascript - 如何允许使用 REST API 进行自由文本搜索?

c - 如何从 C 应用程序使用 ArangoDB 图形 API

web-applications - 将常量文件加载到应用程序-Golang