1. 程式人生 > >python編寫簡單RESTful API

python編寫簡單RESTful API

初來乍到,菜鳥一枚。。。

1.安裝python 3.5.4 下載地址 *注意環境變數哦~~~

2.使用包管理工具安裝flask (此處沒有安裝 virtualenv,這個主要是用來做直譯器環境隔離的,避免同一機器上的多個python或者多個python的庫依賴)
安裝flask

3.JetBrains PyCharm 編寫如下程式碼

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

出現以下效果:
效果展示

RESTful API 練習

get請求

程式碼如下

from flask import Flask,jsonify,request

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()) if __name__ == '__main__': app.run()

展示效果

post請求

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

app = Flask(__name__)

MY_URL = '/everything/api/v1/'
hello='今天天氣真好呀'
not_hello = '為什麼今天天氣不好呀'

#get
@app.route(MY_URL + 'tasks/get/',methods=['GET'])
def get_task(): 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 #404處理 @app.errorhandler(404) def not_found(error): return make_response(jsonify({'error':'Not found'}),404) if __name__ == '__main__': app.run()
from flask import Flask,jsonify,request,make_response,abort

app = Flask(__name__)

MY_URL = '/everything/api/v1/'
hello='今天天氣真好呀'
not_hello = '為什麼今天天氣不好呀'

#get
@app.route(MY_URL + 'tasks/get/',methods=['GET'])
def get_task():
    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)
    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()

效果展示