请求的两个API

news/2024/7/19 15:48:09 标签: java, python, 设计模式, js, 数据库

Kenneth Reitz’s excellent Requests library has been praised, rightfully, for its excellent API. In fact, its API is so good that it’s been praised in a literary context, as well as by almost every programmer who has come across it. There is no question that this API is one of the best you can find in the Python world. It has even inspired other programmers’ API design.

肯尼斯·雷茨 ( Kenneth Reitz )出色的请求库因其出色的API而受到称赞。 实际上,它的API是如此出色,以至于它在文学领域以及几乎所有遇到过它的程序员中都得到了好评。 毫无疑问,此API是您在Python世界中可以找到的最好的API之一。 它甚至启发了其他程序员的API设计 。

What a lot of people seem not to know, however, is that Requests actually has two APIs. The first API is the highly-praised procedural and object-oriented API that drives making and interacting with HTTP traffic. The second API appeared when Kenneth undertook the giant refactor for v1.0. This is Requests’ barely heralded inheritance-based API.

但是,很多人似乎不知道的是,请求实际上有两个API。 第一个API是备受赞誉的过程化和面向对象的API,它可以推动HTTP流量的生成并与之交互。 当肯尼斯(Kenneth) 对v1.0进行了巨大的重构时,出现了第二个API。 这是Requests几乎没有公开的基于继承的API。

请求的继承API (Requests’ Inheritance API)

To discuss the second, super secret Requests API we need to draw one very import distinction. This distinction is between properties of a single HTTP request (things like data, headers and cookies) and things that are properties of the connection (things like the kinds of SSL you can use, or what IP address you send data from).

为了讨论第二个超级机密的Requests API,我们需要区分一个非常重要的区别。 这种区别是在单个HTTP请求的属性(诸如数据,标头和cookie之类的事物)与作为连接属性的事物(诸如您可以使用的SSL类型或您从其发送数据的IP地址之类的事物)之间的区别。

Requests by and large exposes the first kind of property on its ‘standard’ API. You can set the headers, and the body data, and the cookies, all through the arguments to the Request object and as properties of the Session object. This makes sense: this is the kind of thing that is really specific to a single request or session of requests.

总体而言,请求在其“标准” API上公开了第一种属性。 您可以通过Request对象的参数以及Session对象的属性来设置标题,正文数据和cookie。 这是有道理的:这是真正针对单个请求或请求会话的事情。

But what about the second kind of thing? Where do you set that? Some of the most-used stuff bubbles its way up to the main API so that it’s easily accessible, but most of it is hardcoded.

但是第二种事情呢? 您在哪里设置? 一些最常用的东西冒充了通往主API的道路,因此很容易访问,但是大多数都是硬编码的。

I can hear some of you now. “Kenneth hardcoded these options? How awful!” In the Requests versions v0.14.2 and earlier, I’d have probably agreed with you. They aren’t options people want often, but it would be good to have access to them.

我现在可以听到你们中的一些人。 “肯尼思对这些选项进行了硬编码? 真可怕!” 在Requests v0.14.2及更早版本中,我可能已经同意您的观点。 这些不是人们经常想要的选择,但最好能使用它们。

The problem is: how do you give access to these options without cluttering the main API so much your documentation looks like this?

问题是:你怎么给访问这些选项而不会扰乱了主要的API这么多你的文档看起来像这样 ?

通过继承进行配置 (Configuration Through Inheritance)

If you look carefully at the Requests code, you’ll notice that there are two major objects involved in each request. The first is the Requests Session object (requests.Session). The second is the Requests default Transport Adapter, the HTTPAdapter (requests.adapters.HTTPAdapter). These two objects maintain all of the configuration in Requests.

如果仔细查看“请求”代码,您会发现每个请求涉及两个主要对象。 第一个是Requests Session对象( requests.Session )。 第二个是请求默认传输适配器 ,所述HTTPAdapter( requests.adapters.HTTPAdapter )。 这两个对象维护请求中的所有配置。

The Session object is almost entirely concerned with the first kind of property. You can set default headers and default cookies, and that all goes really well. But what if you want to handle the second kind? The answer is surprisingly simple: subclass the HTTPAdapter.

Session对象几乎完全与第一种属性有关。 您可以设置默认的标头和默认的cookie,一切都很好。 但是,如果您想处理第二种呢? 答案非常简单:将HTTPAdapter子类化。

The HTTPAdapter manages all of the connection-level behaviour, and doesn’t expose much in the way of options on its constructor. The real way to affect this behaviour is to subclass it and create your own.

HTTPAdapter管理所有连接级别的行为,并且在其构造函数中的选项方面没有太多暴露。 影响此行为的真正方法是将其子类化并创建自己的行为。

例子 (Examples)

I’ve shown this configuration once before on this blog, but I want to provide a few examples of what I mean. The first is one I’ve shown before: selecting an SSL version.

我之前在此博客上已经显示了此配置,但是我想提供一些我的意思的示例。 第一个是我之前显示的:选择一个SSL版本。

from from requests.adapters requests.adapters import import HTTPAdapter
HTTPAdapter
from from requests.packages.urllib3.poolmanager requests.packages.urllib3.poolmanager import import PoolManager

PoolManager

class class SSLAdapterSSLAdapter (( HTTPAdapterHTTPAdapter ):
    ):
    '''An HTTPS transport adapter that uses an arbitrary SSL version.'''
    '''An HTTPS transport adapter that uses an arbitrary SSL version.'''
    def def __init____init__ (( selfself , , ssl_versionssl_version == NoneNone , , **** kwargskwargs ):
        ):
        selfself .. ssl_version ssl_version = = ssl_version
        ssl_version
        supersuper (( SSLAdapterSSLAdapter , , selfself )) .. __init____init__ (( **** kwargskwargs )

    )

    def def init_poolmanaagerinit_poolmanaager (( selfself , , connectionsconnections , , maxsizemaxsize ):
        ):
        selfself .. poolmanager poolmanager = = PoolManagerPoolManager (( num_poolsnum_pools == connectionsconnections ,
                                       ,
                                       maxsizemaxsize == maxsizemaxsize ,
                                       ,
                                       ssl_versionssl_version == selfself .. ssl_versionssl_version ))

You can unconditionally sign requests:

您可以无条件签署请求:

You can even support totally different protocols (though having done that myself, I don’t entirely recommend it, but it can be done).

您甚至可以支持完全不同的协议 (尽管我自己做过,但我并不完全推荐这样做,但是可以做到)。

为什么这样有效 (Why This Works)

The reason this works is because Requests allows you to configure the backend, using Session.mount(). Before you could do this, anything that was not contained in the Session object was totally inaccessible to users. This meant if you wanted to change the sending logic, you had to subclass the Session and get your hands dirty in the 2000-line send function.

之所以可行,是因为Requests允许您使用Session.mount()配置后端。 在执行此操作之前,用户完全无法访问Session对象中未包含的任何内容。 这意味着,如果您想更改发送逻辑,则必须将Session子类化,并动手使用2000行send功能。

翻译自: https://www.pybloggers.com/2013/04/requests-two-apis/


http://www.niftyadmin.cn/n/982316.html

相关文章

HTML 钟表 小时钟

该放假了,心情不好,写个小表针感慨一下时间为什么过得如此之快,写了个小钟表. 提示 1:这个钟表的秒针转的非常快,如果需要和当前的网络时间一样,请修改</script>上一行的代码,把1换成1000 2:无需素材.直接运行即可 3:如有bug请直接留言 <!DOCTYPE html><html>…

sql 删除重复语句只保留一条

1.查询重复记录 select * from 表名where 重复字段 in (select 重复字段 from 表名 group by 重复字段 having count(重复字段) > 1) 2.删除保留一条重复记录 delete from 表名where 重复字段 in (select 重复字段 from 表名 group by 重复字段 having count(重…

Python中的绝对导入和相对导入

If you’ve worked on a Python project that has more than one file, chances are you’ve had to use an import statement before. 如果您从事的Python项目有多个文件&#xff0c;那么您以前可能不得不使用import语句。 Even for Pythonistas with a couple of projects u…

栈应用——最长括号匹配

问题描述&#xff1a; 给定字符串&#xff0c;仅包含左括号(和右括号)&#xff0c;它可能不是括号匹配的&#xff0c;设计算法&#xff0c;找出最长的括号字串&#xff0c;并返回字串的长度。 如&#xff1a; ((): 2 ()(): 4 ()(()):6 (()()): 6 思路分析&#xff1a; 记起始位…

gitlab:gitlab-runner多服务器自动部署项目

服务器gitlab 已经搭建好 搭建gitlab-runner服务器之间建立免密登陆跑.gitlab-ci.yml 搭建gitlab-runner 1.下载执行文件 sudo wget -O/usr/local/bin/gitlab-runner https://gitlab-runner-downloads.s3.amazonaws.com/latest/binaries/gitlab-runner-linux-amd64 2.设置…

【★★★★★】提高PHP代码质量的36个技巧

http://www.cnblogs.com/52php/p/5658031.html 不要直接使用 $_SESSION 变量 某些简单例子: $_SESSION[username] $username; $username $_SESSION[username]; 这会导致某些问题. 如果在同个域名中运行了多个应用, session 变量可能会冲突. 两个不同的应用可能使用同一个ses…

ipython_IPython笔记本

ipythonLast PyCon US (2013) I attended, there were many interesting talks, but if I had to talk about what’s happening, what’s the trend, between other things I would mention IPython Notebook. 我参加的上一届PyCon US&#xff08;2013&#xff09;上有很多有趣…

java判断字符串是否回文

java判断字符串是否回文 /*** java判断字符串是否回文<br><br>* 基本思想是利用字符串首尾对应位置相比较* * author InJavaWeTrust**/ public class Palindrome {public static boolean isPalindrome(String str) {boolean bool true;for (int i 0; i < str.…