编写简单restful api - python

半兽人 发表于: 2019-04-17   最后更新时间: 2023-05-23 11:57:11  
{{totalSubscript}} 订阅, 2,422 游览

先安装flask,之后运行如下代码:

from flask import Flask
app = Flask(__name__)
@app.route('/')  
def hello_world():
    return "hello world"
if __name__=='__main__':
    app.run()

浏览器输入:

127.0.0.1:5000

非常简单的一个web项目,就运行起来了。

完整restful示例:

from flask import Flask, jsonify, request, make_response, abort

app = Flask(__name__)

MY_URL = '/everything/api/v1/'
hello = '今天天气真好呀'
not_hello = '为什么今天天气不好呀'


@app.route(MY_URL + 'tasks/get/', methods=['GET'])
def get_task():
    print(request.args.to_dict())  # request.args请求参数
    return str(request.args.to_dict())


# get
@app.route(MY_URL + 'tasks/get/404/', methods=['GET'])
def get_task_get():
    if not 'abc' in request.args.to_dict():
        abort(404)
    print(request.args.to_dict())
    return str(request.args.to_dict())


# post
@app.route(MY_URL + 'tasks/post/', methods=['POST'])
def post_task():
    print(request.json)
    if not request.json:
        abort(404)
    print('222222222')
    global hello
    hello = hello + str(request.json)
    return hello


# post
@app.route(MY_URL + 'tasks/post/json/', methods=['POST'])
def post_task_json():
    print(request.json)
    if not request.json:
        abort(404)
    print('222222222')
    global hello
    hello = hello + str(request.json)
    print(hello)
    return jsonify(request.json)


# 404处理
@app.errorhandler(404)
def not_found(error):
    return make_response(jsonify({'error': 'Not found'}), 404)


if __name__ == '__main__':
    app.run()

游览器输入:

https://127.0.0.1:5000/everything/api/v1/tasks/get/?abc=hello            
https://127.0.0.1:5000/everything/api/v1/tasks/get/404/?abc=hello
.....
post的就不列了,自己测试
更新于 2023-05-23

查看python更多相关的文章或提一个关于python的问题,也可以与我们一起分享文章