一个非常简单的http/1.1请求模块。
yrequests的Python项目详细描述
年请求
一个非常简单的http/1.1请求模块。它基于python请求模块。
什么和为什么
yrequest只是requests函数的包装器,但它可以无声地处理连接和http错误。
如何使用
fromyrequestsimportYRequestsreq=YRequests()# you can pass "headers" (dict) or a "timeout" (secs) tooresult=req.get('http://url.com/a/b/c',params={'q':'apple'})ifresult['ok']:print(result['text'])# If you except a JSON uses result['json']# ...and other stuffs when everything is fineelse:# Connections, HTTP and general errorsprint(result['error'])# or result['status_code']# and other stuffs when an error occurs
您还可以使用post
、put
、delete
、head
和options
。这些(http)方法接收requests模块的相同参数。如果需要有关“请求”模块工作原理的说明,请查看:http://docs.python-requests.org/en/master/user/quickstart/
安装
要安装yrequest,只需使用pip。
pip install yrequests
yrequests类
yrequests(超时=60,头=无)
- 超时:所有请求的默认超时(秒)。
- headers:所有请求的默认头(
dict
)。
yrequests.get(url,*args,**kwargs)yrequests.post(url,*args,**kwargs)yrequests.delete(url,*args,**kwargs)yrequests.put(url,*args,**kwargs)yrequests.head(url,*args,**kwargs)yrequests.options(url,*args,**kwargs)
使用相应的http方法发出请求。args
和kwargs
被传递给各自的requests.<method>
。
- url:url。
- args,kwargs:传递到requests模块(作为requests.get(url,*args,**kwargs))
- 返回带结果的
dict
。更多细节见上面的结果。
要了解这些方法是如何工作的,请查看requests documentation。
结果
方法get
、post
、put
、delete
、head
和options
返回一个dict
对象:
result={'ok':<bool>,'error':<str|None>,'error_type':<str|None>,'response':<requests.response|None>,'headers':<dict>,'status_code':<int|None>,'content_type':<str|None>,'text':<str|None>,'json':<str|None>,}
结果键:
- 好的:如果一切都好的话。始终检查此值。
- 错误:文本错误(当ok为false时)。
- 错误类型:错误类型为的字符串:
- 一般:一般错误。
- 连接:DNS问题、连接被拒绝等。唯一的异常是有自己的代码的超时(见上文)。
- 超时:连接超时。
- http:http错误,如404403500等。
- json:“content type”头表示为json,但内容不是有效的json。
- response:响应对象(与requests模块相同)。您可以使用作为回退来检查此类未处理的信息。
- headers:带有响应头的字典(与requests.response.headers模块相同)。
- 状态码:http状态码的整数(200、404、500等)。
- 内容类型:content type头值。
- 文本:回复内容(如有)。它总是Unicode的。
- json:如果“content type”头指示为json,则为内容的字典。
其他示例
此示例在Facebook Graph API上发出请求。
fromyrequestsimportYRequestsdefget_facebook_me(req):params={'fields':'id,name','access_token':'XXXxxx...'}# Note that the "get" method uses "user-agent" and "extra-header" headers.result=req.get('https://graph.facebook.com/me',params=params,headers={'extra-header':'other-header-value'})ifnotresult['ok']:print(result['error'])return{}data=result['json']print('My name is %(name)s, my Facebook ID is %(id)s'%data)returndata# YRequests only accepts two optional parameters: headers and timeoutreq=YRequests(headers={'user-agent':'BugBot/1.0'},timeout=30)user_dict=get_facebook_me(req)
贡献
如果你发现一个错误,打字错误或错误的编码,你可以贡献给这个项目! 发送请求或联系yoshiodeveloper@gmail.com。