【问题标题】:building REST API in FLASK在 FLASK 中构建 REST API
【发布时间】:2013-05-03 08:04:57
【问题描述】:

一个非常基本的问题。我有一个 FLASK 应用程序,它背后有 postgresql。此应用程序没有 ORM。所有请求都通过 SQL psycopg2 接口完成。

现在我想从这个应用程序中公开某些 API。最好的方法是什么。

1> 就像:http://flask-peewee.readthedocs.org/en/latest/rest-api.html 2> 或者我可以在没有 ORM 的情况下做一个。似乎 RESTful API 的 ORM 非常有用,但在这种情况下,我必须有一个单独的数据库元素并将数据从 postgres 模型复制到 ORM。

欢迎提出任何建议。

【问题讨论】:

标签: rest flask


【解决方案1】:

我有类似的设置 Flask + Postgres 和 PsycoPG2。 我按照以下教程设计和实现 API 我手动处理错误并使用适当的 HTTP 代码进行响应

http://blog.luisrei.com/articles/rest.html { 设计 API}

http://blog.luisrei.com/articles/flaskrest.html { 实施 API}

【讨论】:

    【解决方案2】:

    看起来Flask-Restless 是一个更好的选择。有了它,验证、身份验证支持就简单多了。

    【讨论】:

      【解决方案3】:

      对于非平凡的应用程序,最好使用flask-classy。 Flask-Restless 有一定的限制,Flask-restful 除了更复杂之外,并没有真正超越flask-classy。 我个人使用了flask-restless一段时间,然后才转向flask-classy。

      【讨论】:

      • 不幸的是,Flask-classy 不再维护。
      【解决方案4】:

      flask 现在有很多不同的框架。

      【讨论】:

        【解决方案5】:

        FLASK 和 Postman 应用中的 REST API:

        代码:

        from flask_sqlalchemy import SQLAlchemy
        from flask import Flask,render_template,request,jsonify,json
        import psycopg2
        import psycopg2.extras
        
        
        app = Flask(__name__)
        db = SQLAlchemy()
        
        conn = psycopg2.connect("postgresql://postgres:postgres@localhost:5432/country")
        cr = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
            
        
        @app.route('/', methods=['GET'])
        def test():
        
            return jsonify({
                'message': 'Welcome'
            })
        
        
        @app.errorhandler(404)
        def page_not_found(e):
            return "<h1>404</h1><p>The resource could not be found.</p>", 404
        
        
        ##### Countries ######
        @app.route('/country/all', methods=['GET'])
        def country():
        
           cr.execute('select * from country')
           country = cr.fetchall()
           countries = []
           for row in country:
               countries.append(dict(row))
           return jsonify(countries)
        
        if __name__ == '__main__':
            app.run(debug=True, port=8080)
        

        结果:

        **

        【讨论】:

          猜你喜欢
          • 2016-01-28
          • 1970-01-01
          • 2020-11-03
          • 1970-01-01
          • 1970-01-01
          • 2015-12-19
          • 2017-05-09
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多