【问题标题】:Make HTTP request with cherrypy使用cherrypy发出HTTP请求
【发布时间】:2014-05-09 18:22:13
【问题描述】:

我已经搜索了很长时间,但我找不到任何关于如何使用cherrypy 创建 HTTP 请求的文档。

我想实现这样的目标:

@cherrypy.expose
def index(self):

    json = http_request("http://somesite/")

    processed = process_json(json)

    tmpl = env.get_template("template.html")
    return tmpl.render(data=processed)

知道如何实现这一点吗?

【问题讨论】:

  • 看看 python requests 库。见docs.python-requests.org/en/latest
  • Cherrypy 用于服务请求而不是创建请求。您应该使用 urllib 或 requests 来发送 HTTP 请求。

标签: python httprequest cherrypy


【解决方案1】:

如果你在谈论 python 3,你需要 urllib。

import urllib.request

@cherrypy.tools.json_in() 
@cherrypy.expose
def index(self):    
    httpreq = urllib.request.Request(url="http://somesite/")
    response = urllib.request.urlopen(httpreq)
    jsonobject = response.read()

如果您需要其他版本的 python,请告诉我。

希望这会有所帮助!

【讨论】:

  • 我用的是2.7,有没有类似的?
猜你喜欢
  • 2011-03-31
  • 1970-01-01
  • 1970-01-01
  • 2023-02-06
  • 2019-10-20
  • 2015-04-24
  • 2017-01-23
相关资源
最近更新 更多