获得解析帖子
我似乎无法让它发挥作用。这就是我认为正在发生的事情:(但显然我做错了。)
尝试:
import requests
import json
#Token used to post
auth_token = "X"
#Take and parse payload for title and body at site 1.
def payload(nid):
from urllib.request import urlopen
with urlopen("www.site1.com/" + nid + ".json") as rr:
result = json.loads(rr.read().decode(rr.headers.get_content_charset("utf-8")))
title = (result["title"])
body = (result["body"]["und"])
#Take title, body, auth_token and then also nid from user input, and POSTing to site 2
def add(nid):
url = "www.site2.com/stuff.json"
headers = {"content-type": "application/json"}
payload = {
"auth_token": auth_token,
"document":
{
"external_id": nid,
"fields": [
{"name": "title", "value": title, "type": "string"},
{"name": "path", "value": "www.site1.com/node/"+nid,"type": "enum"},
{"name": "nid", "value": nid, "type": "integer"},
{"name": "body", "value": body, "type": "text"},
]}
}
r = requests.post(url, data=json.dumps(payload), headers=headers)
print("{} was added".format(nid))
while True:
#Trigger User Input
new_item = input("> ")
#Add nid
if new_item == "A":
nid = input("Give me an NID please: ")
payload(nid)
add(nid)
答案 0 :(得分:0)
您尚未在def add(nid)
函数参数/参数中传递title,body。
因此,要更正此问题,请修改def payload(nid)
以返回正文/标题&将此参数传递给add(nid,title,body)
函数。
希望这有帮助!
import requests
import json
#Token used to post
auth_token = "X"
#Take and parse payload for title and body at site 1.
def payload(nid):
from urllib.request import urlopen
with urlopen("www.site1.com/" + nid + ".json") as rr:
result = json.loads(rr.read().decode(rr.headers.get_content_charset("utf-8")))
title = (result["title"])
body = (result["body"]["und"])
return (title,body)
#Take title, body, auth_token and then also nid from user input, and POSTing to site 2
def add(nid,title,body):
url = "www.site2.com/stuff.json"
headers = {"content-type": "application/json"}
payload = {
"auth_token": auth_token,
"document":
{
"external_id": nid,
"fields": [
{"name": "title", "value": title, "type": "string"},
{"name": "path", "value": "www.site1.com/node/"+nid,"type": "enum"},
{"name": "nid", "value": nid, "type": "integer"},
{"name": "body", "value": body, "type": "text"},
]}
}
r = requests.post(url, data=json.dumps(payload), headers=headers)
print("{} was added".format(nid))
while True:
#Trigger User Input
new_item = input("> ")
#Add nid
if new_item == "A":
nid = input("Give me an NID please: ")
title,body = payload(nid)
add(nid,title,body)