# -*- coding: utf-8 -*-""" package.module
~~~~~~~~~~~~~~
python實現的圖書的乙個restful api.
restful api 一般模式:
get(select):從伺服器取出資源(一項或多項)。
post(create):在伺服器新建乙個資源。
put(update):在伺服器更新資源(客戶端提供改變後的完整資源)。
patch(update):在伺服器更新資源(客戶端提供改變的屬性)。
delete(delete):從伺服器刪除資源。
注意:沒有做儲存持久化,為了實現例子,實際上應該是從資料庫裡面拿,而增冊改查方法也應該呼叫
後端的方法。
:license: gomeops, see license_file for more details.
"""from flask import flask, request, jsonify
import random
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
def page_not_found(e):
return jsonify(dict(code=1, message='method error.')), 405
# get all books
def handle_books():
return jsonify(books)
# get a book
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
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)
return jsonify(code=0, message='success')
# update book
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
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__':
python寫乙個服務 Python寫乙個服務
coding utf 8 import json from urllib.parse import parse qs from wsgiref.server import make server 定義函式,引數是函式的兩個引數,都是python本身定義的,預設就行了。定義檔案請求的型別和當前請求成功...
用python寫乙個蛇形矩陣
蛇形矩陣,如 10 11 12 1 9 16 13 2 8 15 14 3 7 6 5 4從右上角大回環,其實挺簡單,思路想明白了就順了。這樣的矩陣可以看做二維陣列,python對陣列的寫法很麻煩,用numpy生成就簡單多了 myarray np.zeros n,n dtype np.int16 有...
用python寫乙個定時提醒程式
較基礎,適合python新手及對python感興趣的同學閱讀。1。等待 3。重複 1,2兩步。因為我們要在一天內休息多次,迴圈3次好了。開啟python idle 讓我們開始吧!total breaks 3 重複3次 break count 0 while break count total bre...