python3 flask练习笔记-数据库版-连接池版-API

普通mysql数据库版

from flask import Flask,request,jsonify
#import request 需要flask里面的request  不然会报 module 'request' has no attribute 'args'
import pymysql
import hashlib


app = Flask(__name__)
def fetch_one(sql,params):
    conn=pymysql.connect(host='192.168.9.156',port=3306,user='root',passwd='123456',db='test_db',charset='utf8')
    cursor=conn.cursor()
    #cursor.execute("select * from test_user where token=%s",[token, ])
    cursor.execute(sql,params)
    result = cursor.fetchone()
    cursor.close()
    conn.close()
    return result

@app.route('/bili',methods=['GET','POST'])
def bili():
    "访问post   http://192.168.9.148/bili?token=fec22f96-2783-414o-06e3-991d357c96e6"
    # 1.token是否为空
    token = request.args.get("token")
    print('获取的token:',token)
    if not token:
        return jsonify({"status":False,'error':"认证失败1"})
    #token是否合法,连接mysql执行sql命令
    result =fetch_one("select * from test_user where token=%s",[token, ])



    if not result:
        return jsonify({"status": False, 'error': "认证失败2"})

    ordered_string = request.json.get("ordered_string")
    print('ordered_string=======',ordered_string)
    if not ordered_string:
        return jsonify({"status":False,'error':"认证失败3"})


    #调用核心算法,生成sign
    encrypt_string = ordered_string + "568c52ccd288fed845859ed18bffd973"
    print('encrypt_string:',encrypt_string)

    #encrypt_string.encode() 将字符串 123fnsfdsfdfdfdcdscfesdcdscdcdcdcddddddddddddscddswerewrfewfedcdcsdcdabc568c52ccd288fed845859ed18bffd973
    # 转换为字节 b'123fnsfdsfdfdfdcdscfesdcdscdcdcdcddddddddddddscddswerewrfewfedcdcsdcdabc568c52ccd288fed845859ed18bffd973'
    obj = hashlib.md5(encrypt_string.encode('utf-8'))
    print('字节=======',encrypt_string.encode('utf-8'))
    print('obj=',obj)
    '''
    encrypt_string.encode()  将字符串 转换 为字节
    hashlib.md5():创建一个 MD5 哈希对象  
    .hexdigest():获取哈希对象的十六进制表示
    '''
    sign = obj.hexdigest()
    print('sign=',sign)

    return jsonify({"status": True, 'data': sign})

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=80)

mysql 数据库连接池版本

from flask import Flask,request,jsonify
#import request 需要flask里面的request  不然会报 module 'request' has no attribute 'args'
import pymysql
import hashlib
from dbutils.pooled_db import PooledDB


app = Flask(__name__)
#创建一个mysql连接池
POOL = PooledDB(
    creator=pymysql,# 使用链接数据库的模块
    maxconnections=10,#连接池允许的最大连接数,0和None表示不限制连接数
    mincached=2,#初始化时,链接池中至少创建的空闲的链接,0表示不创建
    maxcached=5,#链接池中最多闲置的链接,0和None不限制
    blocking=True, #连接池中如果没有可用连接后,是否阻塞等待。True,等待;False,不等待然后报错
    setsession=["SET time_zone = 'Asia/Shanghai'"],  # 开始会话前执行的命令列表。如: ["set datestxle to ...","set time zone..."]
    ping=0,
    host='192.168.9.156',port=3306,user='root',passwd='123456',db='test_db',charset='utf8'
)

def fetch_one(sql,params):
    #conn=pymysql.connect(host='192.168.9.156',port=3306,user='root',passwd='123456',db='test_db',charset='utf8')
    #通过连接池连接数据库

    conn = POOL.connection()
    cursor=conn.cursor()
    #cursor.execute("select * from test_user where token=%s",[token, ])
    cursor.execute(sql,params)
    result = cursor.fetchone()
    cursor.close()
    # 没有连接池的情况下是关闭mysql连接;
    #有连接池的情况下表示使用完毕后将  连接  交还给连接池,以供后续连接使用
    conn.close()
    return result

@app.route('/bili',methods=['GET','POST'])
def bili():
    "访问post   http://192.168.9.148/bili?token=fec22f96-2783-414o-06e3-991d357c96e6"
    # 1.token是否为空
    token = request.args.get("token")
    print('获取的token:',token)
    if not token:
        return jsonify({"status":False,'error':"认证失败1"})
    #token是否合法,连接mysql执行sql命令
    result =fetch_one("select * from test_user where token=%s",[token, ])



    if not result:
        return jsonify({"status": False, 'error': "认证失败2"})

    ordered_string = request.json.get("ordered_string")
    print('ordered_string=======',ordered_string)
    if not ordered_string:
        return jsonify({"status":False,'error':"认证失败3"})


    #调用核心算法,生成sign
    encrypt_string = ordered_string + "568c52ccd288fed845859ed18bffd973"
    print('encrypt_string:',encrypt_string)

    #encrypt_string.encode() 将字符串 123fnsfdsfdfdfdcdscfesdcdscdcdcdcddddddddddddscddswerewrfewfedcdcsdcdabc568c52ccd288fed845859ed18bffd973
    # 转换为字节 b'123fnsfdsfdfdfdcdscfesdcdscdcdcdcddddddddddddscddswerewrfewfedcdcsdcdabc568c52ccd288fed845859ed18bffd973'
    obj = hashlib.md5(encrypt_string.encode('utf-8'))
    print('字节=======',encrypt_string.encode('utf-8'))
    print('obj=',obj)
    '''
    encrypt_string.encode()  将字符串 转换 为字节
    hashlib.md5():创建一个 MD5 哈希对象  
    .hexdigest():获取哈希对象的十六进制表示
    '''
    sign = obj.hexdigest()
    print('sign=',sign)

    return jsonify({"status": True, 'data': sign})

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=80)

work任务队列版本

带任务队列版本

import uuid

from flask import Flask,request,jsonify
#import request 需要flask里面的request  不然会报 module 'request' has no attribute 'args'
import pymysql
import hashlib
from dbutils.pooled_db import PooledDB
import redis
import json


app = Flask(__name__)
#创建一个mysql连接池
POOL = PooledDB(
    creator=pymysql,# 使用链接数据库的模块
    maxconnections=10,#连接池允许的最大连接数,0和None表示不限制连接数
    mincached=2,#初始化时,链接池中至少创建的空闲的链接,0表示不创建
    maxcached=5,#链接池中最多闲置的链接,0和None不限制
    blocking=True, #连接池中如果没有可用连接后,是否阻塞等待。True,等待;False,不等待然后报错
    setsession=["SET time_zone = 'Asia/Shanghai'"],  # 开始会话前执行的命令列表。如: ["set datestxle to ...","set time zone..."]
    ping=0,
    host='192.168.9.156',port=3306,user='root',passwd='123456',db='test_db',charset='utf8'

)

#redis连接池
REDIS_POOL = redis.ConnectionPool(host= '192.168.9.156',password='12345600', port= 6379, encoding="utf-8",max_connections=100)
def fetch_one(sql,params):
    #conn=pymysql.connect(host='192.168.9.156',port=3306,user='root',passwd='123456',db='test_db',charset='utf8')
    #通过连接池连接数据库

    conn = POOL.connection()
    cursor=conn.cursor()
    #cursor.execute("select * from test_user where token=%s",[token, ])
    cursor.execute(sql,params)
    result = cursor.fetchone()
    cursor.close()
    # 没有连接池的情况下是关闭mysql连接;
    #有连接池的情况下表示使用完毕后将  连接  交还给连接池,以供后续连接使用
    conn.close()
    return result

@app.route('/task',methods=['GET','POST'])
def task():
    "访问post   http://192.168.9.148/task?token=fec22f96-2783-414o-06e3-991d357c96e6 提交任务,返回任务id882e1c4f-d82c-493c-991e-e330ff3af5fc"
    # 访问get  http://192.168.9.148/result?tid=882e1c4f-d82c-493c-991e-e330ff3af5fc 通过任务id查询任务完成情况

    # 1.token是否为空
    token = request.args.get("token")
    print('获取的token:',token)
    if not token:
        return jsonify({"status":False,'error':"认证失败1"})
    #token是否合法,连接mysql执行sql命令
    result =fetch_one("select * from test_user where token=%s",[token, ])



    if not result:
        return jsonify({"status": False, 'error': "认证失败2"})

    ordered_string = request.json.get("ordered_string")
    print('ordered_string=======',ordered_string)
    if not ordered_string:
        return jsonify({"status":False,'error':"认证失败3"})


    #生成任务ID
    tid=str(uuid.uuid4())
    #1.放入到redis队列中
    task_dict = {"tid":tid,"data":ordered_string}
    #REDIS_CONN_PARAMS = {"host":"192.168.9.156","password":"12345600","port":6379,"encoding":"utf-8"}
    #REDIS_CONN_PARAMS = {"host": "192.168.9.156", "password": "12345600", "port": 6379, "encoding": "utf-8"}
    #conn = redis.Redis(**REDIS_CONN_PARAMS)
    conn = redis.Redis(connection_pool=REDIS_POOL)
    conn.lpush("spider_task_list", json.dumps(task_dict))



    #2.给用户返回
    return jsonify({"status": True, 'data': tid , "message": "正在处理中,预计分钟后结束"})
@app.route('/result',methods=['GET'])
def result():
    #/result?tid=....
    tid=request.args.get('tid')
    if not tid:
        return jsonify({"status": False, 'error': "没有携带tid"})
    REDIS_CONN_PARAMS = {"host": "192.168.9.156", "password": "12345600", "port": 6379, "encoding": "utf-8"}
    conn = redis.Redis(**REDIS_CONN_PARAMS)
    singn = conn.hget("spider_result_dict", tid)
    if not singn:
        return jsonify({"status": True,'data': "","message":"未完成,请继续等待"})
    singn_string = singn.decode('utf-8')
    print("sign===",singn_string)
    #已经拿到的tid 在redis清除掉,避免一直能拿到
    conn.hdel("spider_result_dict", tid)
    return jsonify({"status": True,'data': singn_string})




'''   
    #调用核心算法,生成sign
    encrypt_string = ordered_string + "568c52ccd288fed845859ed18bffd973"
    print('encrypt_string:',encrypt_string)

    #encrypt_string.encode() 将字符串 123fnsfdsfdfdfdcdscfesdcdscdcdcdcddddddddddddscddswerewrfewfedcdcsdcdabc568c52ccd288fed845859ed18bffd973
    # 转换为字节 b'123fnsfdsfdfdfdcdscfesdcdscdcdcdcddddddddddddscddswerewrfewfedcdcsdcdabc568c52ccd288fed845859ed18bffd973'
    obj = hashlib.md5(encrypt_string.encode('utf-8'))
    print('字节=======',encrypt_string.encode('utf-8'))
    print('obj=',obj)
    
    # encrypt_string.encode()  将字符串 转换 为字节
    #hashlib.md5():创建一个 MD5 哈希对象  
    #hexdigest():获取哈希对象的十六进制表示
   
    sign = obj.hexdigest()
    print('sign=',sign)

    return jsonify({"status": True, 'data': sign})
'''
if __name__ == '__main__':
    app.run(host='0.0.0.0', port=80)

work进程

"""
去队列获取任务,执行并写入到结果队列
"""
import redis
import json
import hashlib

#redis连接池
REDIS_POOL = redis.ConnectionPool(host= '192.168.9.156',password='12345600', port= 6379, encoding="utf-8",max_connections=100)
def get_task():
    REDIS_CONN_PARAMS = {"host": "192.168.9.156", "password": "12345600", "port": 6379, "encoding": "utf-8"}
    conn = redis.Redis(**REDIS_CONN_PARAMS)
    data = conn.brpop("spider_task_list", timeout=10)
    if not data:
        return
    return json.loads(data[1].decode("utf-8"))
def set_result(tid,value):
    # REDIS_CONN_PARAMS = {"host": "192.168.9.156", "password": "12345600", "port": 6379, "encoding": "utf-8"}
    #conn = redis.Redis(**REDIS_CONN_PARAMS)
    conn = redis.Redis(connection_pool=REDIS_POOL)

    conn.hset("spider_result_dict",tid,value)

def run():
    while True:
        #1 执行耗时任务 获取传过去的body信息
        task_dict = get_task()
        print('已经接收的任务:',task_dict)
        if not task_dict:
            continue
    #2 执行耗时操作
        #数据格式: 已经接收的任务: {"tid": "4dfae670-9aa9-4739-be82-74d137b7ed99", "data": "123fnsfdsfdfdfdcdscfesdcdscdcdcdcddddddddddddscddswerewrfewfedcdcsdcdabc"}
        ordered_string = task_dict["data"]
        encrypt_string = ordered_string + "568c52ccd288fed845859ed18bffd973"
        obj = hashlib.md5(encrypt_string.encode('utf-8'))
        sign = obj.hexdigest()
        #3 写入到结果队列
        tid = task_dict['tid']
        set_result(tid,sign)






if __name__ == '__main__':
    run()

截图结果:
post提交一个任务

work收到任务:

通过id查询任务完成情况:

post访问:http://192.168.9.148/bili?token=fec22f96-2783-414o-06e3-991d357c96e6
json body体:{
"ordered_string":"123fnsfdsfdfdfdcdscfesdcdscdcdcdcddddddddddddscddswerewrfewfedcdcsdcdabc"
}

mysql数据库表示范:

import redis 报 SSL错

处理办法是把原来版本的卸载了 安装低版本的 原先版本是6.0

换成4.5.5就好了

posted @ 2025-05-02 01:55  ^_^小情绪~  阅读(54)  评论(0)    收藏  举报