【问题标题】:Python is inserting newline characters into requests headerPython正在将换行符插入请求标头
【发布时间】:2020-04-04 22:54:14
【问题描述】:

一些背景。此代码从数据收集脚本中获取数据,然后将其发布到 Django 中的安全 REST API。我生成了一个 api 密钥,它是文件 api.key 中的唯一行。我还有要发布到文件 post.url 中的 url(它看起来像 http://example.com/api/,然后我在最后连接正确的 api 节点名称)。

下面是我的太阳能数据 api 节点的代码(发布从太阳能电池板收集的数据)

import gather_solar as gs
import requests
import json
import os

def post_solar():
print("DEBUG: start solar")
data = gs.gather_solar()
api_key = None
url = None
try:
    here = os.path.dirname(os.path.abspath(__file__))
    filename = os.path.join(here, 'api.key')
    file = open(filename, "r")
    api_key = file.readline()
    api_key.replace('\n', '')
except Exception as e:
    print("ERROR: " + str(e))

try:
    here = os.path.dirname(os.path.abspath(__file__))
    filename = os.path.join(here, 'post.url') #server will use different url
    file = open(filename, "r")
    url = file.readline()
    url.replace('\n', '')
except Exception as e:
    print("ERROR: " + str(e))

if api_key is not None and url is not None:
    authorization = "Token " + api_key
    authorization.replace('\n', '')
    headers = {
        'Content-Type': 'application/json; charset=UTF-8',
        'Authorization': authorization
    }
    json_data = json.dumps(data)
    url += "solar/"        
    url.replace('\n', '')
    print(url)
    req = requests.Request('POST', url, data=json_data, headers=headers)
    prepared = req.prepare()
    print("DEBUG: POST Headers: " + str(prepared.headers))
    print("DEBUG: POST Body: " + str(prepared.body))

    s = requests.Session()
    response = s.send(prepared)
    print("DEBUG: Response Code: " + str(response.status_code))
    print("DEBUG: Response Headers: " + str(response.headers))
    print("DEBUG: Response Data: " + str(response.json()))
else:
    print("DEBUG: Error with API key")

print("DEBUG: end solar")

我正在通过 AWS 在 ubuntu 服务器上运行代码,并安装并运行 Apache 2。但是,每当我运行此脚本时,我都会收到一条错误消息,指出我的令牌无效,并将令牌显示为 "Token abcd...abcd\n" 。这尤其令人沮丧,因为当我在本地运行脚本(Win10 上的 Visual Studio 代码)时我没有遇到这个问题正如您所见,我已尝试尽可能删除任何换行符,但它似乎没有帮助。任何帮助将不胜感激

【问题讨论】:

    标签: django python-3.x python-requests apache2


    【解决方案1】:

    replace() 不改变字符串(字符串是不可变的);它返回一个新字符串。所以:

    api_key = file.readline()
    api_key.replace('\n', '')
    

    \n 保留在api_key 上,您将忽略replace() 返回的新字符串。

    你可以在赋值之前把这行串起来:

    api_key = file.readline().strip()
    

    【讨论】:

    • 我必须使用 str(file.readline().strip()) 将密钥设置为字符串,但否则这行得通。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-01
    • 1970-01-01
    • 2019-01-08
    • 2018-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多