iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 25
2

把資料庫基礎操作, server環境架設, 自動化相關操作搞定後,就來看後端程式怎麼設計。


  1. 後端程式架構設計
    https://ithelp.ithome.com.tw/upload/images/20191010/20005722lj4fVGxNZ3.png
    主要分Controllers / Models兩個folder
    Controllers -- 決定api router以及要存取哪個資料表,丟哪些資料到前端。
    Models -- 就是每個資料表的ORM表示。
    api.yml -- swagger顯示的檔案 for swagger_ui這套library
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


  1. 安全性相關設定研究
    使用Flask-HTTPAuth
    https://flask-httpauth.readthedocs.io/en/latest/
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()

https://ithelp.ithome.com.tw/upload/images/20191010/20005722k15cMBcVmd.png

輸入正確帳號密碼,成功登入後,就會出現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')

  1. 了解後端設計模式,比如最近很火紅的DDD(Domain-Driven Design)

    該架構分成了Applications、Domain和Infrastructure三層。
    https://ithelp.ithome.com.tw/upload/images/20191010/20005722DWMhJO20rb.png
    網路上有很多DDD的討論,以及用python寫的sample: 連結

明天接著講其他的案例。


上一篇
[破] 心存全端,徐圖進取: 後端技術突破(一)
下一篇
[破] 以戰止戰方能兵不血刃: 軟體開發技術突破
系列文
30天全端手把手學徒計畫-前後端整合之旅33
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言