Python 正在向请求中插入换行符 header

Python is inserting newline characters into requests header

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

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

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

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

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

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

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

api_key = file.readline().strip()