簡體   English   中英

使用 Python 請求向本地主機發出 POST 請求

[英]POST request to localhost using Python requests

我的 Django 網站在端口 8000 的本地服務器上運行。我想從一個單獨的 python 文件發送一個發布請求,觸發我網站的一個端點。

但是即使添加了所有必需的信息后也無法做到這一點。 請幫忙!!

import requests
URL = 'http://127.0.0.1:8000/api/org/create/'
client = requests.Session()
client.get(URL)
csrftoken = client.cookies['csrftoken']

data = dict(csrfmiddlewaretoken=csrftoken)
headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36'}
response = client.post(URL, data=data,cookies=client.cookies, headers=headers)
print(response.status_code)

它給了我這個錯誤。

EC:\Program Files\Python37\lib\unittest\case.py:643: ResourceWarning: unclosed <socket.socket fd=420, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=('127.0.0.1', 10510), raddr=('127.0.0
.1', 8000)>
  outcome.errors.clear()

======================================================================
ERROR: test_org_create (test_org.TestOrg)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "\test_org.py", line 13, in test_org_create
    csrftoken = client.cookies['csrftoken']
  File "\venv\lib\site-packages\requests\cookies.py", line 328, in __getitem__
    return self._find_no_duplicates(name)
  File "\venv\lib\site-packages\requests\cookies.py", line 399, in _find_no_duplicates
    raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))
KeyError: "name='csrftoken', domain=None, path=None"

如何解決這個問題? 請評論任何其他信息。

因此,請查看以下部分中的錯誤和請求文檔

def _find_no_duplicates(self, name, domain=None, path=None):
        """Both ``__get_item__`` and ``get`` call this function: it's never
        used elsewhere in Requests.

       ... blah blah ignore this, alot of stuff

        :raises KeyError: if cookie is not found
     
       ... blah blah also ignore this, another lot of stuff

看到:raises KeyError: if cookie is not found似乎您缺少 cookie。 您是否檢查過它是否按預期在響應中正確設置?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM