flask实现关于json的get/post/put/delete方法
程序员文章站
2022-07-12 19:03:38
...
方法1
from flask import Flask
from flask.ext.restful import Api, Resource
app = Flask(__name__)
api = Api(app)
class TaskListAPI(Resource):
def get(self):
pass
def post(self):
pass
class TaskAPI(Resource):
def get(self, id):
pass
def put(self, id):
pass
def delete(self, id):
pass
api.add_resource(TaskListAPI, '/todo/api/v1.0/tasks', endpoint = 'tasks')
api.add_resource(TaskAPI, '/todo/api/v1.0/tasks/<int:id>', endpoint = 'task')
方法2&Json
import json
from flask import Flask
from flask import request
from flask import redirect
from flask import jsonify
app = Flask(__name__)
@app.route('/' , methods=['GET', 'POST'])
def index():
if request.method == 'POST':
a = request.get_data()
dict1 = json.loads(a)
return json.dumps(dict1["data"])
else:
return '<h1>只接受post请求!</h1>'
@app.route('/user/<name>')
def user(name):
return'<h1>hello, %s</h1>' % name
if __name__ =='__main__':
app.run(debug=True)