Python 使用 Flask 创建 RESTful API?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28032278/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Creating a RESTful API using Flask?
提问by u3l
The Flask tutorial site heresays that to create a RESTful API, you would write classes that extend restful.Resource
, then add them to the API by:
此处的 Flask 教程站点说要创建 RESTful API,您将编写扩展 的类restful.Resource
,然后通过以下方式将它们添加到 API:
app = Flask(__name__)
api = restful.Api(app)
class HelloWorld(restful.Resource):
def get(self):
return {'hello': 'world'}
api.add_resource(HelloWorld, '/')
However, I've looked at quite a few tutorials that all just use functions with the @app.route('/path')
decorator that I'm more used to seeing in Flask apps. For example, here, they have:
但是,我已经看过不少教程,这些教程都只是将函数与@app.route('/path')
装饰器结合使用,而我更习惯在 Flask 应用程序中看到这些函数。例如,在这里,他们有:
@app.route('/todo/api/v1.0/tasks', methods=['GET'])
def get_tasks():
return jsonify({'tasks': tasks})
And here:
而在这里:
@app.route('/')
def api_root():
return 'Welcome'
What's the difference between using the restful.Resource
class and just the decorated functions if any? If there are no differences, what should I be doing by convention to create a RESTful API?
restful.Resource
如果有的话,使用类和仅使用装饰函数有什么区别?如果没有差异,我应该按照惯例做什么来创建 RESTful API?
采纳答案by chfw
Short answer:
简短的回答:
restful.Resource is from a Flask-Restfulextension, which is not Flask itself. Miguel's tutorialuses Flaskto write a restful interface.
restful.Resource 来自Flask-Restful扩展,它不是 Flask 本身。Miguel 的教程使用Flask编写了一个宁静的界面。
Long answer:
长答案:
First of all, along with Flask, there are a number of Flask extensions. Although they work together, they are separate packages and are written by individual authors. Flask-Restfulis an extension to Flask.
首先,除了 Flask,还有一些Flask 扩展。尽管它们一起工作,但它们是单独的包,并且是由各个作者编写的。Flask-Restful是Flask的扩展。
Miguel's tutorial explains how you can make a restful api using Flask by itself.
Miguel 的教程解释了如何单独使用 Flask 制作一个宁静的 api。
Flask-Restfulwith the aim to saving some of us from re-inventing the wheel, promises to turn a custom class(or a custom Python data structure) to a restful web service. Flask-RESTX, a fork of Flask-Restful, auto-generates api documentation with swagger UI.
Flask-Restful旨在让我们中的一些人免于重新发明轮子,承诺将自定义类(或自定义 Python 数据结构)转变为一个安静的 Web 服务。Flask-RESTX是Flask-Restful 的一个分支,使用 swagger UI 自动生成 api 文档。
In addition, Flask also documentedthe usage of MethodViewto allow developers to write their own restful APIs. In parallel, Flask-Restlesspromises to turn a SqlAlchemy class into a restful web service.
此外,Flask 还记录了MethodView的用法,以允许开发人员编写自己的RestfulAPI。同时,Flask-Restless承诺将 SqlAlchemy 类变成一个安静的 Web 服务。
An update(18/07/2016), flask-apiturns a function/view into a restful interface and is designed by Tom Christie, the author of django restful framework.
更新(18/07/2016),flask-api将函数/视图变成了一个宁静的界面,由django restful framework的作者 Tom Christie 设计。
There are many roads to Roma.
通往罗马的道路很多。
回答by Sebastian
Using methods instead of classes can quickly become confusing when lots of endpoints are needed. Classes/resource are a better way of separating and decoupling logic. Plus your code becomes much more readable and easier to change/fix
当需要大量端点时,使用方法而不是类会很快变得混乱。类/资源是分离和解耦逻辑的更好方法。此外,您的代码变得更具可读性,更容易更改/修复
Using flask-restful is probably the best way, although I will have some work to do in order to create the blueprint for your api, configuring routing, handling the request parameters, and many things that every normal api needs, that gets quite annoying.
使用flask-restful 可能是最好的方法,尽管我将有一些工作要做,以便为您的api 创建蓝图、配置路由、处理请求参数以及每个普通api 需要的许多事情,这很烦人。
I have built this lightweight framework on top of flask-restful that lets you build restful apis easily without worrying about all the wiring needed, and just focus on defining your api and coding the business logic. You can check it out here: https://github.com/sebastiandev/peach
我在flask-restful 之上构建了这个轻量级框架,它可以让您轻松构建restful api,而无需担心所需的所有接线,只需专注于定义您的api 和编码业务逻辑。你可以在这里查看:https: //github.com/sebastiandev/peach
It is more oriented to NOSQL databases, but thats only because the proxy for the database that comes as default is for mongodb, if you need sql, you can just make a proxy for sqlachemy (or wait until i find time to build it).
它更面向 NOSQL 数据库,但这只是因为默认数据库的代理是用于 mongodb 的,如果您需要 sql,您可以为 sqlachemy 制作一个代理(或等到我找到时间来构建它)。
回答by Hasitha Lakshan
#from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return "Hello, World!"
if __name__ == '__main__':
app.run(debug=True)
回答by Ankush Shrivastava
Setup:
设置:
1:create app.py file.
1:创建app.py文件。
2: pip3 install flask.
2:pip3安装烧瓶。
Code:
代码:
import flask
app=flask.Flask(__name__)
app.config["DEBUG"]=True
@app.route('/',methods=['GET'])
def home():
return "hello"
app.run()
Run:
跑:
python app.py
蟒蛇应用程序.py