简体   繁体   English

如何优化 python 请求?

[英]How can I optimize python requests?

I have been trying to optimize requests but i can't figure it out我一直在尝试优化请求,但我无法弄清楚

def chuck_norris_jokes():
    import requests
    url = "https://api.chucknorris.io/jokes/random"
    response = requests.request("GET", url)
    dict = response.text
    import json
    test_string = dict 
    dict = json.loads(test_string)
    print(dict.get('value'))

It's not specified what you are trying to optimize.它没有指定您要优化的内容。

In case you are looking to optimize the code, you can drop the json import and use the .json method of requests response object:如果您希望优化代码,您可以删除json导入并使用请求响应 object 的.json方法:

import requests

url = "https://api.chucknorris.io/jokes/random"

def chuck_norris_jokes():
    response = requests.get(url)
    print(response.json().get('value'))

chuck_norris_jokes()

If the problem is that you want to run this function hundreds of times and it is taking too long than the problem is not with the code but with the duration of the requests.如果问题是您想运行此 function 数百次,并且它花费的时间太长,那么问题不在于代码,而在于请求的持续时间。 If this is the case I would look into the Python threading or asyncio modules.如果是这种情况,我会研究asyncio threading或异步模块。

just move the imports outside of the function.只需将imports移到 function 之外。 Remove test_string = dict .删除test_string = dict

This works:这有效:

import requests
import json

def chuck_norris_jokes():
    url = "https://api.chucknorris.io/jokes/random"
    response = requests.request("GET", url)
    x = response.text
    d = json.loads(x)
    print(d.get('value'))

chuck_norris_jokes()

this returns one of the jokes.这返回了一个笑话。

I guess you are trying to optimize the code, maybe you can do something like that我猜你正在尝试优化代码,也许你可以做类似的事情

def chuck_norris_jokes():
    import requests, json
    url = "https://api.chucknorris.io/jokes/random"
    response = requests.request("GET", url)
    print(json.loads(response.text).get('value'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM