3 回答
TA贡献1810条经验 获得超4个赞
这是与该问题相关的一个工作示例,可能对将来的某人有所帮助。
服务器.go
package main
import (
"fmt"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
"github.com/jmoiron/sqlx"
"gopkg.in/guregu/null.v3"
"strconv"
)
type RawOffer struct {
Used_f bool `json:"Used_f"`
Used_t bool `json:"Used_t"`
RawOfferData string `json:"Raw"`
Modified null.Time `json:"Modified"`
Created null.Time `json:"Created"`
}
func convert(c *gin.Context) {
var rawOffer RawOffer
c.BindJSON(&rawOffer)
fmt.Println(`Used_f = ` + strconv.FormatBool(rawOffer.Used_f))
fmt.Println(`Used_t = ` + strconv.FormatBool(rawOffer.Used_t))
fmt.Println(`RawOfferData = `, rawOffer.RawOfferData)
fmt.Println(`Modified = `, rawOffer.Modified)
fmt.Println(`Created = `, rawOffer.Created)
}
var db *sqlx.DB
func main() {
fmt.Println("begin")
r := gin.Default()
r.Use(cors.Default())
r.POST("/convert/", convert)
r.Run((":8087"))
}
test.py
import requests
import json
import datetime
def default(o):
if isinstance(o, (datetime.date, datetime.datetime)):
return o.isoformat() + 'Z'
try :
data = dict(
Created = datetime.datetime.utcnow(),
Modified = datetime.datetime.utcnow(),
Used_f = False,
Used_t = True,
Raw = 'some raw data here',
)
datastr = json.dumps(data, default=default)
print(datastr)
requests.post("http://127.0.0.1:8087/convert/", datastr)
except Exception as e:
print(e)
登录test.py:
$ python test.py
{"Created": "2019-06-09T15:48:38.978230Z", "Modified": "2019-06-09T15:48:38.978689Z", "Used_f": false, "Used_t": true, "Raw": "some raw data here"}
登录服务器:
begin
[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.
[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.
- using env: export GIN_MODE=release
- using code: gin.SetMode(gin.ReleaseMode)
[GIN-debug] POST /convert/ --> main.convert (4 handlers)
[GIN-debug] Listening and serving HTTP on :8087
Used_f = false
Used_t = true
RawOfferData = some raw data here
Modified = {2019-06-09 15:48:38.978689 +0000 UTC true}
Created = {2019-06-09 15:48:38.97823 +0000 UTC true}
[GIN] 2019/06/09 - 11:48:39 |[97;42m 200 [0m| 16.979399ms | 127.0.0.1 |[97;46m POST [0m /convert/
TA贡献1852条经验 获得超7个赞
默认情况下,django 日期时间字段具有时区支持。你需要换个方式思考。或者您可以使用 django-extentions 。此第三方软件包附带一个创建和修改的日期时间字段,该字段不记录时区,使用这两个字段您将得到类似 {0001-01-01 00:00:00 } 的输出
TA贡献1827条经验 获得超4个赞
我使用了一个肮脏的技巧来序列化日期:
def toJson(self):
ret = {}
date_handler = lambda obj: (
obj.isoformat()
if isinstance(obj, (datetime.datetime, datetime.date))
else None
)
ret["Created"] = str(json.dumps(self.created, default=date_handler)).replace("\"","")
ret["Modified"] = str(json.dumps(self.modified, default=date_handler)).replace("\"","")
ret["Used"] = self.used
ret["Raw"] = self.raw
return ret
我希望有人能找到更好的解决方案
- 3 回答
- 0 关注
- 115 浏览
添加回答
举报