用python寫一個restful API

來源:互聯網
上載者:User

標籤:python   restful   

# -*- coding: utf-8 -*-# 煮酒品茶""" package.module ~~~~~~~~~~~~~~ python實現的圖書的一個restful api. 參考restful設計指南 URL: http://www.ruanyifeng.com/blog/2014/05/restful_api.html restful api 一般模式: GET(SELECT):從伺服器取出資源(一項或多項)。 POST(CREATE):在伺服器建立一個資源。 PUT(UPDATE):在伺服器更新資源(用戶端提供改變後的完整資源)。 PATCH(UPDATE):在伺服器更新資源(用戶端提供改變的屬性)。 DELETE(DELETE):從伺服器刪除資源。 注意: 沒有做儲存持久化,為了實現例子,實際上應該是從資料庫裡面拿,而增冊改查方法也應該調用 後端的方法。 :copyright: (c) YEAR by zwhset. :license: GOMEOPS, see LICENSE_FILE for more details."""from flask import Flask, request, jsonifyimport randomapp = Flask(__name__)books = [ dict(id=1, isdn=random.randrange(1, 1000), title=‘a python book‘, author=dict( name=‘l0set‘, city=‘hunan‘ )), dict(id=2, isdn=random.randrange(1, 1000), title=‘a golang book‘, author=dict( name=‘zwhset‘, city=‘beijing‘ ))]# error action@app.errorhandler(405)def page_not_found(e): return jsonify(dict(code=1, message=‘method error.‘)), 405# get all books@app.route(‘/api/books‘)def handle_books(): return jsonify(books)# get a book@app.route(‘/api/book/<int:id>‘)def handle_book(id): for i, book in enumerate(books): if book[‘id‘] == id: return jsonify(book) return jsonify(dict(code=2, message="don‘t fund the book"))# create a new book@app.route(‘/api/book‘, methods=[‘POST‘])def create_book(): book = request.json # check params if ((not ‘title‘ in book and ‘author‘ in book) or (not isinstance(book[‘author‘], dict)) or (not ‘name‘ in book[‘author‘] and ‘city‘ in book[‘author‘])): return jsonify(code=3, message=‘json author error.‘) # create a new book book[‘id‘] = random.randrange(1, 10000) book[‘isdn‘] = random.randrange(1, 10000) books.append(book) return jsonify(code=0, message=‘success‘)# update book@app.route(‘/api/book/<int:id>‘, methods=[‘PUT‘])def update_book(id): book = request.json # check params if ((not ‘title‘ in book and ‘author‘ in book) or (not isinstance(book[‘author‘], dict)) or (not ‘name‘ in book[‘author‘] and ‘city‘ in book[‘author‘])): return jsonify(code=3, message=‘json author error.‘) # 安全考慮,只拿要的資料,其它的不要 book_data = dict(title=book[‘title‘], author=dict( name=book[‘author‘][‘name‘], city=book[‘author‘][‘city‘] )) for i, book in enumerate(books): # check id if book[‘id‘] == id: books[i].update(book_data) # 進行更新操作 return jsonify(code=0, message=‘success‘) return jsonify(dict(code=2, message="don‘t fund the book"))# delete a book@app.route(‘/api/book/<int:id>‘, methods=[‘DELETE‘])def delete_book(id): for i, book in enumerate(books): # check id if book[‘id‘] == id: del books[i] # 刪除書 return jsonify(code=0, message=‘success‘) return jsonify(dict(code=2, message="don‘t fund the book"))if __name__ == ‘__main__‘: app.run(host=‘0.0.0.0‘, port=8000)

用python寫一個restful API

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.