V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
prasanta
V2EX  ›  Python

Toapi2.0 发布!优雅地让网站提供 API 接口!

  •  
  •   prasanta · 2018-03-04 20:34:07 +08:00 · 1240 次点击
    这是一个创建于 2245 天前的主题,其中的信息可能已经有所发展或是发生改变。

    Toapi

    Build Coverage Python Version License

    简介

    Toapi 是一个能够将任何 web 网站转化为 api 服务的库。当前版本为 2.0 版,完全重新设计了用法,使得代码更加优雅,更加 pythonic。

    Get Started

    Installation

    $ pip install toapi
    $ toapi -v
    toapi, version 2.0.0
    

    用法

    创建 app.py ,复制下面的代码:

    from flask import request
    from htmlparsing import Attr, Text
    from toapi import Api, Item
    
    api = Api()
    
    
    @api.site('https://news.ycombinator.com')
    @api.list('.athing')
    @api.route('/posts?page={page}', '/news?p={page}')
    @api.route('/posts', '/news?p=1')
    class Post(Item):
        url = Attr('.storylink', 'href')
        title = Text('.storylink')
    
    
    @api.site('https://news.ycombinator.com')
    @api.route('/posts?page={page}', '/news?p={page}')
    @api.route('/posts', '/news?p=1')
    class Page(Item):
        next_page = Attr('.morelink', 'href')
    
    
    api.run(debug=True, host='0.0.0.0', port=5000)
    

    运行 python app.py

    打开浏览器访问 http://127.0.0.1:5000/posts?page=1

    你讲获得类似下面的结果:

    {
      "Page": {
        "next_page": "http://127.0.0.1:5000/posts?page=2"
      }, 
      "Post": [
        {
          "title": "Mathematicians Crack the Cursed Curve", 
          "url": "https://www.quantamagazine.org/mathematicians-crack-the-cursed-curve-20171207/"
        }, 
        {
          "title": "Stuffing a Tesla Drivetrain into a 1981 Honda Accord", 
          "url": "https://jalopnik.com/this-glorious-madman-stuffed-a-p85-tesla-drivetrain-int-1823461909"
        }
      ]
    }
    

    直接看上面的案例就能很容易理解用法. 目前版本完全开源。

    Github: https://github.com/gaojiuli/toapi

    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2768 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 02:36 · PVG 10:36 · LAX 19:36 · JFK 22:36
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.