Python请求标头。如何解析呢? AST的语法无效?

时间:2019-05-10 23:18:43

标签: python ssl python-requests http-headers tls1.2

我想将标题字符串转换为字典。字符串来自各种来源,因此格式有点复杂。

这是一个示例:

import ast
import re

header="{'Content-Type': 'text/html', 'Content-Security-Policy': "default-src 'self'; img-src 'self' https://www.google.com/ https://www.google-analytics.com/ https://stats.g.doubleclick.net/; form-action 'self' https://agilemail.createsend.com/ https://www.createsend.com/t/subscribeerror https://www.createsend.com/t/securedsubscribe; frame-src https://www.youtube-nocookie.com/; connect-src 'self'", 'X-Content-Type-Options': 'nosniff', 'X-Amz-Cf-Id': 'XZOj8R9YBVEMbHv93beUYFIizxUbrGKL_LVrS1gjMF-86I8mgtNFYw=='}"

headerDict = ast.literal_eval(header)

运行它时,出现此错误:

SyntaxError: invalid syntax

我将字符串"default-src [...] https://a.1password.eu/"中的两个双引号从"更改为""

但是仍然存在错误。显然是从'self'的内容开始,其中包含单引号。

我完全不应该更改标题内容。但是,例如,如果我应用一条规则,则将每个"替换为"",这是可行的解决方案。由于我需要解析标题。它应该保留其原始数据,我不应该对其进行任何更改。

在这种情况下,解决方案是什么?这是一个示例,但我希望看到其他变体。如何将类似dict的字符串转换成字典?

1 个答案:

答案 0 :(得分:2)

使用三引号引起来的字符串:

import ast

header = """{'Content-Type': 'text/html', 'Content-Security-Policy': "default-src 'self'; img-src 'self' https://www.google.com/ https://www.google-analytics.com/ https://stats.g.doubleclick.net/; form-action 'self' https://agilemail.createsend.com/ https://www.createsend.com/t/subscribeerror https://www.createsend.com/t/securedsubscribe; frame-src https://www.youtube-nocookie.com/; connect-src 'self'", 'X-Content-Type-Options': 'nosniff', 'X-Amz-Cf-Id': 'XZOj8R9YBVEMbHv93beUYFIizxUbrGKL_LVrS1gjMF-86I8mgtNFYw=='}"""

ast.literal_eval(header)

输出:

{'Content-Type': 'text/html',
 'Content-Security-Policy': "default-src 'self'; img-src 'self' https://www.google.com/ https://www.google-analytics.com/ https://stats.g.doubleclick.net/; form-action 'self' https://agilemail.createsend.com/ https://www.createsend.com/t/subscribeerror https://www.createsend.com/t/securedsubscribe; frame-src https://www.youtube-nocookie.com/; connect-src 'self'",
 'X-Content-Type-Options': 'nosniff',
 'X-Amz-Cf-Id': 'XZOj8R9YBVEMbHv93beUYFIizxUbrGKL_LVrS1gjMF-86I8mgtNFYw=='}