python flask and postman

markdown #說明 這個也是基本的網頁架設,只是使用postman 去測試,其中get 和 post 是最常見的方法。 #操作流程 ##Code ``` from flask import Flask from flask_restful import Api from flask_restful import Resource class PrintHelloWorld(Resource): def get(self): return { 'message': 'Hello Wrold!' }, 200 app = Flask(__name__) api = Api(app) api.add_resource(PrintHelloWorld, "/print_hello_world/") if __name__ == "__main__": app.run() ``` ##Demo
##app.py ``` from flask import Flask,jsonify,request,render_template app = Flask(__name__) stores = [{ 'name': 'My Store', 'items': [{'name':'my item', 'price': 15.99 }] }] @app.route('/') def home(): return render_template('index.html') #post /store data: {name :} @app.route('/store' , methods=['POST']) def create_store(): request_data = request.get_json() new_store = { 'name':request_data['name'], 'items':[] } stores.append(new_store) return jsonify(new_store) #pass #get /store/ data: {name :} @app.route('/store/') def get_store(name): for store in stores: if store['name'] == name: return jsonify(store) return jsonify ({'message': 'store not found'}) #pass #get /store @app.route('/store') def get_stores(): return jsonify({'stores': stores}) #pass #post /store/ data: {name :} @app.route('/store//item' , methods=['POST']) def create_item_in_store(name): request_data = request.get_json() for store in stores: if store['name'] == name: new_item = { 'name': request_data['name'], 'price': request_data['price'] } store['items'].append(new_item) return jsonify(new_item) return jsonify ({'message' :'store not found'}) #pass #get /store//item data: {name :} @app.route('/store//item') def get_item_in_store(name): for store in stores: if store['name'] == name: return jsonify( {'items':store['items'] } ) return jsonify ({'message':'store not found'}) #pass app.run(port=5000) ``` ##index.html ```
Hello, world!
``` ##DEMO
##REF - Python flask error https://zhidao.baidu.com/question/1820085531739250548.html - code https://github.com/schoolofcode-me/rest-api-sections/tree/master/section3 - https://medium.com/%E4%B8%80%E5%80%8B%E4%BA%BA%E7%9A%84%E6%96%87%E8%97%9D%E5%BE%A9%E8%88%88/python-flask-rest-api%E7%AD%86%E8%A8%98-869c3d2fee3 - https://blog.taiker.space/python-shi-yong-python-he-flask-she-ji-restful-api/

留言