2023-02-21

[Python] Flask Log 配置

import os
import logging
import logging.handlers

from flask import Flask, g, request, json

app = Flask(__name__)


#[ Log 配置 ]#############################################################
 # 用來記錄無法處理的錯誤 (PS: 使用 WSGI 會依附 Apache 的設定,可以不用配置)

# https://docs.python.org/zh-cn/3/library/logging.html
formatter = logging.Formatter("%(asctime)s [%(levelname)s]  %(message)s")

# https://docs.python.org/zh-tw/3/library/logging.handlers.html#timedrotatingfilehandler
handler = logging.handlers.TimedRotatingFileHandler("log/web-api",
    when = "D",
    interval = 1,
    backupCount = 7,
    encoding = "UTF-8",
    delay = False,
    utc = True)
handler.setFormatter(formatter)

app.logger.addHandler(handler)

[Python] Flask 自訂日期的 Json 轉換

import os
import datetime
import time

from flask import Flask, g, request, json
from flask.json import JSONEncoder


class CustomJsonEncoder(JSONEncoder):
    # 針對日期自訂 Json 轉換

    def default(self, obj):
        if isinstance(obj, datetime.date):
            return obj.isoformat().replace('T', ' ')

        return super().default(obj)


app = Flask(__name__)

app.json_encoder = CustomJsonEncoder
app.config['JSON_AS_ASCII'] = False  # 返回結果可以正確顯示中文

[Python] Flask MySQL 連線管理

import os
import mysql.connector as sql

from werkzeug.exceptions import HTTPException, BadRequest
from flask import Flask, g, request, json


app = Flask(__name__)



#[ DB 處裡 ]#############################################################

# https://docsxyz.com/zh-hant/wiki/python/connector-python-connectargs
db_config = {
    'host'      : "localhost",
    'user'      : "XXXX",
    'passwd'    : "XXXX",
    'db'        : 'XXXX',
    'use_pure'  : True,
    'autocommit': True,
    'charset'   : 'utf8',
}


@app.before_request
def before_request():
    # 在 request 前開啟 DB 連線
    # g 是 Flask global 在每個 request 有獨立的 context

    g.cnt = sql.connect(**db_config)
    g.cursor = g.cnt.cursor(dictionary = True)



@app.after_request
def after_request(response):
    # 在 request 後結束 DB 連線

    cursor = g.get('cursor', None)
    if cursor is not None:
        # 當 cursor 還有 row 沒有取出,close 會發生錯誤
        if cursor.with_rows : cursor.fetchall()
        cursor.close()

    cnt = g.get('cnt', None)
    if cnt is not None:
        cnt.close()

    return response

[Python] Flask 筆記

相依套件:
-------------------------------------------------------------------------------
python-3.8.10-amd64.exe

pip install Flask
pip install flask_cors
pip install mysql-connector-python
pip install pycryptodomex
pip install py-linq     # https://viralogic.github.io/py-enumerable/


Apache CGI 配置,用虛擬 Script 指向到 app.cgi
-------------------------------------------------------------------------------


ScriptAlias /web-api  D:/iog-project/web-api/app.cgi

<Directory "D:/iog-project/web-api/">
Options ExecCGI 
AllowOverride all
Require local
</Directory>


-------------------------------------------------------------------------------

# 正常執行
flask run

# 除錯執行  (flask 會提供除錯功能,並將 logger 從 warning 提升到 debug 
export FLASK_ENV=development    # for linux / git  bash 
set FLASK_ENV=development       # for windows cmd
flask run

# 列出設定的路徑
flask routes


其他
-------------------------------------------------------------------------------

因為 web-api 的格式是 Json,所以遵照 JS 的命名風格,欄位名稱開頭小寫第二個字大寫

[Python] Flask 錯誤處裡


from werkzeug.exceptions import HTTPException, BadRequest
from flask import Flask, g, request, json

app = Flask(__name__)


#[ 錯誤處裡 ]#############################################################
@app.errorhandler(Exception)
def handle_exception(e):
    if isinstance(e, HTTPException): return e  # 讓 HTTPException 交由下一個處理

    app.logger.exception("Internal Server Error.")  # log 錯誤訊息
    if app.debug : return e

    return json.jsonify({'message': 'Internal Server Error.'}), 500


@app.errorhandler(HTTPException)
def handle_exception(e):
    response = e.get_response()
    return json.jsonify({'message': e.description}), e.code