Пытаюсь обновить DjangoREST API, используя вызовы из Golang Job runner. По какой-то причине я продолжаю получать значение None в request.POST в django
Ниже приведена функция, которую я запускаю для обновления Django REST API. Карта построена правильно, что проверяется функцией println, но сервер Django показывает полученное значение как None. Аналогичный API успешно вызывается с помощью модуля Python requests. В чем здесь может быть ошибка?
func upd_prices() {
for i:=0; i<501; i++ {
co_id:=strconv.Itoa(i)
// co_obj:=Company{co_id}
co_obj:=map[string]string{"id":co_id}
jsonStr,err:=json.Marshal(co_obj)
if err!=nil {
log.Println(err)
}
// var jsonStr = []byte(`{"co_id":`+co_id+`}`)
// responseBody:=bytes.NewBuffer(postBody)
fmt.Println(string(jsonStr))
resp,err:=http.Post("http://127.0.0.1:8000/insert_prices/","application/json", bytes.NewBuffer(jsonStr))
if err!=nil {
log.Print(err)
}
defer resp.Body.Close()
_, err2 := ioutil.ReadAll(resp.Body)
if err2 != nil {
log.Fatalln(err)
}
// sb := string(body)
// log.Print(sb)
// // file,_:=os.Create("log.txt")
// file.WriteString(sb)
// defer file.Close()
time.Sleep(time.Second*5)
}
}
Обратите внимание на косую черту впереди:
1- Используйте: "http://127.0.0.1:8000/insert_prices" вместо "http://127.0.0.1:8000/insert_prices/" :
resp, err := http.Post("http://127.0.0.1:8000/insert_prices", "application/json", bytes.NewBuffer(jsonStr))
2- Или убедитесь, что путь API принимающей стороны "/insert_prices/", а не "/insert_prices", Вот рабочий пример для вас:
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"strconv"
"time"
)
func main() {
go func() {
for i := 0; i < 5; i++ {
ID := strconv.Itoa(i)
m := map[string]string{"id": ID}
jsonStr, err := json.Marshal(m)
if err != nil {
log.Println(err)
}
fmt.Println(string(jsonStr))
resp, err := http.Post("http://127.0.0.1:8000/insert_prices/", "application/json", bytes.NewBuffer(jsonStr))
if err != nil {
log.Print(err)
}
defer resp.Body.Close()
_, err2 := ioutil.ReadAll(resp.Body)
if err2 != nil {
log.Fatalln(err)
}
time.Sleep(100 * time.Millisecond)
}
}()
http.HandleFunc("/insert_prices/", handler)
err := http.ListenAndServe("127.0.0.1:8000", nil)
if err != nil {
log.Fatal(err)
}
}
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Println(r.URL) // output: /insert_prices/
if r.Method == "POST" {
m := map[string]string{}
err := json.NewDecoder(r.Body).Decode(&m)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(m) // map[id:1]
}
}
Выход:
{"id":"0"}
/insert_prices/
map[id:0]
{"id":"1"}
/insert_prices/
map[id:1]
{"id":"2"}
/insert_prices/
map[id:2]
{"id":"3"}
/insert_prices/
map[id:3]
{"id":"4"}
/insert_prices/
map[id:4]