Press ESC to close

wordpress调用REST API通过python发送文章

代码:

# coding: utf-8
import base64
import json
import requests
from pprint import pprint


def main():
    # Init
    url = "https://www.xatest.net/blog/wp-json/wp/v2/posts"
    username = "xxx"
    password = "xxx"
    credentials = "{}:{}".format(username, password)
    token = base64.b64encode(credentials.encode())

    # Header
    headers = {
        "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36",
        "Authorization": "Basic {}".format(token.decode("utf-8")),
        "content-type": "application/json",
    }

    # Post info
    post = {
        "title": "This is a REST API test",
        "content": "Accessed.",
        "status": "publish"
    }

    # Post
    r = requests.post(
        url,
        headers=headers,
        json=post,
    )

    # Print
    pprint(r.text)


if __name__ == "__main__":
    main()

发表回复