把資料庫基礎操作, server環境架設, 自動化相關操作搞定後,就來看後端程式怎麼設計。
swagger: "2.0"
info:
description: "This is a Live Server API."
version: "1.0.0"
title: "Live Server API"
termsOfService: "http://swagger.io/terms/"
contact:
email: "apiteam@swagger.io"
license:
name: "Apache 2.0"
url: "http://www.apache.org/licenses/LICENSE-2.0.html"
host: "xxx.xxx.com"
basePath: "/api/v1"
tags:
- name: "Products"
description: "Everything about your Products"
externalDocs:
description: "Find out more"
url: "http://swagger.io"
schemes:
- "https"
- "http"
paths:
/products:
get:
tags:
- "products"
summary: "Get products info"
description: "Get products info"
operationId: "getProductsInfo"
produces:
- "application/xml"
- "application/json"
parameters:
- name: "cate"
in: "query"
description: "指定哪個分類下的商品"
required: false
type: "string"
responses:
200:
description: "successful operation"
schema:
type: "string"
400:
description: "Invalid status value"
/products/{goodId}:
get:
tags:
- "products"
summary: "Get products info"
description: "Get A product info"
operationId: "getProductInfoByID"
produces:
- "application/xml"
- "application/json"
parameters:
- name: "goodId"
in: "path"
description: "指定哪個商品"
required: true
type: "string"
responses:
200:
description: "successful operation"
schema:
type: "string"
400:
description: "Invalid status value"
app.py -- 後端起始檔案(main)
config.py -- 決定是dev還是prod的設定檔
data.sqlite -- 資料庫實際紀錄的檔案
Pipfile -- for venv(Heroku是用venv)部屬所要(pip)install的library內容
name = "pypi"
url = "https://pypi.org/simple"
verify_ssl = true
[dev-packages]
[packages]
...
Flask = "==1.1.1"
Flask-CLI = "==0.4.0"
Flask-RESTful = "==0.3.7"
Flask-Script = "==2.0.6"
Flask-SQLAlchemy = "==2.4.0"
Jinja2 = "==2.10.1"
MarkupSafe = "==1.1.1"
Pillow = "==6.1.0"
PyPubSub = "==4.0.3"
SQLAlchemy = "==1.3.8"
jwt = "*"
swagger-ui-py = "*"
flask-cors = "*"
psycopg2 = "*"
[requires]
python_version = "3.7"
Procfile -- Heroku要運行python的起始檔案web: gunicorn app:app
from flask import Flask
from flask_httpauth import HTTPBasicAuth
from werkzeug.security import generate_password_hash, check_password_hash
app = Flask(__name__)
auth = HTTPBasicAuth()
users = {
"Ivan": generate_password_hash("Teacher"),
"Tyson": generate_password_hash("Assistant")
}
@auth.verify_password
def verify_password(username, password):
if username in users:
return check_password_hash(users.get(username), password)
return False
@app.route('/')
@auth.login_required
def index():
return "Hello, %s!" % auth.username()
if __name__ == '__main__':
app.run()
輸入正確帳號密碼,成功登入後,就會出現Hello訊息,順利存取api資料Hello, Ivan!
如果輸入帳號密碼有誤,就會出現Unauthorized Access
或者用jwt做token驗證
https://www.infoq.cn/article/identity-authentication-of-architecture-in-micro-service
import jwt
from datetime import datetime
payload = {
'iss': 'xxx.xxx.com',
'sub': goodId,
'aud': 'xxx.xxx.com',
'exp': datetime.utcnow(),
'nbf': datetime.utcnow(),
'iat': datetime.utcnow(),
'jti': goodId,
'hello': 'world',
}
token = jwt.encode(payload, 'secret', algorithm='HS256')
明天接著講其他的案例。