Browsable web APIs for Flask.
| 文件 | 最后提交记录 | 最后更新时间 |
|---|---|---|
| 2 年前 | ||
| 2 年前 | ||
| 2 年前 | ||
| 8 年前 | ||
| 7 年前 | ||
| 8 年前 | ||
| 9 年前 | ||
| 2 年前 | ||
| 2 年前 | ||
| 3 年前 | ||
| 5 年前 | ||
| 2 年前 | ||
| 3 年前 | ||
| 3 年前 |
以下内容由 AI 翻译,如有问题请 点此提交 issue 反馈
Flask API
为Flask提供可浏览的Web API。
状态:此项目处于维护模式。原作者(Tom Christie)已转向开发API Star。维护者(Jace Browning)将继续考虑通过的PR进行发布。
概览
Flask API是Flask的一个直接替换选项,它提供了类似于Django REST框架的可浏览API实现。它可以为你提供正确的内容协商响应和智能请求解析:

安装
需求:
- Python 3.6+
- Flask 1.1.+
使用pip安装:
$ pip install Flask-API
导入并初始化你的应用程序:
from flask_api import FlaskAPI
app = FlaskAPI(__name__)
响应
正常返回任何有效的响应对象,或者返回一个列表或字典。
@app.route('/example/')
def example():
return {'hello': 'world'}
根据客户端'Accept'头进行内容协商选择响应数据的渲染器。如果你从常规客户端发起API请求,这将默认为JSON响应。如果在浏览器中查看API,它将默认为可浏览API的HTML。
请求
通过访问request.data获取解析后的请求数据。默认情况下,它会处理JSON或表单数据。
@app.route('/example/')
def example():
return {'request data': request.data}
示例
以下示例演示了一个简单的用于创建、列出、更新和删除笔记的API。
from flask import request, url_for
from flask_api import FlaskAPI, status, exceptions
app = FlaskAPI(__name__)
notes = {
0: '购物',
1: '编写代码',
2: '漆门',
}
def note_representation(key):
return {
'url': request.host_url.strip('/') + url_for('notes_detail', key=key),
'text': notes[key]
}
@app.route("/", methods=['GET', 'POST'])
def notes_list():
"""
列出或创建笔记。
"""
if request.method == 'POST':
note = str(request.data.get('text', ''))
idx = max(notes.keys()) + 1
notes[idx] = note
return note_representation(idx), status.HTTP_201_CREATED
# request.method == 'GET'
return [note_representation(idx) for idx in sorted(notes.keys())]
@app.route("/<int:key>/", methods=['GET', 'PUT', 'DELETE'])
def notes_detail(key):
"""
获取、更新或删除笔记实例。
"""
if request.method == 'PUT':
note = str(request.data.get('text', ''))
notes[key] = note
return note_representation(key)
elif request.method == 'DELETE':
notes.pop(key, None)
return '', status.HTTP_204_NO_CONTENT
# request.method == 'GET'
if key not in notes:
raise exceptions.NotFound()
return note_representation(key)
if __name__ == "__main__":
app.run(debug=True)
现在运行web应用:
$ python ./example.py
* 运行在 http://127.0.0.1:5000/
* 使用reloader重新启动
现在你可以在新的标签页中与API交互,从命令行执行如下操作:
$ curl -X GET http://127.0.0.1:5000/
[{"url": "http://127.0.0.1:5000/0/", "text": "购物"},
{"url": "http://127.0.0.1:5000/1/", "text": "编写代码"},
{"url": "http://127.0.0.1:5000/2/", "text": "漆门"}]
$ curl -X GET http://127.0.0.1:5000/1/
{"url": "http://127.0.0.1:5000/1/", "text": "编写代码"}
$ curl -X PUT http://127.0.0.1:5000/1/ -d text="Flask API 很棒"
{"url": "http://127.0.0.1:5000/1/", "text": "Flask API 很棒"}
你也可以直接在浏览器中访问http://127.0.0.1:5000/来操作API。然后,你可以导航到不同的笔记,并进行GET、PUT、POST和DELETE的API请求。