【python】0、超详细介绍:json、http

一、json

import json
f = open('data.json') # open json file
data = json.load(f) # 读出 json object
for i in data['emp_details']: # 取出一级属性 emp_details, 下的各二级属性
    print(i)
// 正确的 json 格式如下, 但它无法通过 python 的 request(json.dumps(payload)) 库发送
{
    "Face": false,
    "Id": null
}

// 能通过 python 的 request(json.dumps(payload)) 库发送的如下
{
    "Face": False, // 需大写 F
    "Id": None // 需为 None 而不是 null
}

二、http

def rec_image(url):
    server_addr = "http://192.168.100.99:8000/api"
    payload = {
        'image': {
            'url': url,
        }
    }
    headers = {'Content-Type': 'application/json'}
    resp = requests.post(server_addr, json=payload, headers=headers) # 或将 json=payload 替换为 data=json.dumps(payload)
    print(resp.text)

requests http

2.1 json 读取 + request 序列化

import json
import requests

def send_request(task_id):
    url = "http://192.168.2.99:8000/new"
    with open("my.json") as file:
        content = json.load(file) # 读出 json object
    content["task_id"] = task_id  # 根据 key 更改 value
    payload = json.dumps(content) # 将 json object 序列化为 json string
    print(payload)

    headers = {"Content-Type": "application/json"}
    response = requests.request("POST", url, headers=headers, data=payload) # 向 request 包传入 json string 参数
    print("response: ", response.text)

send_request("task1")

三、基本类型

3.1 decimal

# 保留两位小数
a = 12.345
round(a, 2) # 12.34
print("%.2f", a) # 12.34

序列化时注意:

  • js 的 null 值对应 py 的 None
  • js 的 bool 值只有 True 和 False (没有 true 和 false)

四、图像

4.1 颜色格式转换

hex: #0C78B7
rgb: (12,120,183)
这两种颜色格式,可通过RGB颜色值与十六进制颜色码转换转换,和RGB颜色查询查询

也可通过代码实现:

def Hex_to_RGB(hex):
    r = int(hex[0:2],16)
    g = int(hex[2:4],16)
    b = int(hex[4:6], 16)
    return tuple([r,g,b]) # 将 list 转为 tuple
  • 9
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

呆呆的猫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值