如何重新格式化使用 curlify lib 请求的结果?

How to reformat result of using curlify lib for request?

提问人:Katrin T 提问时间:10/19/2023 最后编辑:Brian Tompsett - 汤莱恩Katrin T 更新时间:10/19/2023 访问量:24

问:

Pyrhon、GraphQL、Allure 报告、请求。

我需要将请求详细信息附加到我的 repotr。 我使用 curlify lib,但无法重新格式化结果以使其易于阅读。

import curlify
def def api_request(method='POST', **kwargs):
    with allure.step(f"{method.upper()}{base_url}"):
        with sessions.Session() as session:
            response = session.request(method=method, url=base_url, **kwargs)
            message = to_curl(response.request)

            allure.attach(
                body=message.encode("utf-8"),
                name="Curl",
                attachment_type=AttachmentType.TEXT,
                extension='txt'

我得到的附件看起来像:

curl -X POST -H 'Accept: */*' -H 'Accept-Encoding: gzip, deflate' -H 'Connection: keep-alive' -H 'Content-Length: 318' -H 'Content-Type: application/json' -H 'User-Agent: python-requests/2.31.0' -d '{"query": "\n    mutation Mutation($email: String!, $password: String!) {\n    tokenAuth(email: $email, password: $password) {\n        token\n        refreshToken\n        refreshExpiresIn\n        __typename\n      }\n    }\n    ", "variables": {"email": "ABC", "password": "ABC"}}' https://url/api/v2/graphql/

但我至少想以这种方式重新格式化查询:

curl -X POST -H 'Accept: */*' -H 'Accept-Encoding: gzip, deflate' -H 'Connection: keep-alive' -H 'Content-Length: 318' -H 'Content-Type: application/json' -H 'User-Agent: python-requests/2.31.0' -d '
{"query": " mutation Mutation($email: String!, $password: String!) 
   { tokenAuth(email: $email, password: $password) {        
      token        
      refreshToken        
      refreshExpiresIn        
      __typename      
   }    
}    ", 
"variables": {"email": "ABC", "password": "ABC"}}' https://url/api/v2/graphql/

需要你的帮助!

我试图将结果转换为 JSON 并使用 ,但预计它不起作用。json.dumps(response.json(), ensure_ascii=False, indent=4).encode("utf-8")

python graphql 请求 附件

评论


答:

0赞 Katrin T 10/19/2023 #1

message.replace(r'\n', '\n')可用于解决问题。 但是,如果有更简单的方法来重新格式化呢?