简体   繁体   English

没有请求的Python Post json API

[英]Python Post json API without Request

I am on a system without pip and its not planned to use.我在一个没有 pip 的系统上,并且不打算使用它。 Put I have do to a post with python to an API (With this post I want to add a row in a postgresdb)把我必须用 python 写到 API 的帖子(通过这篇文章,我想在 postgresdb 中添加一行)

it works with the following code.它适用于以下代码。 but there are two columns which are jsonb in postgres.但是postgres中有两列是jsonb。 With this code these columns have quotation marks, so the json doesn't work properly.使用此代码,这些列带有引号,因此 json 无法正常工作。

How can I avoid this?我怎样才能避免这种情况?

  import urllib.parse
import urllib.request
def_post_wo_requ
        json_post= { 'store' : 'Jack', 'store_detail' : {'Tel1':'00000','Tel2':'11111'}}
        url=host+'/'+ pg_table
        data = urllib.parse.urlencode(json_post)
    
        data = data.encode('utf-8')
        print(data)

The print data shows this:打印数据显示:

b'store=Jack&store_detail=%7B%27Tel1%27%3A+%2700000%27%2C+%27Tel2%27%3A+%2711111%27%7D'

and the json in the db is this: db中的json是这样的:

"{'Tel1': '00000', 'Tel2': '11111'}"

Do you need to convert the data to a string?您需要将数据转换为字符串吗? Would not this ("classic" approach) work ?这种(“经典”方法)不起作用吗?

from urllib import request
import json

url = 'https://myapp.domain/endpoint'
json_data= {'store': 'Jack', 'store_detail': {'Tel1': '00000','Tel2': '11111'}}

req = request.Request(url, method="POST")
req.add_header('Content-Type', 'application/json')
data = json.dumps(data)
data = data.encode()
r = request.urlopen(req, data=data)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM