以下哪一个是请求 API 的好方法?

发布于 2024-09-06 18:18:27 字数 438 浏览 3 评论 0原文

每当查看 Python 的 API 库时,似乎其中大约一半只是使用:

response = urllib2.urlopen('https://www.example.com/api', data)

大约一半使用:

connection = httplib.HTTPSConnection('www.example.com/api')
# ... rest omitted for simplicity

我倾向于认为第二个版本“更酷”(我偏向于对大多数事情采用更多的 OO 方法)。

使用其中一种比另一种有好处或理由吗?或者,我一路上错过了什么吗?我怀疑 urllib2.urlopen 在其实现中使用了 HTTPSConnection ,所以也许只是代表我减少了编码。无论哪种方式,我都希望得到一些反馈。谢谢。

Whenever looking at API libraries for Python, there seems to be about half of them simply using:

response = urllib2.urlopen('https://www.example.com/api', data)

and about half using:

connection = httplib.HTTPSConnection('www.example.com/api')
# ... rest omitted for simplicity

I tend to think the second version is "cooler" (I'm biased towards a more OO approach to most things).

Is there a benefit or reason for using one over the other. Or, am I missing something along the way. I would suspect that urllib2.urlopen uses HTTPSConnection in its implementation, so perhaps one is simply less coding on my behalf. Whichever way, I'd love some feedback. Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

自在安然 2024-09-13 18:18:27

是的,urllib2 在其实现中使用 HTTPSConnection(或任何适合该协议的连接类型)。它基本上只是人们使用 httplib 执行最常见操作的快捷方式。

urllib2 还具有一些代码来处理重定向和身份验证请求等事务,如果您使用普通的 httplib 执行这些操作,则可能需要手动编写所有内容。

编辑:作为对迈克尔评论的回应,如果您想知道对象与数据......这在某种程度上取决于您要如何处理它。如果您需要连接对象(例如,用它做一些特殊的事情,可能是保持连接),那么当然,继续使用httplib方式并返回连接对象。但如果您只是想获取数据,只需获取数据并返回即可。如果您喜欢 OOP,请知道 Python 中的所有内容从技术上讲都是对象;从 urllib2.urlopen 得到的是一个类似文件的对象,它具有以字符串对象或行列表(也是字符串对象)的形式检索其值的方法。我认为大多数 Python 程序员会认为在后一种情况下使用 httplib 是浪费精力。

Yep, urllib2 uses HTTPSConnection (or whatever kind of connection is appropriate for the protocol) in its implementation. It's basically just a shortcut to do the most common thing people do with httplib.

urllib2 also has some code to handle things like redirects and authentication requests, all stuff you might have to code manually if you were doing it with plain httplib.

EDIT: In response to Michael's comment, if you were wondering about object vs. data... it sort of depends on what you're going to do with it. If you need the connection object (e.g. to do something special with it, maybe a keepalive connection), then sure, go ahead and use the httplib way and return the connection object. But if you're just trying to get the data, just get the data and return it. If you like OOP, know that everything in Python technically is an object; what you get from urllib2.urlopen is a file-like object which has methods to retrieve its value as a string object or as a list of lines (also string objects). I think most Python programmers would consider it a waste of effort to use httplib in the latter case.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文