init.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. import os
  2. import sys
  3. import time
  4. from typing import Union, List
  5. print("初始化程序开始执行")
  6. print("开始检查依赖")
  7. print(r"是否使用 http://pypi.douban.com/simple/ 源")
  8. use_i = input(r"[Y/n]")
  9. if use_i == "Y" or use_i == 'y':
  10. use_i = r"-i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com"
  11. else:
  12. use_i = ""
  13. try:
  14. __import__("pip")
  15. except ImportError:
  16. print("检查结束, 未找到pip")
  17. sys.exit(1)
  18. else:
  19. print("依赖 pip 存在")
  20. if os.system(f"{sys.executable} -m pip install {use_i} --upgrade pip") != 0:
  21. print(f"依赖 pip 更新失败", file=sys.stderr)
  22. else:
  23. print(f"依赖 pip 更新成功")
  24. __setup = os.path.dirname(os.path.abspath(__file__))
  25. def check_import(packages: Union[str, List[str]], pips: Union[str, List[str]]):
  26. if type(pips) is str:
  27. pips = [pips]
  28. if type(packages) is str:
  29. packages = [packages]
  30. try:
  31. for package in packages:
  32. __import__(package)
  33. print(f"依赖 {package} 存在")
  34. except ImportError:
  35. for pip in pips:
  36. command = f"{sys.executable} -m pip install {use_i} {pip}"
  37. print(f"依赖 {pip} 安装: {command}")
  38. if os.system(command) != 0:
  39. print(f"依赖 {pip} 安装失败", file=sys.stderr)
  40. sys.exit(1)
  41. else:
  42. print(f"依赖 {packages}:{pip} 安装成功")
  43. check_import("cv2", "opencv-python==4.5.3.56") # 图像处理
  44. check_import("qrcode", "qrcode") # 二维码生成
  45. check_import("pymysql", "PyMySQL") # 连接 MySQL服务器
  46. check_import("cryptography", "cryptography") # 链接 MySQL 服务器时加密
  47. check_import("flask", "Flask") # 网页服务
  48. check_import("flask", "Flask") # 网页服务
  49. check_import("flask_wtf", "Flask-WTF") # 网页服务
  50. check_import("flask_login", "Flask-Login") # 网页服务
  51. check_import("pyecharts", "pyecharts") # 网页服务
  52. check_import("waitress", "waitress") # waitress 网页服务
  53. check_import("PIL", "Pillow") # 图片处理
  54. check_import("numpy", "numpy") # matplotlib依赖
  55. check_import("matplotlib", "matplotlib") # matplotlib依赖
  56. check_import(["oss2", "viapi", "aliyunsdkcore", "aliyunsdkimagerecog"],
  57. ["oss2", "aliyun-python-sdk-viapiutils", "viapi-utils", "aliyun-python-sdk-imagerecog"]) # 阿里云依赖
  58. import pymysql
  59. from conf import Config
  60. mysql_url = Config.mysql_url
  61. mysql_name = Config.mysql_name
  62. mysql_passwd = Config.mysql_passwd
  63. mysql_port = Config.mysql_port
  64. try:
  65. print(f"MySQL -h {mysql_url} -u {mysql_name} -P {mysql_port} -p{mysql_passwd}")
  66. sql = pymysql.connect(user=mysql_name, password=mysql_passwd, host=mysql_url, port=mysql_port)
  67. cursor = sql.cursor()
  68. except pymysql.err.Error:
  69. print("请提供正确的MySQL信息", file=sys.stderr)
  70. sys.exit(1)
  71. print("是否执行数据库初始化程序?\n执行初始化程序会令你丢失所有数据.")
  72. res = input("[Y/n]")
  73. if res == 'Y' or res == 'y':
  74. with open(os.path.join(__setup, "init.sql"), "r", encoding='utf-8') as f:
  75. all_sql = f.read().split(';\n') # 使用 `;` 作为分隔符是不够的, 因为函数中可能会使用`;`表示语句
  76. for s in all_sql:
  77. if s.strip() == "":
  78. continue
  79. cursor.execute(f"{s};")
  80. sql.commit()
  81. admin_passwd = input("创建 'admin' 管理员的密码: ")
  82. admin_phone = ""
  83. while len(admin_phone) != 11:
  84. admin_phone = input("输入 'admin' 管理员的电话[长度=11]: ")
  85. from tool.login import create_uid
  86. from tool.time import mysql_time
  87. # 生成基本 admin 用户
  88. uid = create_uid("admin", admin_passwd)
  89. cursor.execute(f"INSERT INTO user(UserID, Name, IsManager, Phone, Score, Reputation, CreateTime) "
  90. f"VALUES ('{uid}', 'admin', 1, '{admin_phone}', 10, 300, {mysql_time()});")
  91. sql.commit()
  92. print("是否伪造数据?")
  93. if input("[Y/n]") != "Y":
  94. cursor.close()
  95. sql.close()
  96. exit(0)
  97. # 伪造数据
  98. # 只有执行setup时可以伪造数据, 目的是不希望在生产环境上允许伪造数据
  99. # 不过这是个开源程序, 所以你完全可以绕开限制
  100. import random
  101. from tool.login import randomPassword
  102. check_import("faker", "Faker") # matplotlib依赖
  103. from faker import Faker
  104. fake = Faker(locale='zh_CN')
  105. random_manager = []
  106. random_normal = []
  107. loc = [fake.street_name() for _ in range(4)]
  108. def random_time() -> str:
  109. r_time = int(time.time())
  110. r_start = int(r_time - 35 * 24 * 60 * 60)
  111. return mysql_time(random.randint(r_start, r_time))
  112. def random_time_double() -> tuple[str, str]:
  113. r_time = int(time.time())
  114. r_start = int(r_time - 35 * 24 * 60 * 60)
  115. r_h1 = random.randint(r_start, r_time)
  116. r_h2 = random.randint(r_start, r_time)
  117. return mysql_time(min(r_h1, r_h2)), mysql_time(max(r_h1, r_h2))
  118. def random_user(r_name, r_passwd, r_phone, r_time, is_manager: int, cur, c_g=0, u_g=0):
  119. r_score = random.randint(0, 50000) / 100
  120. r_reputation = random.randint(5, 995)
  121. r_uid = create_uid(r_name, r_passwd)
  122. cur.execute(f"INSERT INTO user(UserID, Name, IsManager, Phone, Score, Reputation, CreateTime) "
  123. f"VALUES ('{r_uid}', '{r_name}', {is_manager}, '{r_phone}', {r_score}, {r_reputation}, {r_time});")
  124. if is_manager:
  125. random_manager.append(r_uid)
  126. print(f"管理员: {r_name} {r_passwd} {r_phone} {r_reputation} {r_score} {r_uid}")
  127. else:
  128. random_normal.append(r_uid)
  129. print(f"普通用户: {r_name} {r_passwd} {r_phone} {r_reputation} {r_score} {r_uid}")
  130. while c_g > 0:
  131. c_g -= 1
  132. t2, t1 = random_time_double()
  133. random_garbage_c_to_user(r_uid, t1, t2, cur)
  134. while u_g > 0:
  135. u_g -= 1
  136. t2, t1 = random_time_double()
  137. random_garbage_u_to_user(r_uid, t1, t2, cur)
  138. def random_garbage_n(r_time, cur):
  139. cur.execute(f"INSERT INTO garbage(CreateTime, Flat) VALUES ({r_time}, 0);")
  140. def random_garbage_c_to_user(user, r_time, r_time2, cur):
  141. r_loc = random.choice(loc)
  142. cur.execute(f"INSERT INTO garbage(CreateTime, Flat, UserID, UseTime, GarbageType, Location) "
  143. f"VALUES ({r_time}, 1, '{user}', {r_time2}, {random.randint(1, 4)}, '{r_loc}');")
  144. def random_garbage_u_to_user(user, r_time, r_time2, cur):
  145. checker = random.choice(random_manager)
  146. r_loc = random.choice(loc)
  147. cur.execute(f"INSERT INTO garbage(CreateTime, Flat, UserID, UseTime, GarbageType, Location, "
  148. f"CheckerID, CheckResult) "
  149. f"VALUES ({r_time}, 1, '{user}', {r_time2}, {random.randint(1, 4)}, '{r_loc}', "
  150. f"'{checker}', {random.randint(0, 1)});")
  151. def random_garbage_c(r_time, r_time2, cur):
  152. user = random.choice(random_normal)
  153. random_garbage_c_to_user(user, r_time, r_time2, cur)
  154. def random_garbage_u(r_time, r_time2, cur):
  155. user = random.choice(random_normal)
  156. random_garbage_c_to_user(user, r_time, r_time2, cur)
  157. def random_news(c_time, cur):
  158. user = random.choice(random_normal)
  159. text = f"大家好,我是 {fake.name()}, 我居住在 {fake.street_name()}{fake.street_address()}, 谢谢"
  160. cur.execute(f"INSERT INTO context(Context, Author, Time) "
  161. f"VALUES ('{text}', '{user}', {c_time});")
  162. def random_goods(cur):
  163. car = fake.license_plate()
  164. quantity = random.randint(0, 20)
  165. score = random.randint(10, 200)
  166. cur.execute(f"INSERT INTO goods(Name, Quantity, Score) "
  167. f"VALUES ('{car}', '{quantity}', {score});")
  168. def make_fake():
  169. print("步骤1, 注册管理账户[输入q结束]:")
  170. while True:
  171. if (name := input("输入用户名:")) == 'q': # 这里使用了海象表达式, 把赋值运算变成一种表达式
  172. break
  173. if (passwd := input("输入密码:")) == 'q':
  174. break
  175. if (phone := input("输入手机号码[输入x表示随机]:")) == 'q':
  176. break
  177. if (creat_time := input("是否随机时间[n=不随机 y=随机]:")) == 'q':
  178. break
  179. if phone == 'x':
  180. phone = fake.phone_number()
  181. if creat_time == 'n':
  182. c_time = mysql_time()
  183. else:
  184. c_time = random_time()
  185. random_user(name, passwd, phone, c_time, 1, cursor)
  186. print("步骤2, 注册普通账户[输入q结束]:")
  187. while True:
  188. if (name := input("输入用户名:")) == 'q': # 这里使用了海象表达式, 把赋值运算变成一种表达式
  189. break
  190. if (passwd := input("输入密码:")) == 'q':
  191. break
  192. if (phone := input("输入手机号码[输入x表示随机]:")) == 'q':
  193. break
  194. if (creat_time := input("是否随机时间[n=不随机 y=随机]:")) == 'q':
  195. break
  196. if (w_garbage := input("待检测垃圾个数:")) == 'q':
  197. break
  198. if (c_garbage := input("已检测垃圾个数:")) == 'q':
  199. break
  200. if creat_time == 'n':
  201. c_time = mysql_time()
  202. else:
  203. c_time = random_time()
  204. if phone == 'x':
  205. phone = fake.phone_number()
  206. w_garbage = int(w_garbage)
  207. c_garbage = int(w_garbage)
  208. random_user(name, passwd, phone, c_time, 0, cursor, w_garbage, c_garbage)
  209. count = int(input("步骤3, 注册随机管理员账户[输入个数]:"))
  210. while count > 0:
  211. name = randomPassword()[:5]
  212. passwd = randomPassword()
  213. phone = fake.phone_number()
  214. c_time = random_time()
  215. random_user(name, passwd, phone, c_time, 1, cursor)
  216. count -= 1
  217. count = int(input("步骤3, 注册随机普通账户[输入个数]:"))
  218. while count > 0:
  219. name = randomPassword()[:5]
  220. passwd = randomPassword()
  221. phone = fake.phone_number()
  222. c_time = random_time()
  223. random_user(name, passwd, phone, c_time, 0, cursor)
  224. count -= 1
  225. count = int(input("步骤4, 注册随机已检查垃圾袋[输入个数]:"))
  226. while count > 0:
  227. count -= 1
  228. c_time2, c_time1 = random_time_double()
  229. random_garbage_u(c_time1, c_time2, cursor)
  230. count = int(input("步骤5, 注册随机待检查垃圾袋[输入个数]:"))
  231. while count > 0:
  232. count -= 1
  233. c_time2, c_time1 = random_time_double()
  234. random_garbage_c(c_time1, c_time2, cursor)
  235. count = int(input("步骤6, 注册随机未使用垃圾袋[输入个数]:"))
  236. while count > 0:
  237. count -= 1
  238. c_time = random_time()
  239. random_garbage_n(c_time, cursor)
  240. count = int(input("步骤7, 注册随机新闻内容:"))
  241. while count > 0:
  242. count -= 1
  243. c_time = random_time()
  244. random_news(c_time, cursor)
  245. count = int(input("步骤8, 注册随机商城内容:"))
  246. while count > 0:
  247. count -= 1
  248. random_goods(cursor)
  249. make_fake()
  250. sql.commit()
  251. cursor.close()
  252. sql.close()