代码之家  ›  专栏  ›  技术社区  ›  Fabián Gabriel L.S.

为什么make POST REQUEST的头文件不起作用,但使用Auth时却起作用??(WORDPRESS)

  •  0
  • Fabián Gabriel L.S.  · 技术社区  · 1 年前

    我试图将数据库(SQLite)作为JSON文件发送并在Wordpress中发布(我还想编辑行和列等),但当我这样做时,在python中使用请求库做一个简单的帖子会在我使用这行代码时抛出以下错误: header = {"user": username, "password": password} response = requests.post(url, headers=header, json=data)

    {“代码”:“rest_cannot_edit”,“消息”:“Lo siento,没有任何编辑许可证。”,“数据”:{“状态”:401}}

    但是,当我在requests.post函数中使用auth时,它会工作,它只使用以下命令发送信息: response = requests.post(url, auth=(username, password), json=data) 我的responde.status是200(帖子正确完成!)

    根据我找到的所有论坛,我需要插件应用程序密码,是的,我已经创建了我的TOKEN密码,就像上面一样,为什么?

    所有代码:

    import requests
    
    #PAGE WHERE I WANT TO SEND INFO
    url = "https://dca-mx.com/wp-json/wp/v2/pages/362"
    
    username = 'Fabian'
    # The application password you generated
    password = 'XXXX XXXX XXXX XXXX XXXX'
    
    # The post data
    data = {
        'title': 'DCA DB',
        'content': 'HELLO FROM PYTHON.',
        'status': 'publish'
    }
    
    header = {"user": username, "password": password}
    
    # Send the HTTP request THIS WORKS
    response = requests.post(url, auth=(username, password), json=data)
    #THIS DOES NOT WORKS WHY??????!!!!!!!!!!!
    response = requests.post(url, headers=header, json=data)
    
    # Check the response
    if response.status_code == 201:
        print('Post created successfully')
    elif response.status_code == 200:
        print('Posteado Correctamente!')
    else:
        print(response.text)
    
    1 回复  |  直到 1 年前
        1
  •  2
  •   dann    1 年前

    问题在于如何处理您的身份验证 requests.post 电话。使用WordPress REST API处理身份验证有两种主要方法。

    当您使用auth参数时,您正在使用基本身份验证,这就是它工作的原因,请检查您的代码:

    response = requests.post(url, auth=(username, password), json=data) .

    尽管auth参数在内部为Basic Athentication设置了正确的Authorization标头,但在直接使用标头时,您需要正确格式化Authorization标头。您使用的标头字典的格式不正确,无法进行基本身份验证。所以,你需要设置 Authorization 带有base64编码字符串的标头 username:password .

    试试这个:

    import requests
    import base64
    
    # PAGE WHERE I WANT TO SEND INFO
    url = "https://dca-mx.com/wp-json/wp/v2/pages/362"
    
    username = 'Fabian'
    # The application password you generated
    password = 'XXXX XXXX XXXX XXXX XXXX'
    
    # The post data
    data = {
        'title': 'DCA DB',
        'content': 'HELLO FROM PYTHON.',
        'status': 'publish'
    }
    
    # Encode the username and password
    credentials = f"{username}:{password}"
    encoded_credentials = base64.b64encode(credentials.encode('utf-8')).decode('utf-8')
    header = {"Authorization": f"Basic {encoded_credentials}"}
    
    # Send the HTTP request (it should still work)
    response = requests.post(url, headers=header, json=data)
    
    # Now, check the response
    if response.status_code == 201:
        print('Post created successfully')
    elif response.status_code == 200:
        print('Posteado Correctamente!')
    else:
        print(response.text)
    

    希望它能帮助我,让我更新!