init.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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") # 图像处理
  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. try:
  64. sql = pymysql.connect(user=mysql_name, password=mysql_passwd, host=mysql_url)
  65. cursor = sql.cursor()
  66. except pymysql.err:
  67. print("请提供正确的MySQL信息", file=sys.stderr)
  68. sys.exit(1)
  69. print("是否执行数据库初始化程序?\n执行初始化程序会令你丢失所有数据.")
  70. res = input("[Y/n]")
  71. if res == 'Y' or res == 'y':
  72. with open(os.path.join(__setup, "init.sql"), "r", encoding='utf-8') as f:
  73. all_sql = f.read().split(';\n') # 使用 `;` 作为分隔符是不够的, 因为函数中可能会使用`;`表示语句
  74. for s in all_sql:
  75. if s.strip() == "":
  76. continue
  77. cursor.execute(f"{s};")
  78. sql.commit()
  79. admin_passwd = input("创建 'admin' 管理员的密码: ")
  80. admin_phone = ""
  81. while len(admin_phone) != 11:
  82. admin_phone = input("输入 'admin' 管理员的电话[长度=11]: ")
  83. from tool.login import create_uid
  84. from tool.time import mysql_time
  85. # 生成基本 admin 用户
  86. uid = create_uid("admin", admin_passwd)
  87. cursor.execute(f"INSERT INTO user(UserID, Name, IsManager, Phone, Score, Reputation, CreateTime) "
  88. f"VALUES ('{uid}', 'admin', 1, '{admin_phone}', 10, 300, {mysql_time()});")
  89. sql.commit()
  90. print("是否伪造数据?")
  91. if input("[Y/n]") != "Y":
  92. cursor.close()
  93. sql.close()
  94. exit(0)
  95. # 伪造数据
  96. # 只有执行setup时可以伪造数据, 目的是不希望在生产环境上允许伪造数据
  97. # 不过这是个开源程序, 所以你完全可以绕开限制
  98. import random
  99. from tool.login import randomPassword
  100. check_import("faker", "Faker") # matplotlib依赖
  101. from faker import Faker
  102. fake = Faker(locale='zh_CN')
  103. random_manager = []
  104. random_normal = []
  105. loc = [fake.street_name() for _ in range(4)]
  106. def random_time() -> str:
  107. r_time = int(time.time())
  108. r_start = int(r_time - 35 * 24 * 60 * 60)
  109. return mysql_time(random.randint(r_start, r_time))
  110. def random_time_double() -> tuple[str, str]:
  111. r_time = int(time.time())
  112. r_start = int(r_time - 35 * 24 * 60 * 60)
  113. r_h1 = random.randint(r_start, r_time)
  114. r_h2 = random.randint(r_start, r_time)
  115. return mysql_time(min(r_h1, r_h2)), mysql_time(max(r_h1, r_h2))
  116. def random_user(r_name, r_passwd, r_phone, r_time, is_manager: int, cur, c_g=0, u_g=0):
  117. r_score = random.randint(0, 50000) / 100
  118. r_reputation = random.randint(5, 995)
  119. r_uid = create_uid(r_name, r_passwd)
  120. cur.execute(f"INSERT INTO user(UserID, Name, IsManager, Phone, Score, Reputation, CreateTime) "
  121. f"VALUES ('{r_uid}', '{r_name}', {is_manager}, '{r_phone}', {r_score}, {r_reputation}, {r_time});")
  122. if is_manager:
  123. random_manager.append(r_uid)
  124. print(f"管理员: {r_name} {r_passwd} {r_phone} {r_reputation} {r_score} {r_uid}")
  125. else:
  126. random_normal.append(r_uid)
  127. print(f"普通用户: {r_name} {r_passwd} {r_phone} {r_reputation} {r_score} {r_uid}")
  128. while c_g > 0:
  129. c_g -= 1
  130. t2, t1 = random_time_double()
  131. random_garbage_c_to_user(r_uid, t1, t2, cur)
  132. while u_g > 0:
  133. u_g -= 1
  134. t2, t1 = random_time_double()
  135. random_garbage_u_to_user(r_uid, t1, t2, cur)
  136. def random_garbage_n(r_time, cur):
  137. cur.execute(f"INSERT INTO garbage(CreateTime, Flat) VALUES ({r_time}, 0);")
  138. def random_garbage_c_to_user(user, r_time, r_time2, cur):
  139. r_loc = random.choice(loc)
  140. cur.execute(f"INSERT INTO garbage(CreateTime, Flat, UserID, UseTime, GarbageType, Location) "
  141. f"VALUES ({r_time}, 1, '{user}', {r_time2}, {random.randint(1, 4)}, '{r_loc}');")
  142. def random_garbage_u_to_user(user, r_time, r_time2, cur):
  143. checker = random.choice(random_manager)
  144. r_loc = random.choice(loc)
  145. cur.execute(f"INSERT INTO garbage(CreateTime, Flat, UserID, UseTime, GarbageType, Location, "
  146. f"CheckerID, CheckResult) "
  147. f"VALUES ({r_time}, 1, '{user}', {r_time2}, {random.randint(1, 4)}, '{r_loc}', "
  148. f"'{checker}', {random.randint(0, 1)});")
  149. def random_garbage_c(r_time, r_time2, cur):
  150. user = random.choice(random_normal)
  151. random_garbage_c_to_user(user, r_time, r_time2, cur)
  152. def random_garbage_u(r_time, r_time2, cur):
  153. user = random.choice(random_normal)
  154. random_garbage_c_to_user(user, r_time, r_time2, cur)
  155. def random_news(c_time, cur):
  156. user = random.choice(random_normal)
  157. text = f"大家好,我是 {fake.name()}, 我居住在 {fake.street_name()}{fake.street_address()}, 谢谢"
  158. cur.execute(f"INSERT INTO context(Context, Author, Time) "
  159. f"VALUES ('{text}', '{user}', {c_time});")
  160. def random_goods(cur):
  161. car = fake.license_plate()
  162. quantity = random.randint(0, 20)
  163. score = random.randint(10, 200)
  164. cur.execute(f"INSERT INTO goods(Name, Quantity, Score) "
  165. f"VALUES ('{car}', '{quantity}', {score});")
  166. def make_fake():
  167. print("步骤1, 注册管理账户[输入q结束]:")
  168. while True:
  169. if (name := input("输入用户名:")) == 'q': # 这里使用了海象表达式, 把赋值运算变成一种表达式
  170. break
  171. if (passwd := input("输入密码:")) == 'q':
  172. break
  173. if (phone := input("输入手机号码[输入x表示随机]:")) == 'q':
  174. break
  175. if (creat_time := input("是否随机时间[n=不随机 y=随机]:")) == 'q':
  176. break
  177. if phone == 'x':
  178. phone = fake.phone_number()
  179. if creat_time == 'n':
  180. c_time = mysql_time()
  181. else:
  182. c_time = random_time()
  183. random_user(name, passwd, phone, c_time, 1, cursor)
  184. print("步骤2, 注册普通账户[输入q结束]:")
  185. while True:
  186. if (name := input("输入用户名:")) == 'q': # 这里使用了海象表达式, 把赋值运算变成一种表达式
  187. break
  188. if (passwd := input("输入密码:")) == 'q':
  189. break
  190. if (phone := input("输入手机号码[输入x表示随机]:")) == 'q':
  191. break
  192. if (creat_time := input("是否随机时间[n=不随机 y=随机]:")) == 'q':
  193. break
  194. if (w_garbage := input("待检测垃圾个数:")) == 'q':
  195. break
  196. if (c_garbage := input("已检测垃圾个数:")) == 'q':
  197. break
  198. if creat_time == 'n':
  199. c_time = mysql_time()
  200. else:
  201. c_time = random_time()
  202. if phone == 'x':
  203. phone = fake.phone_number()
  204. w_garbage = int(w_garbage)
  205. c_garbage = int(w_garbage)
  206. random_user(name, passwd, phone, c_time, 0, cursor, w_garbage, c_garbage)
  207. count = int(input("步骤3, 注册随机管理员账户[输入个数]:"))
  208. while count > 0:
  209. name = randomPassword()[:5]
  210. passwd = randomPassword()
  211. phone = fake.phone_number()
  212. c_time = random_time()
  213. random_user(name, passwd, phone, c_time, 1, cursor)
  214. count -= 1
  215. count = int(input("步骤3, 注册随机普通账户[输入个数]:"))
  216. while count > 0:
  217. name = randomPassword()[:5]
  218. passwd = randomPassword()
  219. phone = fake.phone_number()
  220. c_time = random_time()
  221. random_user(name, passwd, phone, c_time, 0, cursor)
  222. count -= 1
  223. count = int(input("步骤4, 注册随机已检查垃圾袋[输入个数]:"))
  224. while count > 0:
  225. count -= 1
  226. c_time2, c_time1 = random_time_double()
  227. random_garbage_u(c_time1, c_time2, cursor)
  228. count = int(input("步骤5, 注册随机待检查垃圾袋[输入个数]:"))
  229. while count > 0:
  230. count -= 1
  231. c_time2, c_time1 = random_time_double()
  232. random_garbage_c(c_time1, c_time2, cursor)
  233. count = int(input("步骤6, 注册随机未使用垃圾袋[输入个数]:"))
  234. while count > 0:
  235. count -= 1
  236. c_time = random_time()
  237. random_garbage_n(c_time, cursor)
  238. count = int(input("步骤7, 注册随机新闻内容:"))
  239. while count > 0:
  240. count -= 1
  241. c_time = random_time()
  242. random_news(c_time, cursor)
  243. count = int(input("步骤8, 注册随机商城内容:"))
  244. while count > 0:
  245. count -= 1
  246. random_goods(cursor)
  247. make_fake()
  248. sql.commit()
  249. cursor.close()
  250. sql.close()