代码拉取完成,页面将自动刷新
# -*- 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)
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。