[英]How can i take data one line at a time from a txt file and use it as a variable to send requests?
I'm currently working on a small side project that I thought was cool.我目前正在做一个我认为很酷的小项目。 However, I've reached a big road blockage.
但是,我遇到了很大的障碍。 I'm trying to get it to read a username from a text file and upload it to an API, however, I keep getting error code 400 with a server response stating that the username field was empty in the request.
我试图让它从文本文件中读取用户名并将其上传到 API,但是,我不断收到错误代码 400,服务器响应表明请求中的用户名字段为空。 I also added a print statement to confirm the credential variable was set correctly, and it was making me think it was a communication error from me to the API. I think another problem may be that I set the content type to "plain/text".
我还添加了一个打印语句来确认凭证变量设置正确,这让我认为这是我与 API 的通信错误。我认为另一个问题可能是我将内容类型设置为“纯文本” . I ran Wireshark to see the exact request I made, and it looks like everything is scrunched together.
我运行 Wireshark 查看我提出的确切请求,看起来所有内容都被压缩在一起。 Here is my current code:
这是我当前的代码:
import requests
import time
with open('./user.txt', 'r') as f:
creds = f.read()
print(f"Current User: {creds}")
url = 'http://example.com/api'
data = {f"nickname":"{creds}","password":"{creds}","email":"","referral":"null"}
headers = {'Content-Type': 'text/plain'}
response = requests.post(url, data=data, headers=headers)
I'm pretty new to using the requests library, so I'm sorry if this is a bad question to ask, but any help will be really appreciated.我对使用请求库还很陌生,所以如果这是一个糟糕的问题,我很抱歉,但我们将不胜感激任何帮助。
Wireshark states that my request data is nickname=%7Bcreds%7D&password=%7Bcreds%7D
. Wireshark 声明我的请求数据是
nickname=%7Bcreds%7D&password=%7Bcreds%7D
。
import time
import requests
import json
with open('./user.txt', 'r') as f:
for line in f:
creds = line.strip()
print(f"Current User: {creds}")
url = 'http://example.com/api'
data = {f"nickname":"{creds}","password":"{creds}","email":"","referral":"null"}
headers = {'Content-Type': 'application/json'}
response = requests.post(url, data=json.dumps(data), headers=headers)
print(response.status_code)
print(response.text)
The problem was with my header type!问题出在我的 header 类型上! I didn't need to use
JSON
or plain/text
.我不需要使用
JSON
或plain/text
。 I used application/x-www-form-urlencoding
, which I got from the file's history.我使用了
application/x-www-form-urlencoding
,这是我从文件的历史记录中获得的。 The application now reads each username and password, and sends it to the server!应用程序现在读取每个用户名和密码,并将其发送到服务器!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.