前言
利用python直接操作wordpress数据库,批量添加用户,评论等。
模块 | 说明 |
---|
flask | web框架 |
faker | 随机账号信息生成 |
pymysql | 数据库操作 |
主函数
# -*- coding: utf-8 -*-
"""主函数"""
import argparse
import sys
from utils import *
from server import *
#程序入口
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="wp辅助工具")
parser.add_argument("-u","--adduser", action="store_true", help="批量添加用户")
parser.add_argument("-s","--server", action="store_true", help="启动web服务")
if not sys.argv[1:]:
sys.argv.extend(['-h'])
args = parser.parse_args()
if args.adduser:
add_users(3700)
if args.server:
app.run(debug=True, host='0.0.0.0', port=3060)
exit()
# -*- coding: utf-8 -*-
"""
Created on 2022-05-23 21:16:39
---------
@summary:
---------
@author: wxzy
"""
from flask import Flask, render_template, session, redirect, url_for, flash
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, TextAreaField
from wtforms.validators import DataRequired
from flask_bootstrap import Bootstrap
from utils import *
class CommentsForm(FlaskForm):
"""
评论表单类
"""
product_name = StringField("商品名:", validators=[DataRequired()])
comment = TextAreaField("评论列表:", validators=[DataRequired()], render_kw={"style": "height: 500px"})
submit = SubmitField("提交")
app = Flask(__name__)
app.config["SECRET_KEY"] = '79537d00f4834892986f09a100aa1aaf'
bootstrap = Bootstrap(app)
@app.route('/', methods=["GET", "POST"])
def index():
"""
添加表单页面
"""
product_name = None
form = CommentsForm()
#提交评论
if form.validate_on_submit():
if session.get("product_name") == form.product_name.data and session.get("comment") == form.comment.data :
flash("本商品已经提交过一次相同评论,请不要重复提交~!")
else:
#添加评论
res = addcomment(form.product_name.data, form.comment.data)
if res[0] == 1:
flash("此名称查询到{}个对应商品,请输入商品全称!".format(res[1]))
elif res[0] == 2:
flash("此商品名未查询到对应商品, 请检查商品名输入是否正确!")
else:
flash("恭喜你你,成功添加{}条评论!".format(res[1]))
# 更新session 字段
session["product_name"] = form.product_name.data
session["comment"] = form.comment.data
return redirect(url_for("index"))
return render_template("index.html",form=form)
数据库操作
批量添加用户
def add_users(num):
"""
批量添加用户
"""
user_str = ''
email_array = ['@163.com', '@gmail.com', '@126.com', '@microsoft.com', '@mail.com', '@fastmail.com']
fake = Faker('en_US')
#打开数据库
conn = pymysql.connect(host=HOST, user=USER, password=PASSWORD, db=DB, port=PORT, charset='utf8')
cur = conn.cursor()
for i in range(num):
i = i+1
user = '{}{}'.format(fake.first_name(), random.randint(10, 999))
email = '{}{}'.format(user, random.choice(email_array))
registered = datetime.strftime(datetime.now(),'%Y-%m-%d %H:%M:%S')
sql = "insert into wp_users(user_login, user_pass, user_nicename, user_email, user_registered, user_status, display_name) values(%s, %s, %s, %s, %s, %s, %s);"
#密码123456
#user_activation_key 无意义
cur.execute(sql, (user, '$P$BSBdHomZc571IfTLJhf3PhxaN3x7dn0', user, email, registered, 0, user))
conn.commit()
print('新增第{}个用户:{}'.format(i, email))
user_str = user_str + email + '\n'
#关闭数据库
cur.close()
conn.close()
#保存结果到文件
with open('/tmp/user{}.txt'.format(datetime.strftime(datetime.now(),'%Y-%m-%d-%H-%M-%S')), 'a+') as w:
w.write(user_str)
批量添加评论
def addcomment(product, comments):
"""
商品添加评论函数
"""
num = 0
#打开数据库
conn = pymysql.connect(host=HOST, user=USER, password=PASSWORD, db=DB, port=PORT, charset='utf8')
cur = conn.cursor()
#查询商品
sql = "select ID from wp_posts where post_title like '%{}%'".format(product)
cur.execute(sql)
ids = cur.fetchall()
if len(ids) == 0:
res = [2, 0]
elif len(ids) > 1:
res = [1, len(ids)]
else:
#变量
comment_post_ID = ids[0][0]
comment_array = comments.splitlines()
# ip_array
ips = os.popen("cat /data/log/nginx-proxy/access.log | awk '{print $1}' | sort | uniq").readlines()
# author
sql = "select ID,user_nicename,user_email,user_registered from wp_users where id not in (select user_id from wp_comments group by user_id having count(user_id) > 4) and id not in (select user_id from wp_comments where comment_post_ID = {}) order by RAND() limit {};".format(comment_post_ID, len(comment_array))
cur.execute(sql)
authors = cur.fetchall()
for comment in comment_array:
if len(comment) == 0:
continue
#时间
date = date_gmt = datetime.strftime(datetime.now(),'%Y-%m-%d %H:%M:%S')
#插入数据
try:
sql = "insert into wp_comments(comment_post_ID, comment_author, comment_author_email, comment_author_IP, comment_date, comment_date_gmt, comment_content, comment_agent, comment_type, user_id) values(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s);"
cur.execute(sql, (comment_post_ID, authors[num][1], authors[num][2], random.choice(ips).strip(), date, date_gmt, comment, random.choice(AGENTS), 'review', authors[num][0]))
last_id = cur.lastrowid
sql = "INSERT INTO `wp_commentmeta` (`comment_id`, `meta_key`, `meta_value`) VALUES (%s, 'rating', %s);"
cur.execute(sql, (last_id, random.choices(population=[3, 4, 5], weights=[0.1, 0.2, 0.7]).pop()))
sql = "UPDATE wp_posts SET comment_count = comment_count + 1 WHERE ID = '{}';".format(comment_post_ID)
cur.execute(sql)
sql = "UPDATE wp_postmeta SET meta_value = meta_value + 1 WHERE post_id = '{}' AND meta_key = '_wc_review_count';".format(comment_post_ID)
cur.execute(sql)
conn.commit()
except:
conn.rollback()
#评论加1
num = num + 1
res = [0, num]
#关闭链接
cur.close()
conn.close()
#返回结果
return res
评论 (2)