将python代码转换为json编码

2024-04-29 20:16:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经编写了这段python代码-

import json
import time
import hmac
import hashlib
import requests
    
secret = "somekey"
url = f"https://api.coindcx.com/exchange/v1/orders/status"
timeStamp = int(round(time.time() * 1000))
body = {
    "id": "ead19992-43fd-11e8-b027-bb815bcb14ed",
    "timestamp": timeStamp
}
json_body = json.dumps(body, separators=(',', ':'))
signature = hmac.new(secret.encode('utf-8'), json_body.encode('utf-8'), hashlib.sha256).hexdigest()
print(signature)
headers = {
    'Content-Type': 'application/json',
    'X-AUTH-APIKEY': "someapikey",
    'X-AUTH-SIGNATURE': signature
}
response = requests.post(url, data=json_body, headers=headers)
print(response)

在围棋中我试着这样写-

type GetOrderStatusInput struct {   
    ID string `json:"id"`
    Timestamp int64  `json:"timestamp"` 
}

timestamp := time.Now().UnixNano() / 1000000 
getOrderStatusInput := GetOrderStatusInput{ 
    ID: "ead19992-43fd-11e8-b027-bb815bcb14ed",         
    Timestamp: timestamp,   
}

但我不知道如何在这里进行json编码和hmac


Tags: importidjsonurlsecrettimebodyrequests
1条回答
网友
1楼 · 发布于 2024-04-29 20:16:14
package main

import (
    "bytes"
    "crypto/hmac"
    "crypto/sha256"
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
    "time"
)

func main() {
    secret := "somekey"
    url := "https://api.coindcx.com/exchange/v1/orders/status"
    type GetOrderStatusInput struct {
        ID        string `json:"id"`
        Timestamp int64  `json:"timestamp"`
    }

    timestamp := time.Now().UnixNano() / 1000000
    getOrderStatusInput := GetOrderStatusInput{
        ID:        "ead19992-43fd-11e8-b027-bb815bcb14ed",
        Timestamp: timestamp,
    }
    jsonBytes, err := json.Marshal(getOrderStatusInput)
    if err != nil {
        // handle error
    }

    mac := hmac.New(sha256.New, []byte(secret))
    mac.Write(jsonBytes)
    signature := mac.Sum(nil)

    jsonBody := bytes.NewReader(jsonBytes)

    req, _ := http.NewRequest("POST", url, jsonBody)
    req.Header.Set("Content-Type", "application/json")
    req.Header.Set("X-AUTH-APIKEY", "someapikey")
    req.Header.Set("X-AUTH-SIGNATURE", string(signature))

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        // handle error
    }
    defer resp.Body.Close()

    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        // handle error
    }

    fmt.Println(string(body))
}

相关问题 更多 >