python 常用功能积累

sql查询

python 复制代码
import pymysql
import pandas as pd

user = '' #用户名
password = '' #密码
dbName = ''  #库名
dbHost = '' #ip
dbPort = 8888
con = pymysql.connect(
    host=dbHost,
    port=dbPort,
    user=user,
    password=password,
    database=dbName,
    charset='utf8')
cursor = con.cursor()
head = ["Id", "Url"]
t0, t1, name = '', '', ''
sql_select = "SELECT id, Url " \
             "FROM xxx " \
             "WHERE createTime >= ('{}') and createTime <= ('{}') and name = ('{}')".format(t0, t1, name)
cursor.execute(sql_select)
cds = cursor.fetchall()
df = pd.DataFrame(cds)
cursor.close()
con.close()

日志功能

python 复制代码
import logging
import os

if os.path.exists('log_retry.log'):
    os.remove('log_retry.log')

logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                    datefmt='%a, %d %b %Y %H:%M:%S',
                    filename='log_retry.log',
                    filemode='w')
count = 0
try:
    logging.info('############# TOTAL number ############:{}, '.format(count))
except:
    logging.error()

kafka传输

python 复制代码
from kafka import KafkaProducer
import json
# pip install kafka-python==2.0.2 -i https://pypi.tuna.tsinghua.edu.cn/simple
def kfk_send(msg):
    # kafka
    kafka_topic = '' #库名
    kafka_bootstrap_servers = ['172.25.214.75:9092', '172.25.214.76:9092', '172.25.214.78:9092']
    producer = KafkaProducer(bootstrap_servers=kafka_bootstrap_servers,
                             value_serializer=lambda v: json.dumps(v).encode('utf-8'))
    producer.send(kafka_topic, value=msg)
    producer.flush()

head = []
value = []
ndata = dict(zip(head, value))
kfk_send(ndata)

flask服务,异步执行(服务及时返回+耗时任务),使用线程池

python 复制代码
from concurrent.futures import ThreadPoolExecutor
from flask import Flask, request
import json
from time import sleep

executor = ThreadPoolExecutor(max_workers=4)
app = Flask(__name__)

def task(name):
    print(f"Hello {name}")
    
@app.route("/", methods=["POST"])
def main():
    request_dict = json.loads(request.data)
    p1 = request_dict["p1"]
    p2 = request_dict["p2"]
    executor.submit(task, p1, p2) #ubmit(fn, *args, **kwargs)
    sleep(3)
    return "Get your POST!!!"

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

python多进程

python 复制代码
from multiprocessing import Process

def infer(i, filelist):
    print(i, filelist)

if __name__ == '__main__':
    img_list = []
    num_process = 5
    num = int(len(img_list) / num_process)

    process_list = []
    for i in range(num_process):
        filelist = img_list[i * num:(i + 1) * num]
        if i == num_process - 1:
            filelist = img_list[i * num:]
        process_list.append(Process(target=infer, args=(i, filelist)))
    [p.start() for p in process_list]
    [p.join() for p in process_list]
相关推荐
用户277844910499315 小时前
借助DeepSeek智能生成测试用例:从提示词到Excel表格的全流程实践
人工智能·python
JavaEdge在掘金17 小时前
ssl.SSLCertVerificationError报错解决方案
python
我不会编程55517 小时前
Python Cookbook-5.1 对字典排序
开发语言·数据结构·python
李少兄17 小时前
Unirest:优雅的Java HTTP客户端库
java·开发语言·http
老歌老听老掉牙18 小时前
平面旋转与交线投影夹角计算
python·线性代数·平面·sympy
满怀101518 小时前
Python入门(7):模块
python
无名之逆18 小时前
Rust 开发提效神器:lombok-macros 宏库
服务器·开发语言·前端·数据库·后端·python·rust
你觉得20518 小时前
哈尔滨工业大学DeepSeek公开课:探索大模型原理、技术与应用从GPT到DeepSeek|附视频与讲义下载方法
大数据·人工智能·python·gpt·学习·机器学习·aigc
似水এ᭄往昔18 小时前
【C语言】文件操作
c语言·开发语言
啊喜拔牙18 小时前
1. hadoop 集群的常用命令
java·大数据·开发语言·python·scala