setup.py 10.0 KB

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