推荐学习书目
› 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
BeanYoung
V2EX  ›  Python

如何用 flask 优雅的实现 restful api

  •  
  •   BeanYoung · Jan 27, 2015 · 9259 views
    This topic created in 4310 days ago, the information mentioned may be changed or developed.

    api 这么来设计,访问 /users.json 返回 json 格式数据,访问 /users.csv 返回 csv 格式数据。

    目前想到这么几个实现方法:

    1. nginx 匹配 url,将 url 后缀去掉,对于不同的 url 后缀,添加对应的 Accept header,flask 里根据请求headers 里 Accept 的值返回对应格式的数据。flask-restful 这个库可以根据 Accept header 来返回对应的数据格式。
    2. 给一个函数添加路由
    @app.route('/users<data_type>')
    def users(data_type='.json'):
        pass
    

    第一种依赖外部代理服务器,第二种还没想好怎么和 flask-restful 一起用。

    有没有更优雅的方式来实现类似的需求?

    6 replies  •  2015-01-28 09:22:47 +08:00
    gevin
    gevin
    Jan 27, 2015
    1
    >>访问 /users.json 返回 json 格式数据,访问 /users.csv 返回 csv 格式数据

    这不是严格意义上的RESTful API
    9hills
    9hills
    Jan 27, 2015
    2
    你的需求就不是restful api,标准做法是做到Accept中,而且不是你的Nginx来做,而是你的客户端来做
    9hills
    9hills
    Jan 27, 2015
    3
    不过你的客户端说老子就是不遵守Restful,那么你也没必要非要在Server搞restful。。。
    zhangxiao
    zhangxiao
    Jan 28, 2015
    4
    restful 就像是共产主义,大部分只能做到社会主义初级阶段
    elvis_w
    elvis_w
    Jan 28, 2015❤️1
    5
    这问题浓浓的知乎(逼乎)风格
    flask不是有专门的扩展吗?
    https://flask-restful.readthedocs.org/en/0.3.1/
    够优雅吧
    elvis_w
    elvis_w
    Jan 28, 2015
    6
    @elvis_w 没注意看帖子内容,你这严格说来根本不是RESTful啊,不同资源应该在HTTP头中请求才是RESTful啊
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2310 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 13:20 · PVG 21:20 · LAX 05:20 · JFK 08:20
    ♥ Do have faith in what you're doing.