Python 学习记录

1.日志logging模块使用

import logging
from logging.config import dictConfig

#保证日志文件夹存在
dictConfig({
    "version": 1,
    "formatters": {
       "simple": {
           "format": "[%(asctime)s] [%(pathname)s:%(lineno)d] [%(levelname)s] %(message)s"
       }
    },
    "handlers": {
        "console": {
            "class": "logging.StreamHandler",
            "level": "DEBUG",
            "formatter": "simple",
            "stream": "ext://sys.stdout"
        },
        "info_file_handler": {
            "class": "logging.handlers.RotatingFileHandler",
            "level": "INFO",
            "formatter": "simple",
            "filename": "log/info.log",
            "maxBytes": 1024*1024*10,
            "backupCount": 5,
            "encoding": "utf8"
        },
        "error_file_handler": {
            "class": "logging.handlers.RotatingFileHandler",
            "level": "ERROR",
            "formatter": "simple",
            "filename": "log/error.log",
            "maxBytes": 1024*1024*10,
            "backupCount": 5,
            "encoding": "utf8"
        }
    },
    "root": {
        "level": 'INFO',
        "handlers": ["console", "info_file_handler", "error_file_handler"]
    }
})

if __name__ == '__main__':
    print('PyCharm')

    logging.info("hello info")
    logging.warning("hello warning")
    logging.error("hello error")

需要再当前目录下创建log文件夹,运行程序就会再文件夹下生产两个log文件

2. Web 应用框架Flask模块使用

get请求

from flask import Flask
from flask import request
from python_logging import dictConfig


# Flask框架设置
# static_folder是用来指代存放static文件的目录
# static_url_path是我们再url里输入地址用来指向static文件的
app = Flask(__name__, static_folder='', static_url_path='')

@app.route('/analyse', methods=['get'])
def analyse():
    data = request.args.get("text")
    print(data)
    app.logger.info(data)
    return data

if __name__=='__main__':
    app.run()

测试方法:

#输入 直接用网页输入: http://127.0.0.1:5000/analyse?text="2020年3月"
#输出 "2020年3月"

post请求

from flask import Flask, jsonify, request
from flask_socketio import SocketIO
from python_logging import dictConfig
import json

app = Flask(__name__, static_folder='', static_url_path='')

@app.route('/analyse', methods=['post'])
def analyse():
    #application/x-www-form-urlencoded
    print("content_type:", request.headers.get("content_type"))
    data = request.form.to_dict()
    print('form:', data)
    text = data.get("text")
    print(text)
    app.logger.info(text)

    #application/json
    print("content_type:", request.headers.get("content_type"))
    data = request.get_data().decode("utf-8")
    print("data : ", data)
    json_data = json.dumps(data, ensure_ascii=False) #参数 ensure_ascii=False 禁用ascii编码,按utf-8编码
    print("json_data : ", json_data)
    j_data = json.loads(data)
    text = j_data.get("text")
    print("text: ", text)

    for item in j_data.get("num"):
        print("first: ", item.get("first"))
        print("second: ", item.get("second"))

    app.logger.info(text)
    return jsonify({'code': 200})


if __name__=='__main__':
    app.run(host="127.0.0.1", port=5000)

body的两种模式,接收判别type,解读方式不同。

postman模拟发送数据:

body为application/x-www-form-urlencoded模式时:

Python 学习记录_第1张图片

 body为application/json模式时:

Python 学习记录_第2张图片

 打印信息:以 body为application/json模式时为例

Python 学习记录_第3张图片

在应用中Flask直接打印会干扰日志查看。所以换种方式,使用 flask_socketio模块

post程序修改为

from flask import Flask, jsonify, request
from flask_socketio import SocketIO
from python_logging import dictConfig
import json

app = Flask(__name__, static_folder='', static_url_path='')

@app.route('/analyse', methods=['post'])
def analyse():
    #application/x-www-form-urlencoded
    print("content_type:", request.headers.get("content_type"))
    data = request.form.to_dict()
    print('form:', data)
    text = data.get("text")
    print(text)
    app.logger.info(text)

    #application/json
    print("content_type:", request.headers.get("content_type"))
    data = request.get_data().decode("utf-8")
    print("data : ", data)
    json_data = json.dumps(data, ensure_ascii=False) #参数 ensure_ascii=False 禁用ascii编码,按utf-8编码
    print("json_data : ", json_data)
    j_data = json.loads(data)
    text = j_data.get("text")
    print("text: ", text)

    for item in j_data.get("num"):
        print("first: ", item.get("first"))
        print("second: ", item.get("second"))

    app.logger.info(text)
    return jsonify({'code': 200})


if __name__=='__main__':
    socket_io = SocketIO(app, cors_allowed_origins='*', async_mode='eventlet', engineio_logger=False)
    socket_io.run(app, host="127.0.0.1", port=5000)

打印信息: 同样以body为application/json模式时为例

Python 学习记录_第4张图片

 这样看着简洁很多,不会有那么多干扰项

你可能感兴趣的:(Python,python,flask)