2023-02-21 10:33

[Python] Flask Log 配置

  1. import os 
  2. import logging 
  3. import logging.handlers 
  4.  
  5. from flask import Flask, g, request, json 
  6.  
  7. app = Flask(__name__) 
  8.  
  9.  
  10. #[ Log 配置 ]############################################################# 
  11. # 用來記錄無法處理的錯誤 (PS: 使用 WSGI 會依附 Apache 的設定,可以不用配置) 
  12.  
  13. # https://docs.python.org/zh-cn/3/library/logging.html 
  14. formatter = logging.Formatter("%(asctime)s [%(levelname)s]  %(message)s") 
  15.  
  16. # https://docs.python.org/zh-tw/3/library/logging.handlers.html#timedrotatingfilehandler 
  17. handler = logging.handlers.TimedRotatingFileHandler("log/web-api", 
  18.    when = "D", 
  19.    interval = 1, 
  20.    backupCount = 7, 
  21.    encoding = "UTF-8", 
  22.    delay = False, 
  23.    utc = True) 
  24. handler.setFormatter(formatter) 
  25.  
  26. app.logger.addHandler(handler) 
2023-02-21 10:13

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

  1. import os 
  2. import datetime 
  3. import time 
  4.  
  5. from flask import Flask, g, request, json 
  6. from flask.json import JSONEncoder 
  7.  
  8.  
  9. class CustomJsonEncoder(JSONEncoder): 
  10.    # 針對日期自訂 Json 轉換 
  11.  
  12.    def default(self, obj): 
  13.        if isinstance(obj, datetime.date): 
  14.            return obj.isoformat().replace('T', ' ') 
  15.  
  16.        return super().default(obj) 
  17.  
  18.  
  19. app = Flask(__name__) 
  20.  
  21. app.json_encoder = CustomJsonEncoder 
  22. app.config['JSON_AS_ASCII'] = False  # 返回結果可以正確顯示中文 
2023-02-21 10:05

[Python] Flask MySQL 連線管理

  1. import os 
  2. import mysql.connector as sql 
  3.  
  4. from werkzeug.exceptions import HTTPException, BadRequest 
  5. from flask import Flask, g, request, json 
  6.  
  7.  
  8. app = Flask(__name__) 
  9.  
  10.  
  11.  
  12. #[ DB 處裡 ]############################################################# 
  13.  
  14. # https://docsxyz.com/zh-hant/wiki/python/connector-python-connectargs 
  15. db_config = { 
  16.    'host'      : "localhost", 
  17.    'user'      : "XXXX", 
  18.    'passwd'    : "XXXX", 
  19.    'db'        : 'XXXX', 
  20.    'use_pure'  : True, 
  21.    'autocommit': True, 
  22.    'charset'   : 'utf8', 
  23. } 
  24.  
  25.  
  26. @app.before_request 
  27. def before_request(): 
  28.    # 在 request 前開啟 DB 連線 
  29.    # g 是 Flask global 在每個 request 有獨立的 context 
  30.  
  31.    g.cnt = sql.connect(**db_config) 
  32.    g.cursor = g.cnt.cursor(dictionary = True) 
  33.  
  34.  
  35.  
  36. @app.after_request 
  37. def after_request(response): 
  38.    # 在 request 後結束 DB 連線 
  39.  
  40.    cursor = g.get('cursor', None) 
  41.    if cursor is not None: 
  42.        # 當 cursor 還有 row 沒有取出,close 會發生錯誤 
  43.        if cursor.with_rows : cursor.fetchall() 
  44.        cursor.close() 
  45.  
  46.    cnt = g.get('cnt', None) 
  47.    if cnt is not None: 
  48.        cnt.close() 
  49.  
  50.    return response 
2023-02-21 09:55

[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 的命名風格,欄位名稱開頭小寫第二個字大寫

2023-02-21 09:53

[Python] Flask 錯誤處裡

  1. from werkzeug.exceptions import HTTPException, BadRequest 
  2. from flask import Flask, g, request, json 
  3.  
  4. app = Flask(__name__) 
  5.  
  6.  
  7. #[ 錯誤處裡 ]############################################################# 
  8. @app.errorhandler(Exception) 
  9. def handle_exception(e): 
  10.    if isinstance(e, HTTPException): return e  # 讓 HTTPException 交由下一個處理 
  11.  
  12.    app.logger.exception("Internal Server Error.")  # log 錯誤訊息 
  13.    if app.debug : return e 
  14.  
  15.    return json.jsonify({'message': 'Internal Server Error.'}), 500 
  16.  
  17.  
  18. @app.errorhandler(HTTPException) 
  19. def handle_exception(e): 
  20.    response = e.get_response() 
  21.    return json.jsonify({'message': e.description}), e.code