一个非常基本的问题。我有一个FLASK应用程序,后面有postgresql。此应用程序没有ORM。所有请求都通过SQL psycopg2接口完成。
现在我想从这个应用程序中公开某些API。什么是最好的方法。
1>就像:http://flask-peewee.readthedocs.org/en/latest/rest-api.html 2 - ;或者我可以在没有ORM的情况下做一个。似乎RESTful API的ORM非常有用,但在这种情况下,我必须有一个单独的数据库元素,并将数据从postgres模型复制到ORM。
任何建议都会受到欢迎。
答案 0 :(得分:7)
我有类似的设置Flask + Postgres和PsycoPG2。 我按照以下教程来设计和实现API 我手动处理错误并使用适当的HTTP代码进行响应
http://blog.luisrei.com/articles/rest.html {Design API}
答案 1 :(得分:3)
看起来Flask-Restless是更好的选择。验证,身份验证支持更简单。
答案 2 :(得分:3)
对于非平凡的应用,更好地使用烧瓶优等。 Flask-Restless在某种程度上是有限制的,除了更复杂之外,烧瓶安息并没有真正提供超过烧瓶的优点。 我个人使用烧瓶 - 不安分了一段时间才转向烧瓶 - 优雅。
答案 3 :(得分:2)
现在烧瓶顶部有许多不同的框架。
答案 4 :(得分:0)
我已经为Flask,Postgres和Postman应用程序使用了设置:
代码:
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)
结果: