1 Star 0 Fork 0

chilled/official_restful

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
demo04_official_restful.py 2.71 KB
一键复制 编辑 原始数据 按行查看 历史
chilled 提交于 2021-07-11 23:07 . 'init'
# -*- coding: utf-8 -*-
# @Time : 2021/7/11 22:47
# @Author : Dong
# @File : demo04_official_restful.py
from flask import Flask
from flask import request
from flask_restful import Api, Resource
app = Flask(__name__)
api = Api(app)
todos = {}
class TodoSimple(Resource):
# 获取资源
def get(self,todo_id):
return {todo_id:todos[todo_id]}
# 更新资源
def put(self,todo_id):
todos[todo_id] = request.form['data']
return {todo_id:todos[todo_id]}
api.add_resource(TodoSimple,'/<string:todo_id>')
'''
可利用request库在python shell下测试
>>> from requests import put,get
>>> put('http://127.0.0.1:5000/todo2',data={'data':'Remember the bbb'})
<Response [200]>
>>> put('http://127.0.0.1:5000/todo2',data={'data':'Remember the bbb'}).json()
{'todo2': 'Remember the bbb'}
class Todo1(Resource):
def get(self):
# 默认200为正常返回状态码
return {'key':'value'}
class Todo2(Resource):
def get(self):
# 设置201为正常返回状态码
return {'key':'value'},201
class Todo1(Resource):
def get(self):
# 返回多个参数
return {'key':'value'},201,{'k':'v'}
'''
if __name__ == '__main__':
app.run(debug=True)
'''
second post
'''
from flask import Flask
from flask.ext.restful import reqparse, abort, Api, Resource
app = Flask(__name__)
api = Api(app)
TODOS = {
'todo1': {'task': 'build an API'},
'todo2': {'task': '?????'},
'todo3': {'task': 'profit!'},
}
def abort_if_todo_doesnt_exist(todo_id):
if todo_id not in TODOS:
abort(404, message="Todo {} doesn't exist".format(todo_id))
parser = reqparse.RequestParser()
parser.add_argument('task', type=str)
# Todo
# show a single todo item and lets you delete them
class Todo(Resource):
def get(self, todo_id):
abort_if_todo_doesnt_exist(todo_id)
return TODOS[todo_id]
def delete(self, todo_id):
abort_if_todo_doesnt_exist(todo_id)
del TODOS[todo_id]
return '', 204
def put(self, todo_id):
args = parser.parse_args()
task = {'task': args['task']}
TODOS[todo_id] = task
return task, 201
# TodoList
# shows a list of all todos, and lets you POST to add new tasks
class TodoList(Resource):
def get(self):
return TODOS
def post(self):
args = parser.parse_args()
todo_id = int(max(TODOS.keys()).lstrip('todo')) + 1
todo_id = 'todo%i' % todo_id
TODOS[todo_id] = {'task': args['task']}
return TODOS[todo_id], 201
##
## Actually setup the Api resource routing here
##
api.add_resource(TodoList, '/todos')
api.add_resource(Todo, '/todos/<todo_id>')
if __name__ == '__main__':
app.run(debug=True)
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/chilled/official_restful.git
git@gitee.com:chilled/official_restful.git
chilled
official_restful
official_restful
master

搜索帮助