main.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632
  1. # fastapi
  2. from fastapi import FastAPI, Request, Response, HTTPException, status, Depends , Form
  3. from fastapi import templating
  4. from fastapi.templating import Jinja2Templates
  5. from fastapi.responses import HTMLResponse, RedirectResponse, JSONResponse
  6. from fastapi.middleware.cors import CORSMiddleware
  7. from fastapi.staticfiles import StaticFiles
  8. # fastapi view function parameters
  9. from typing import List, Optional
  10. import json
  11. # path
  12. import sys
  13. from sqlalchemy.sql.elements import False_
  14. # time
  15. # import datetime
  16. from datetime import timedelta, datetime
  17. # db
  18. import dataset
  19. from passlib import context
  20. import models
  21. from random import randint
  22. # authorize
  23. from passlib.context import CryptContext
  24. pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
  25. import jwt
  26. from fastapi_jwt_auth import AuthJWT
  27. from fastapi_jwt_auth.exceptions import AuthJWTException
  28. from fastapi.security import OAuth2AuthorizationCodeBearer, OAuth2PasswordRequestForm
  29. import numpy as np
  30. import pymysql
  31. pymysql.install_as_MySQLdb()
  32. db_settings = {
  33. "host": "db.ptt.cx",
  34. "port": 3306,
  35. "user": "choozmo",
  36. "password": "pAssw0rd",
  37. "db": "Water_tower",
  38. "charset": "utf8mb4"
  39. }
  40. # app
  41. app = FastAPI()
  42. app.add_middleware(
  43. CORSMiddleware,
  44. allow_origins=["*"],
  45. allow_credentials=True,
  46. allow_methods=["*"],
  47. allow_headers=["*"],
  48. )
  49. SECRET_KEY = "df2f77bd544240801a048bd4293afd8eeb7fff3cb7050e42c791db4b83ebadcd"
  50. ALGORITHM = "HS256"
  51. ACCESS_TOKEN_EXPIRE_MINUTES = 3000
  52. pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
  53. #
  54. app.mount(path='/templates', app=StaticFiles(directory='templates'), name='templates')
  55. app.mount(path='/static', app=StaticFiles(directory='static'), name='static ')
  56. #
  57. templates = Jinja2Templates(directory='templates')
  58. @AuthJWT.load_config
  59. def get_config():
  60. return models.Settings()
  61. # view
  62. @app.get('/', response_class=HTMLResponse)
  63. async def index(request: Request):
  64. print(request)
  65. return templates.TemplateResponse(name='index.html', context={'request': request})
  66. @app.get('/login', response_class=HTMLResponse)
  67. async def login(request: Request):
  68. return templates.TemplateResponse(name='login_test.html', context={'request': request})
  69. @app.post("/login")
  70. async def login_for_access_token(request: Request, form_data: OAuth2PasswordRequestForm = Depends(), Authorize: AuthJWT = Depends()):
  71. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  72. user = authenticate_user(form_data.username, form_data.password)
  73. if not user:
  74. raise HTTPException(
  75. status_code=status.HTTP_401_UNAUTHORIZED,
  76. detail="Incorrect username or password",
  77. headers={"WWW-Authenticate": "Bearer"},
  78. )
  79. access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
  80. access_token = create_access_token(
  81. data={"sub": user.username}, expires_delta=access_token_expires
  82. )
  83. table = db['users']
  84. user.token = access_token
  85. print(user)
  86. table.update(dict(user), ['username'],['password'])
  87. access_token = Authorize.create_access_token(subject=user.username)
  88. refresh_token = Authorize.create_refresh_token(subject=user.username)
  89. Authorize.set_access_cookies(access_token)
  90. Authorize.set_refresh_cookies(refresh_token)
  91. #return templates.TemplateResponse("home.html", {"request": request, "msg": 'Login'})
  92. return {"access_token": access_token, "token_type": "bearer"} # 回傳token給前端
  93. @app.get('/register', response_class=HTMLResponse)
  94. async def login(request: Request):
  95. return templates.TemplateResponse(name='rigister_test.html', context={'request': request})
  96. @app.post('/register')
  97. async def register(request: Request, form_data: OAuth2PasswordRequestForm = Depends()):
  98. user = models.User(**await request.form())
  99. print(form_data.username, form_data.password, user)
  100. user.id = randint(1000, 9999)
  101. user.isAdmin = 0 #預設為非管理者
  102. user.roleType = 0 #預設為employee
  103. # 密碼加密
  104. #user.password = get_password_hash(user.password)
  105. # 存入DB
  106. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  107. user_table = db['users']
  108. user_table.insert(dict(user))
  109. # 跳轉頁面至登入
  110. return templates.TemplateResponse(name='login.html', context={'request': request})
  111. @app.get('/home', response_class=HTMLResponse)
  112. async def home(request: Request):
  113. return templates.TemplateResponse(name='home.html', context={'request': request})
  114. @app.get('/tower', response_class=HTMLResponse)
  115. async def tower(request: Request, Authorize: AuthJWT = Depends()):
  116. try:
  117. Authorize.jwt_required()
  118. except Exception as e:
  119. print(e)
  120. return RedirectResponse('/login')
  121. # current_user = Authorize.get_jwt_subject()
  122. return templates.TemplateResponse(name='tower.html', context={'request': request})
  123. @app.get('/optim', response_class=HTMLResponse)
  124. async def optim(request: Request, Authorize: AuthJWT = Depends()):
  125. try:
  126. Authorize.jwt_required()
  127. except Exception as e:
  128. print(e)
  129. return RedirectResponse('/login')
  130. # current_user = Authorize.get_jwt_subject()
  131. return templates.TemplateResponse(name='optim.html', context={'request': request})
  132. @app.get('/vibration', response_class=HTMLResponse)
  133. async def vibration(request: Request, Authorize: AuthJWT = Depends()):
  134. try:
  135. Authorize.jwt_required()
  136. except Exception as e:
  137. print(e)
  138. return RedirectResponse('/login')
  139. # current_user = Authorize.get_jwt_subject()
  140. return templates.TemplateResponse(name='vibration.html', context={'request': request})
  141. @app.get('/history', response_class=HTMLResponse)
  142. async def history(request: Request, Authorize: AuthJWT = Depends()):
  143. try:
  144. Authorize.jwt_required()
  145. except Exception as e:
  146. print(e)
  147. return RedirectResponse('/login')
  148. # current_user = Authorize.get_jwt_subject()
  149. return templates.TemplateResponse(name='history.html', context={'request': request})
  150. @app.get('/device', response_class=HTMLResponse)
  151. async def device(request: Request, Authorize: AuthJWT = Depends()):
  152. try:
  153. Authorize.jwt_required()
  154. except Exception as e:
  155. print(e)
  156. return RedirectResponse('/login')
  157. # current_user = Authorize.get_jwt_subject()
  158. return templates.TemplateResponse(name='device.html', context={'request': request})
  159. @app.get('/system', response_class=HTMLResponse)
  160. async def system(request: Request, Authorize: AuthJWT = Depends()):
  161. try:
  162. Authorize.jwt_required()
  163. except Exception as e:
  164. print(e)
  165. return RedirectResponse('/login')
  166. # current_user = Authorize.get_jwt_subject()
  167. return templates.TemplateResponse(name='system.html', context={'request': request})
  168. @app.get('/member', response_class=HTMLResponse)
  169. async def get_member(request: Request, Authorize: AuthJWT = Depends()):
  170. """獲取所有帳號資訊"""
  171. try:
  172. Authorize.jwt_required()
  173. except Exception as e:
  174. print(e)
  175. return RedirectResponse('/login')
  176. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  177. statement = 'SELECT id,username,isAdmin,roleType FROM users'
  178. json_dic = {}
  179. for row in db.query(statement):
  180. #print(row['id'],row['username'])
  181. json_dic[row['username']] = {'isAdmin':row['isAdmin'],'roleType':row['roleType']}
  182. result = json.dumps(json_dic,ensure_ascii=False)
  183. current_user = Authorize.get_jwt_subject()
  184. print(current_user)
  185. return result
  186. @app.get('/member/edit', response_class=HTMLResponse)
  187. async def login(request: Request, Authorize: AuthJWT = Depends()):
  188. try:
  189. Authorize.jwt_required()
  190. except Exception as e:
  191. print(e)
  192. return RedirectResponse('/login')
  193. return templates.TemplateResponse(name='member_edit_test.html', context={'request': request})
  194. @app.get('/member_delete', response_class=HTMLResponse)
  195. async def login(request: Request, Authorize: AuthJWT = Depends()):
  196. try:
  197. Authorize.jwt_required()
  198. except Exception as e:
  199. print(e)
  200. return RedirectResponse('/login')
  201. return templates.TemplateResponse(name='delete_member_test2.html', context={'request': request})
  202. @app.post('/member_delete')
  203. async def delete_member(request: Request):
  204. """刪除成員"""
  205. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  206. del_user = models.del_user(**await request.form())
  207. delete_name = del_user.del_name
  208. statement = 'SELECT * FROM users'
  209. current_user = ''
  210. for row in db.query(statement):
  211. if row['token'] != None :
  212. if compare_jwt_token(row['token'],del_user.access_token):
  213. current_user = row['username']
  214. if current_user == '':
  215. return {'msg':'尚未登入'}
  216. statement = 'SELECT isAdmin FROM users WHERE userName = "'+current_user+'"'
  217. for row in db.query(statement):
  218. if row['isAdmin']!=1:
  219. return {'msg': ' 你沒有權限'}
  220. current_user_roleType = check_role_type(current_user)
  221. del_user_roleType = check_role_type(delete_name)
  222. if del_user_roleType == None:
  223. return {'msg':'不存在使用者'}
  224. elif current_user_roleType>del_user_roleType or current_user_roleType==del_user_roleType:
  225. return {'msg': ' 你沒有權限'}
  226. else :
  227. table = db['users']
  228. table.delete(username=delete_name)
  229. return {'msg': ' 成功刪除'}
  230. @app.get('/member_authority/{edit_one}', response_class=HTMLResponse)
  231. async def member_authority(request:Request,edit_one: str,Authorize: AuthJWT = Depends()):
  232. """設定成員權限"""
  233. try:
  234. Authorize.jwt_required()
  235. except Exception as e:
  236. print(e)
  237. return RedirectResponse('/login')
  238. context = {'request': request}
  239. current_user = Authorize.get_jwt_subject()
  240. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  241. statement = check_isAdmin(current_user)
  242. if statement == "no user":
  243. return {'msg':statement }
  244. elif statement == 0:
  245. return {'msg':'你沒有權限' }
  246. current_user_roleType = check_role_type(current_user)
  247. edit_one_roleType = check_role_type(edit_one)
  248. if edit_one_roleType == None:
  249. return {'msg':'不存在使用者'}
  250. elif current_user_roleType>edit_one_roleType or current_user_roleType==edit_one_roleType:
  251. return {'msg': ' 你沒有權限'}
  252. result = check_role_acl(edit_one)
  253. if result == []:
  254. cmd = 'SELECT id FROM module'
  255. for row in db.query(cmd):
  256. dic_tmp = {'id':get_user_id(edit_one),'isView':0,'isAdd':0 ,'isEdit':0,'isDel':0,'role_id' : check_role_type(edit_one)}
  257. context[get_modul_name(row['id']) ] = dic_tmp
  258. else:
  259. for dic in result:
  260. modul_name = get_modul_name(dic['module_id'])
  261. del dic['module_id']
  262. context[modul_name ] = dic
  263. print(context)
  264. return templates.TemplateResponse(name='member_authority_test.html', context=context)
  265. @app.post('/member_authority')
  266. async def member_authority(request: Request):
  267. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  268. edit_one = models.user_authority(**await request.form())
  269. statement = 'SELECT * FROM users'
  270. current_user = ''
  271. for row in db.query(statement):
  272. if row['token'] != None :
  273. if compare_jwt_token(row['token'],edit_one.access_token):
  274. current_user = row['username']
  275. if current_user == '':
  276. return {'msg':'尚未登入'}
  277. statement = check_isAdmin(current_user)
  278. if statement == "no user":
  279. return {'msg':statement }
  280. elif statement == 0:
  281. return {'msg':'你沒有權限' }
  282. current_user_roleType = check_role_type(current_user)
  283. edit_one_roleType = edit_one.role_id
  284. if edit_one.id == None:
  285. return {'msg':'不存在使用者'}
  286. elif current_user_roleType>edit_one_roleType or current_user_roleType==edit_one_roleType:
  287. return {'msg': ' 你沒有權限'}
  288. else :
  289. row = ['ai_prediction' ,'channel' ,'device', 'event', 'index' ,'performance', 'record', 'setting_device' ,'setting_system','tower']
  290. if check_role_acl(get_user_name(edit_one.id)) == []:
  291. for module in row :
  292. new_dict = edit_one.get_acl_from_module_name(module)
  293. table = db['role_acl']
  294. table.insert(new_dict)
  295. else:
  296. for module in row :
  297. new_dict = edit_one.get_acl_from_module_name(module)
  298. table = db['role_acl']
  299. table.update(new_dict, ['id'],['module_id'])
  300. return {'msg': ' 成功更改'}
  301. # 溫度API
  302. @app.get('/temperature')
  303. async def get_temperatures():
  304. """ 撈DB溫度 """
  305. return {'hot_water': 30.48, 'cold_water': 28.10, 'wet_ball': 25.14}
  306. @app.post("/example")
  307. async def example(request: Request,Authorize: AuthJWT = Depends()):
  308. try:
  309. Authorize.jwt_required()
  310. except Exception as e:
  311. print(e)
  312. current_user = Authorize.get_jwt_subject()
  313. #form_data = await request.form()
  314. print( current_user)
  315. return current_user
  316. @app.post('/user')
  317. def user(Authorize: AuthJWT = Depends()):
  318. Authorize.jwt_required()
  319. current_user = Authorize.get_jwt_subject()
  320. return {"user": current_user}
  321. @app.get("/example", response_class=HTMLResponse)
  322. async def example(request: Request,Authorize: AuthJWT = Depends()):
  323. try:
  324. Authorize.jwt_required()
  325. except Exception as e:
  326. print(e)
  327. return RedirectResponse('/login')
  328. current_user = Authorize.get_jwt_subject()
  329. print( current_user)
  330. return current_user
  331. @app.get('/health')
  332. async def get_health(date: str):
  333. """ 撈健康指標、預設健康指標 """
  334. date = str(datetime.strptime(date, "%Y-%m-%d"))[:10]
  335. print(date)
  336. print(str(datetime.today()))
  337. print(str(datetime.today()-timedelta(days=1)))
  338. fake_data = {
  339. str(datetime.today())[:10]: {'curr_health': 0.7, 'pred_health': 0.8},
  340. str(datetime.today()-timedelta(days=1))[:10]: {'curr_health': 0.6, 'pred_health': 0.7},
  341. }
  342. return fake_data[date]
  343. @app.get('/history_data')
  344. async def get_history(time_end: str):
  345. """ 透過終點時間,抓取歷史資料。 """
  346. date = str(datetime.strptime(time_end, "%Y-%m-%d"))[:10]
  347. print(date)
  348. print(str(datetime.today()))
  349. print(str(datetime.today()-timedelta(days=1)))
  350. fake_data = {
  351. str(datetime.today())[:10]: {
  352. 'curr_history': {
  353. 'RPM_1X': list(np.random.rand(13)),
  354. 'RPM_2X': list(np.random.rand(13)),
  355. 'RPM_3X': list(np.random.rand(13)),
  356. 'RPM_4X': list(np.random.rand(13)),
  357. 'RPM_5X': list(np.random.rand(13)),
  358. 'RPM_6X': list(np.random.rand(13)),
  359. 'RPM_7X': list(np.random.rand(13)),
  360. 'RPM_8X': list(np.random.rand(13)),
  361. 'Gear_1X': list(np.random.rand(13)),
  362. 'Gear_2X': list(np.random.rand(13)),
  363. 'Gear_3X': list(np.random.rand(13)),
  364. 'Gear_4X': list(np.random.rand(13)),
  365. },
  366. 'past_history': {
  367. 'RPM_1X': list(np.random.rand(13)),
  368. 'RPM_2X': list(np.random.rand(13)),
  369. 'RPM_3X': list(np.random.rand(13)),
  370. 'RPM_4X': list(np.random.rand(13)),
  371. 'RPM_5X': list(np.random.rand(13)),
  372. 'RPM_6X': list(np.random.rand(13)),
  373. 'RPM_7X': list(np.random.rand(13)),
  374. 'RPM_8X': list(np.random.rand(13)),
  375. 'Gear_1X': list(np.random.rand(13)),
  376. 'Gear_2X': list(np.random.rand(13)),
  377. 'Gear_3X': list(np.random.rand(13)),
  378. 'Gear_4X': list(np.random.rand(13)),
  379. }
  380. },
  381. str(datetime.today()-timedelta(days=1))[:10]: {
  382. 'curr_history': {
  383. 'RPM_1X': list(np.random.rand(13)),
  384. 'RPM_2X': list(np.random.rand(13)),
  385. 'RPM_3X': list(np.random.rand(13)),
  386. 'RPM_4X': list(np.random.rand(13)),
  387. 'RPM_5X': list(np.random.rand(13)),
  388. 'RPM_6X': list(np.random.rand(13)),
  389. 'RPM_7X': list(np.random.rand(13)),
  390. 'RPM_8X': list(np.random.rand(13)),
  391. 'Gear_1X': list(np.random.rand(13)),
  392. 'Gear_2X': list(np.random.rand(13)),
  393. 'Gear_3X': list(np.random.rand(13)),
  394. 'Gear_4X': list(np.random.rand(13)),
  395. },
  396. 'past_history': {
  397. 'RPM_1X': list(np.random.rand(13)),
  398. 'RPM_2X': list(np.random.rand(13)),
  399. 'RPM_3X': list(np.random.rand(13)),
  400. 'RPM_4X': list(np.random.rand(13)),
  401. 'RPM_5X': list(np.random.rand(13)),
  402. 'RPM_6X': list(np.random.rand(13)),
  403. 'RPM_7X': list(np.random.rand(13)),
  404. 'RPM_8X': list(np.random.rand(13)),
  405. 'Gear_1X': list(np.random.rand(13)),
  406. 'Gear_2X': list(np.random.rand(13)),
  407. 'Gear_3X': list(np.random.rand(13)),
  408. 'Gear_4X': list(np.random.rand(13)),
  409. }
  410. },
  411. }
  412. return fake_data[date]
  413. # Login funtion part
  414. def check_user_exists(username):
  415. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  416. if int(next(iter(db.query('SELECT COUNT(*) FROM Water_tower.users WHERE userName = "'+username+'"')))['COUNT(*)']) > 0:
  417. return True
  418. else:
  419. return False
  420. def get_user(username: str):
  421. """ 取得使用者資訊(Model) """
  422. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  423. if not check_user_exists(username): # if user don't exist
  424. return False
  425. user_dict = next(
  426. iter(db.query('SELECT * FROM Water_tower.users where userName ="'+username+'"')))
  427. user = models.User(**user_dict)
  428. return user
  429. def user_register(user):
  430. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  431. table = db['users']
  432. #user.password = get_password_hash(user.password)
  433. table.insert(dict(user))
  434. def get_password_hash(password):
  435. """ 加密密碼 """
  436. return pwd_context.hash(password)
  437. def verify_password(plain_password, hashed_password):
  438. """ 驗證密碼(hashed) """
  439. return pwd_context.verify(plain_password, hashed_password)
  440. def authenticate_user(username: str, password: str):
  441. """ 連線DB,讀取使用者是否存在。 """
  442. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  443. if not check_user_exists(username): # if user don't exist
  444. return False
  445. user_dict = next(iter(db.query('SELECT * FROM Water_tower.users where userName ="'+username+'"')))
  446. user = models.User(**user_dict)
  447. #if not verify_password(password, user.password):
  448. #return False
  449. return user
  450. def create_access_token(data: dict, expires_delta: Optional[timedelta] = None):
  451. """ 創建token,並設定過期時間。 """
  452. to_encode = data.copy()
  453. if expires_delta:
  454. expire = datetime.utcnow() + expires_delta
  455. else:
  456. expire = datetime.utcnow() + timedelta(minutes=15)
  457. to_encode.update({"exp": expire})
  458. encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
  459. return encoded_jwt
  460. def compare_jwt_token(access_token: str, token: str):
  461. """比對jwt token"""
  462. if len(access_token) < len(token):
  463. if access_token in token:
  464. return True
  465. else :
  466. return False
  467. elif len(access_token) > len(token):
  468. if token in access_token:
  469. return True
  470. else :
  471. return False
  472. else :
  473. if token == access_token:
  474. return True
  475. else :
  476. return False
  477. def check_isAdmin(user_name:str):
  478. """查看是否為管理員"""
  479. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  480. isAdmin = None
  481. cmd = 'SELECT isAdmin FROM users WHERE userName = "'+user_name+'"'
  482. for row in db.query(cmd) :
  483. isAdmin = row['isAdmin']
  484. if isAdmin== None:
  485. return "no user"
  486. return isAdmin
  487. def check_role_type(user_name:str):
  488. """查看使用者權限"""
  489. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  490. cmd = 'SELECT role.id FROM `users` JOIN `role` ON `users`.roleType = `role`.name where `users`.username = "'+user_name+'"'
  491. role_type = None
  492. for row in db.query(cmd) :
  493. role_type = row['id']
  494. return role_type
  495. def check_role_acl(user_name:str):
  496. """查看權限"""
  497. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  498. cmd = 'SELECT role_acl.* FROM `users` JOIN `role_acl` ON `users`.id = `role_acl`.user_id where `users`.username = "'+user_name+'"'
  499. result = []
  500. for row in db.query(cmd) :
  501. dic ={}
  502. for col_name in db['role_acl'].columns:
  503. dic[col_name] = row[col_name]
  504. if dic != {}:
  505. result.append(dic)
  506. return result
  507. def get_user_id(user_name:str):
  508. """獲取user id"""
  509. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  510. cmd = 'SELECT id FROM `users` where username = "'+user_name+'"'
  511. id = None
  512. for row in db.query(cmd) :
  513. id = row['id']
  514. return id
  515. def get_user_name(user_id:int):
  516. """獲取user id"""
  517. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  518. cmd = 'SELECT username FROM `users` where id = "'+user_id+'"'
  519. id = None
  520. for row in db.query(cmd) :
  521. id = row['username']
  522. return id
  523. def get_modul_name(modul_id:str):
  524. """獲取modul名稱"""
  525. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  526. cmd = 'SELECT moduleName FROM `module` where id = "'+modul_id+'"'
  527. modul_name = None
  528. for row in db.query(cmd) :
  529. modul_name = row['moduleName']
  530. return modul_name