类包装器,它将属性调用映射到http api。
attribute_wrapper的Python项目详细描述
属性包装
此包装器将属性调用映射到http api。该包提供了类似的 功能为Tortilla,但它是 用更小更简单的代码实现。
这种简单性使您能够在 需要。
示例
基本访问
fromattribute_wrapperimportHTTPWrapperr=HTTPWrapper("http://kitakitsune.org")data=r.get()
这将下载http://kitakitsune.org的内容并将其作为字符串返回。.get()调用确定用于执行请求的http方法。
特殊字符
python中的点表示法仅限于a-z、a-z、0-9和,这有时可能限制得太多。这就是为什么GenericWrapper具有属性.specials,该属性包含特殊序列到url字符的映射。
目前,.specials表通过以下结构实现:
{"__dot__":".","__slash__":"/","__dash__":"-",}
这意味着包含此子字符串的url将按预期翻译:
r.raw.doctene_knihy__dot__txt.get()
翻译成http://kitakitsune.org/raw/doctene_knihy.txt
此功能可以通过将.specialsdictionary表替换为其他内容来更改,或者使用空白字典来禁用它。
下划线方法
应该使用_方法处理更复杂的路径:
r._("compl?icated/$path/").get()
自动后缀
如果您使用的是api,它期望每个文件以后缀结尾,比如.json或.html,则可以在实例化类时修改.suffix属性或添加suffix参数:
r=HTTPWrapper("http://kitakitsune.org",suffix=".txt")# this will return content of the http://kitakitsune.org, because the suffix# is ignored in root of the pathr.get()# this will return http://kitakitsune.org/raw/doctene_knihy.txtr.raw.doctene_knihy.get()
参数
处理call at last属性的方法接受关键字参数,这些参数作为表单数据发送到服务器:
r.post(something="else")
这将把{"something": "else"}字典作为post数据发送到服务器。
jsonwrapper
作为示例子类,还有JSONWrapper,它将所有参数转换为json并将其作为httpbody发送到服务器。对于某些rest api,这可能特别有用。
子类化
代码实际上非常简单(138行!)而且应该(至少我认为)容易理解。如果您需要一些新的功能,只需对GenericWrapper类进行子类划分,然后重写.download_handler()方法以反映您的需要。
例如,JSONWrapper用几行代码实现:
importjsonclassJSONWrapper(GenericWrapper):defdownload_handler(self,method,url,data):ifdata:data=json.dumps(data)headers={'content-type':'application/json'}resp=requests.request(method,url,headers=headers,data=data)# handle http errorsresp.raise_for_status()returnjson.loads(resp.text)
您的代码
可以用自己的类发送pull请求(不要忘记记录它)。我想使这个包有用,我将很乐意合并您的代码,所以您不需要创建自己的包。
测试
此项目使用py.test进行测试。快跑 py.test来自项目根目录:
bystrousak:/h/D/c0d3z/python/libs/attribute_wrapper,0$ py.test ============================= test session starts ============================== platform linux2 -- Python 2.7.6 -- py-1.4.23 -- pytest-2.6.0 collected 8 items tests/test_wrapper.py ........ =========================== 8 passed in 0.12 seconds ===========================
更改日志
0.2.0
- Added full test coverage.
- Added ValueError exception when calling the root object without method.
- Fixed some typos in comments.
- Added testing section to README.rst.
- Added special underscore method ^{tt17}$ for complicated paths.
0.1.2
- Added handling of HTTP errors.
0.1.1
- Fixed package metadata problems.
0.1.0
- Project created.