How to use isset method in Pytest

Best Python code snippet using pytest

master_data.py

Source:master_data.py Github

copy

Full Screen

1from connections.connect_mongo import db2from function.jsonencoder import json_encoder3from function.checktokenexpire import check_token_expire_backend4from function.getmemberinfo import *5from function.api import *6from bson.objectid import ObjectId7from bson.json_util import loads , dumps8from datetime import datetime , date , timedelta9import sys10import json11import random12import string13import re14import os15from modules.login import get_random_token16from modules.upload_image import *17def car_type_list(request):18 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false19 isset_accept = "Accept" in request.headers20 isset_content_type = "Content-Type" in request.headers21 admin_id = None22 if isset_accept and isset_content_type:23 car_type = db.car_type.find()24 if car_type is None:25 result = { 26 "status" : False,27 "msg" : "Data not found."28 }29 else:30 #เอาค่าที่ได้จาก query มาแปลงจาก object เป็น json31 car_type_object = dumps(car_type)32 car_type_json = json.loads(car_type_object)33 car_type_list = []34 for i in range(len(car_type_json)):35 car_brand = db.car_brand.find({36 "car_type_id": car_type_json[i]['_id']['$oid'],37 "brand_status": "1"38 })39 if car_brand is None:40 detail = "-"41 else:42 #เอาค่าที่ได้จาก query มาแปลงจาก object เป็น json43 car_brand_object = dumps(car_brand)44 car_brand_json = json.loads(car_brand_object)45 detail = ""46 for j in range(len(car_brand_json)):47 if j == 0:48 detail = car_brand_json[j]['brand_name']49 else:50 detail = detail+" , "+car_brand_json[j]['brand_name']51 car_type_list.append({"id" : car_type_json[i]['_id']['$oid'],"type": car_type_json[i]['car_type_name_th'],"detail": detail})52 result = {53 "status" : True,54 "msg" : "Get car type success.",55 "data" : car_type_list56 }57 else:58 result = { 59 "status" : False,60 "msg" : "Please check your parameters."61 }62 #set log detail63 user_type = "admin"64 function_name = "car_type_list"65 request_headers = request.headers66 params_get = None67 params_post = None68 set_api_log(user_type , admin_id , function_name , request_headers , params_get , params_post , result)69 return result70def car_brand_list(request):71 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false72 isset_accept = "Accept" in request.headers73 isset_content_type = "Content-Type" in request.headers74 admin_id = None75 params = json.loads(request.data)76 #เช็ค parameter ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false77 isset_app_version = "app_version" in params78 isset_car_type_id = "car_type_id" in params79 if isset_accept and isset_content_type and isset_app_version and isset_car_type_id:80 car_brand = db.car_brand.find({81 "car_type_id": params['car_type_id'],82 "brand_status": "1"83 })84 car_brand_list = []85 if car_brand is not None:86 #เอาค่าที่ได้จาก query มาแปลงจาก object เป็น json87 car_brand_object = dumps(car_brand)88 car_brand_json = json.loads(car_brand_object)89 car_brand_list = []90 for i in range(len(car_brand_json)):91 car_brand_list.append({"id" : car_brand_json[i]['_id']['$oid'],"name": car_brand_json[i]['brand_name'],"car_type_id": car_brand_json[i]['car_type_id']})92 result = {93 "status" : True,94 "msg" : "Get car brand success.",95 "data" : car_brand_list96 }97 else:98 result = { 99 "status" : False,100 "msg" : "Please check your parameters."101 }102 #set log detail103 user_type = "admin"104 function_name = "car_brand_list"105 request_headers = request.headers106 params_get = None107 params_post = params108 set_api_log(user_type , admin_id , function_name , request_headers , params_get , params_post , result)109 return result110def add_car_brand(request):111 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false112 isset_accept = "Accept" in request.headers113 isset_content_type = "Content-Type" in request.headers114 isset_token = "Authorization" in request.headers115 admin_id = None116 params = json.loads(request.data)117 #เช็ค parameter ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false118 isset_app_version = "app_version" in params119 isset_car_type_id = "car_type_id" in params120 isset_brand_name = "brand_name" in params121 if isset_accept and isset_content_type and isset_token and isset_app_version and isset_car_type_id and isset_brand_name:122 #เช็ค token ว่า expire แล้วหรือยัง123 token = request.headers['Authorization']124 check_token = check_token_expire_backend(token)125 if check_token:126 admin_info = get_admin_info(token)127 admin_id = admin_info['_id']['$oid']128 data = { 129 "car_type_id": params['car_type_id'],130 "brand_name": params['brand_name'].strip(),131 "brand_status": "1",132 "created_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S'),133 "updated_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S')134 }135 if db.car_brand.insert_one(data):136 result = {137 "status" : True,138 "msg" : "Add car brand success."139 }140 else:141 result = {142 "status" : False,143 "msg" : "Data insert failed."144 }145 else:146 result = { 147 "status" : False,148 "error_code" : 401,149 "msg" : "Unauthorized."150 }151 else:152 result = { 153 "status" : False,154 "msg" : "Please check your parameters."155 }156 #set log detail157 user_type = "admin"158 function_name = "add_car_brand"159 request_headers = request.headers160 params_get = None161 params_post = params162 set_api_log(user_type , admin_id , function_name , request_headers , params_get , params_post , result)163 return result164def edit_car_brand(request):165 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false166 isset_accept = "Accept" in request.headers167 isset_content_type = "Content-Type" in request.headers168 isset_token = "Authorization" in request.headers169 admin_id = None170 params = json.loads(request.data)171 #เช็ค parameter ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false172 isset_app_version = "app_version" in params173 isset_brand_id = "brand_id" in params174 isset_brand_name = "brand_name" in params175 if isset_accept and isset_content_type and isset_token and isset_app_version and isset_brand_id and isset_brand_name:176 #เช็ค token ว่า expire แล้วหรือยัง177 token = request.headers['Authorization']178 check_token = check_token_expire_backend(token)179 if check_token:180 admin_info = get_admin_info(token)181 admin_id = admin_info['_id']['$oid']182 # update data183 where_param = { "_id": ObjectId(params['brand_id']) }184 value_param = {185 "$set":186 {187 "brand_name": params['brand_name'].strip(),188 "updated_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S')189 }190 }191 if db.car_brand.update(where_param , value_param):192 result = {193 "status" : True,194 "msg" : "Edit car brand success."195 }196 else:197 result = {198 "status" : False,199 "msg" : "Data update failed."200 }201 else:202 result = { 203 "status" : False,204 "error_code" : 401,205 "msg" : "Unauthorized."206 }207 else:208 result = { 209 "status" : False,210 "msg" : "Please check your parameters."211 }212 #set log detail213 user_type = "admin"214 function_name = "edit_car_brand"215 request_headers = request.headers216 params_get = None217 params_post = params218 set_api_log(user_type , admin_id , function_name , request_headers , params_get , params_post , result)219 return result220def delete_car_brand(request):221 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false222 isset_accept = "Accept" in request.headers223 isset_content_type = "Content-Type" in request.headers224 isset_token = "Authorization" in request.headers225 admin_id = None226 params = json.loads(request.data)227 #เช็ค parameter ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false228 isset_app_version = "app_version" in params229 isset_brand_id = "brand_id" in params230 if isset_accept and isset_content_type and isset_token and isset_app_version and isset_brand_id:231 #เช็ค token ว่า expire แล้วหรือยัง232 token = request.headers['Authorization']233 check_token = check_token_expire_backend(token)234 if check_token:235 admin_info = get_admin_info(token)236 admin_id = admin_info['_id']['$oid']237 # update data238 where_param = { "_id": ObjectId(params['brand_id']) }239 value_param = {240 "$set":241 {242 "brand_status": "0",243 "updated_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S')244 }245 }246 if db.car_brand.update(where_param , value_param):247 result = {248 "status" : True,249 "msg" : "Delete car brand success."250 }251 else:252 result = {253 "status" : False,254 "msg" : "Data update failed."255 }256 else:257 result = { 258 "status" : False,259 "error_code" : 401,260 "msg" : "Unauthorized."261 }262 else:263 result = { 264 "status" : False,265 "msg" : "Please check your parameters."266 }267 #set log detail268 user_type = "admin"269 function_name = "delete_car_brand"270 request_headers = request.headers271 params_get = None272 params_post = params273 set_api_log(user_type , admin_id , function_name , request_headers , params_get , params_post , result)274 return result275def get_outside_inspection(request):276 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false277 isset_accept = "Accept" in request.headers278 isset_content_type = "Content-Type" in request.headers279 admin_id = None280 params = json.loads(request.data)281 #เช็ค parameter ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false282 isset_app_version = "app_version" in params283 isset_car_type_code = "car_type_code" in params284 if isset_accept and isset_content_type and isset_app_version and isset_car_type_code:285 outside_inspection = db.outside_inspection.find({"car_type_code": params['car_type_code']})286 287 if outside_inspection is None:288 result = { 289 "status" : False,290 "msg" : "Data not found."291 }292 else:293 #เอาค่าที่ได้จาก query มาแปลงจาก object เป็น json294 outside_inspection_object = dumps(outside_inspection)295 outside_inspection_json = json.loads(outside_inspection_object)296 outside_inspection_list = []297 for i in range(len(outside_inspection_json)):298 part_list = []299 for j in range(len(outside_inspection_json[i]['part'])):300 part_list.append({301 "part_name_en": outside_inspection_json[i]['part'][j]['part_name_en'],302 "part_name_th": outside_inspection_json[i]['part'][j]['part_name_th']303 })304 outside_inspection_list.append({305 "id" : outside_inspection_json[i]['_id']['$oid'],306 "car_type_code": outside_inspection_json[i]['car_type_code'],307 "point_name_en": outside_inspection_json[i]['point_name_en'],308 "point_name_th": outside_inspection_json[i]['point_name_th'],309 "part": part_list310 })311 result = {312 "status" : True,313 "msg" : "Get outside inspection success.",314 "data" : outside_inspection_list315 }316 else:317 result = { 318 "status" : False,319 "msg" : "Please check your parameters."320 }321 #set log detail322 user_type = "admin"323 function_name = "get_outside_inspection"324 request_headers = request.headers325 params_get = None326 params_post = params327 set_api_log(user_type , admin_id , function_name , request_headers , params_get , params_post , result)328 return result329def edit_outside_inspection(request):330 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false331 isset_accept = "Accept" in request.headers332 isset_content_type = "Content-Type" in request.headers333 isset_token = "Authorization" in request.headers334 admin_id = None335 params = json.loads(request.data)336 #เช็ค parameter ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false337 isset_app_version = "app_version" in params338 isset_data = "data" in params339 if isset_accept and isset_content_type and isset_token and isset_app_version and isset_data:340 #เช็ค token ว่า expire แล้วหรือยัง341 token = request.headers['Authorization']342 check_token = check_token_expire_backend(token)343 if check_token:344 admin_info = get_admin_info(token)345 admin_id = admin_info['_id']['$oid']346 for i in range(len(params['data'])):347 # update data348 where_param = { "_id": ObjectId(params['data'][i]['id']) }349 if len(params['data'][i]['part']) == 0:350 value_param = {351 "$set":352 {353 "point_name_en": params['data'][i]['point_name_en'].strip(),354 "point_name_th": params['data'][i]['point_name_th'].strip(),355 "updated_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S')356 }357 }358 else:359 part_list = []360 for j in range(len(params['data'][i]['part'])):361 part_list.append({362 "part_code": str(j),363 "part_name_en": params['data'][i]['part'][j]['part_name_en'].strip(),364 "part_name_th": params['data'][i]['part'][j]['part_name_th'].strip()365 })366 value_param = {367 "$set":368 {369 "point_name_en": params['data'][i]['point_name_en'].strip(),370 "point_name_th": params['data'][i]['point_name_th'].strip(),371 "part": part_list,372 "updated_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S')373 }374 }375 376 if db.outside_inspection.update(where_param , value_param):377 check_update = "1"378 else:379 check_update = "0"380 data_id = params['data'][i]['id']381 break382 if check_update == "1":383 result = {384 "status" : True,385 "msg" : "Edit outside inspection success."386 }387 else:388 result = {389 "status" : False,390 "msg" : "Data update failed."391 }392 else:393 result = { 394 "status" : False,395 "error_code" : 401,396 "msg" : "Unauthorized."397 }398 else:399 result = { 400 "status" : False,401 "msg" : "Please check your parameters."402 }403 #set log detail404 user_type = "admin"405 function_name = "edit_outside_inspection"406 request_headers = request.headers407 params_get = None408 params_post = params409 set_api_log(user_type , admin_id , function_name , request_headers , params_get , params_post , result)410 return result411def get_inspection_before_use(request):412 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false413 isset_accept = "Accept" in request.headers414 isset_content_type = "Content-Type" in request.headers415 admin_id = None416 if isset_accept and isset_content_type:417 inspection_before_use = db.inspection_before_use.find()418 419 if inspection_before_use is None:420 result = { 421 "status" : False,422 "msg" : "Data not found."423 }424 else:425 #เอาค่าที่ได้จาก query มาแปลงจาก object เป็น json426 inspection_before_use_object = dumps(inspection_before_use)427 inspection_before_use_json = json.loads(inspection_before_use_object)428 inspection_before_use_list = []429 for i in range(len(inspection_before_use_json)):430 if inspection_before_use_json[i]['check_status'] == "1":431 check_status_text = "เปิดใช้งาน"432 else:433 check_status_text = "ปิดใช้งาน"434 inspection_before_use_list.append({435 "id" : inspection_before_use_json[i]['_id']['$oid'],436 "check_name_en": inspection_before_use_json[i]['check_name_en'],437 "check_name_th": inspection_before_use_json[i]['check_name_th'],438 "check_status": inspection_before_use_json[i]['check_status'],439 "check_status_text": check_status_text440 })441 result = {442 "status" : True,443 "msg" : "Get inspection before use success.",444 "data" : inspection_before_use_list445 }446 else:447 result = { 448 "status" : False,449 "msg" : "Please check your parameters."450 }451 #set log detail452 user_type = "admin"453 function_name = "get_inspection_before_use"454 request_headers = request.headers455 params_get = None456 params_post = None457 set_api_log(user_type , admin_id , function_name , request_headers , params_get , params_post , result)458 return result459def add_inspection_before_use(request):460 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false461 isset_accept = "Accept" in request.headers462 isset_content_type = "Content-Type" in request.headers463 isset_token = "Authorization" in request.headers464 admin_id = None465 params = json.loads(request.data)466 #เช็ค parameter ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false467 isset_app_version = "app_version" in params468 isset_check_name_en = "check_name_en" in params469 isset_check_name_th = "check_name_th" in params470 if isset_accept and isset_content_type and isset_token and isset_app_version and isset_check_name_en and isset_check_name_th:471 #เช็ค token ว่า expire แล้วหรือยัง472 token = request.headers['Authorization']473 check_token = check_token_expire_backend(token)474 if check_token:475 admin_info = get_admin_info(token)476 admin_id = admin_info['_id']['$oid']477 data = { 478 "check_name_en": params['check_name_en'].strip(),479 "check_name_th": params['check_name_th'].strip(),480 "check_status": "1",481 "created_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S'),482 "updated_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S')483 }484 if db.inspection_before_use.insert_one(data):485 result = {486 "status" : True,487 "msg" : "Add inspection before use success."488 }489 else:490 result = {491 "status" : False,492 "msg" : "Data insert failed."493 }494 else:495 result = { 496 "status" : False,497 "error_code" : 401,498 "msg" : "Unauthorized."499 }500 else:501 result = { 502 "status" : False,503 "msg" : "Please check your parameters."504 }505 #set log detail506 user_type = "admin"507 function_name = "add_inspection_before_use"508 request_headers = request.headers509 params_get = None510 params_post = params511 set_api_log(user_type , admin_id , function_name , request_headers , params_get , params_post , result)512 return result513def edit_inspection_before_use(request):514 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false515 isset_accept = "Accept" in request.headers516 isset_content_type = "Content-Type" in request.headers517 isset_token = "Authorization" in request.headers518 admin_id = None519 params = json.loads(request.data)520 #เช็ค parameter ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false521 isset_app_version = "app_version" in params522 isset_check_id = "check_id" in params523 isset_check_name_en = "check_name_en" in params524 isset_check_name_th = "check_name_th" in params525 isset_check_status = "check_status" in params526 if isset_accept and isset_content_type and isset_token and isset_app_version and isset_check_id and isset_check_name_en and isset_check_name_th and isset_check_status:527 #เช็ค token ว่า expire แล้วหรือยัง528 token = request.headers['Authorization']529 check_token = check_token_expire_backend(token)530 if check_token:531 admin_info = get_admin_info(token)532 admin_id = admin_info['_id']['$oid']533 inspection_before_use = db.inspection_before_use.find_one({"_id": ObjectId(params['check_id'])})534 535 if inspection_before_use is None:536 result = { 537 "status" : False,538 "msg" : "Data not found."539 }540 else:541 #เอาค่าที่ได้จาก query มาแปลงจาก object เป็น json542 inspection_before_use_object = dumps(inspection_before_use)543 inspection_before_use_json = json.loads(inspection_before_use_object)544 if params['check_status'] is None:545 check_status = inspection_before_use_json['check_status']546 elif params['check_status'] == "0":547 check_status = "0"548 else:549 check_status = "1"550 # update data551 where_param = { "_id": ObjectId(params['check_id']) }552 value_param = {553 "$set":554 {555 "check_name_en": params['check_name_en'].strip(),556 "check_name_th": params['check_name_th'].strip(),557 "check_status": check_status,558 "updated_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S')559 }560 }561 562 if db.inspection_before_use.update(where_param , value_param):563 result = {564 "status" : True,565 "msg" : "Edit inspection before use success."566 }567 else:568 result = {569 "status" : False,570 "msg" : "Data update failed."571 }572 else:573 result = { 574 "status" : False,575 "error_code" : 401,576 "msg" : "Unauthorized."577 }578 else:579 result = { 580 "status" : False,581 "msg" : "Please check your parameters."582 }583 #set log detail584 user_type = "admin"585 function_name = "edit_inspection_before_use"586 request_headers = request.headers587 params_get = None588 params_post = params589 set_api_log(user_type , admin_id , function_name , request_headers , params_get , params_post , result)590 return result591def delete_inspection_before_use(request):592 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false593 isset_accept = "Accept" in request.headers594 isset_content_type = "Content-Type" in request.headers595 isset_token = "Authorization" in request.headers596 admin_id = None597 params = json.loads(request.data)598 #เช็ค parameter ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false599 isset_app_version = "app_version" in params600 isset_check_id = "check_id" in params601 if isset_accept and isset_content_type and isset_token and isset_app_version and isset_check_id:602 #เช็ค token ว่า expire แล้วหรือยัง603 token = request.headers['Authorization']604 check_token = check_token_expire_backend(token)605 if check_token:606 admin_info = get_admin_info(token)607 admin_id = admin_info['_id']['$oid']608 # update data609 where_param = { "_id": ObjectId(params['check_id']) }610 value_param = {611 "$set":612 {613 "check_status": "0",614 "updated_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S')615 }616 }617 if db.inspection_before_use.update(where_param , value_param):618 result = {619 "status" : True,620 "msg" : "Delete inspection before use success."621 }622 else:623 result = {624 "status" : False,625 "msg" : "Data update failed."626 }627 else:628 result = { 629 "status" : False,630 "error_code" : 401,631 "msg" : "Unauthorized."632 }633 else:634 result = { 635 "status" : False,636 "msg" : "Please check your parameters."637 }638 #set log detail639 user_type = "admin"640 function_name = "delete_inspection_before_use"641 request_headers = request.headers642 params_get = None643 params_post = params644 set_api_log(user_type , admin_id , function_name , request_headers , params_get , params_post , result)645 return result646def driver_level_list(request):647 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false648 isset_accept = "Accept" in request.headers649 isset_content_type = "Content-Type" in request.headers650 admin_id = None651 if isset_accept and isset_content_type:652 driver_level = db.driver_level.find({"level_status": "1"})653 driver_level_list = []654 if driver_level is not None:655 #เอาค่าที่ได้จาก query มาแปลงจาก object เป็น json656 driver_level_object = dumps(driver_level)657 driver_level_json = json.loads(driver_level_object)658 for i in range(len(driver_level_json)):659 driver_level_list.append({660 "id" : driver_level_json[i]['_id']['$oid'],661 "name_en": driver_level_json[i]['level_name_en'],662 "name_th": driver_level_json[i]['level_name_th'],663 "detail_en": driver_level_json[i]['level_detail_en'],664 "detail_th": driver_level_json[i]['level_detail_th'],665 "priority": int(driver_level_json[i]['level_priority']),666 "image": driver_level_json[i]['level_image']667 })668 result = {669 "status" : True,670 "msg" : "Get driver level success.",671 "data" : driver_level_list672 }673 else:674 result = { 675 "status" : False,676 "msg" : "Please check your parameters."677 }678 #set log detail679 user_type = "admin"680 function_name = "driver_level_list"681 request_headers = request.headers682 params_get = None683 params_post = None684 set_api_log(user_type , admin_id , function_name , request_headers , params_get , params_post , result)685 return result686def add_driver_level(request):687 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false688 isset_accept = "Accept" in request.headers689 isset_content_type = "Content-Type" in request.headers690 isset_token = "Authorization" in request.headers691 admin_id = None692 params = json.loads(request.data)693 #เช็ค parameter ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false694 isset_app_version = "app_version" in params695 isset_level_name_en = "level_name_en" in params696 isset_level_name_th = "level_name_th" in params697 isset_level_detail_en = "level_detail_en" in params698 isset_level_detail_th = "level_detail_th" in params699 isset_level_priority = "level_priority" in params700 isset_level_image = "level_image" in params701 if isset_accept and isset_content_type and isset_token and isset_app_version and isset_level_name_en and isset_level_name_th and isset_level_detail_en and isset_level_detail_th and isset_level_priority and isset_level_image:702 #เช็ค token ว่า expire แล้วหรือยัง703 token = request.headers['Authorization']704 check_token = check_token_expire_backend(token)705 if check_token:706 admin_info = get_admin_info(token)707 admin_id = admin_info['_id']['$oid']708 try:709 level_priority = int(params['level_priority'])710 check_level_priority = True711 except ValueError:712 check_level_priority = False713 check_level_name_en = db.driver_level.find({"level_name_en": params['level_name_en'].strip() , "level_status": "1"}).count()714 check_level_name_th = db.driver_level.find({"level_name_th": params['level_name_th'].strip() , "level_status": "1"}).count()715 if check_level_name_en > 0:716 result = {717 "status" : False,718 "msg" : "Level name (EN) has been used."719 }720 elif check_level_name_th > 0:721 result = {722 "status" : False,723 "msg" : "Level name (TH) has been used."724 }725 elif not check_level_priority:726 result = { 727 "status" : False,728 "msg" : "Level priority is not a number."729 }730 else:731 if params['level_image'] is None:732 image_name = None733 else:734 #generate token735 generate_token = get_random_token(40)736 check_upload_image = upload_driver_level_image(params['level_image'], generate_token)737 if check_upload_image is None:738 image_name = None739 else:740 image_name = check_upload_image741 data = { 742 "level_name_en": params['level_name_en'].strip(),743 "level_name_th": params['level_name_th'].strip(),744 "level_detail_en": params['level_detail_en'].strip(),745 "level_detail_th": params['level_detail_th'].strip(),746 "level_priority": int(params['level_priority']),747 "level_image": image_name,748 "level_status": "1",749 "created_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S'),750 "updated_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S')751 }752 if db.driver_level.insert_one(data):753 result = {754 "status" : True,755 "msg" : "Add driver level success."756 }757 else:758 result = {759 "status" : False,760 "msg" : "Data insert failed."761 }762 else:763 result = { 764 "status" : False,765 "error_code" : 401,766 "msg" : "Unauthorized."767 }768 else:769 result = { 770 "status" : False,771 "msg" : "Please check your parameters."772 }773 #set log detail774 user_type = "admin"775 function_name = "add_driver_level"776 request_headers = request.headers777 params_get = None778 params_post = params779 set_api_log(user_type , admin_id , function_name , request_headers , params_get , params_post , result)780 return result781def edit_driver_level(request):782 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false783 isset_accept = "Accept" in request.headers784 isset_content_type = "Content-Type" in request.headers785 isset_token = "Authorization" in request.headers786 admin_id = None787 params = json.loads(request.data)788 #เช็ค parameter ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false789 isset_app_version = "app_version" in params790 isset_level_id = "level_id" in params791 isset_level_name_en = "level_name_en" in params792 isset_level_name_th = "level_name_th" in params793 isset_level_detail_en = "level_detail_en" in params794 isset_level_detail_th = "level_detail_th" in params795 isset_level_priority = "level_priority" in params796 isset_level_status = "level_status" in params797 isset_level_image = "level_image" in params798 if isset_accept and isset_content_type and isset_token and isset_app_version and isset_level_id and isset_level_name_en and isset_level_name_th and isset_level_detail_en and isset_level_detail_th and isset_level_priority and isset_level_status and isset_level_image:799 #เช็ค token ว่า expire แล้วหรือยัง800 token = request.headers['Authorization']801 check_token = check_token_expire_backend(token)802 if check_token:803 admin_info = get_admin_info(token)804 admin_id = admin_info['_id']['$oid']805 try:806 level_priority = int(params['level_priority'])807 check_level_priority = True808 except ValueError:809 check_level_priority = False810 check_level_name_en = db.driver_level.find({811 "_id": {"$ne": ObjectId(params['level_id'])},812 "level_name_en": params['level_name_en'].strip(),813 "level_status": "1"814 }).count()815 check_level_name_th = db.driver_level.find({816 "_id": {"$ne": ObjectId(params['level_id'])},817 "level_name_th": params['level_name_th'].strip(),818 "level_status": "1"819 }).count()820 if check_level_name_en > 0:821 result = {822 "status" : False,823 "msg" : "Level name (EN) has been used."824 }825 elif check_level_name_th > 0:826 result = {827 "status" : False,828 "msg" : "Level name (TH) has been used."829 }830 elif not check_level_priority:831 result = { 832 "status" : False,833 "msg" : "Level priority is not a number."834 }835 else:836 driver_level = db.driver_level.find_one({837 "_id": ObjectId(params['level_id'])838 })839 #เอาค่าที่ได้จาก query มาแปลงจาก object เป็น json840 driver_level_object = dumps(driver_level)841 driver_level_json = json.loads(driver_level_object)842 if params['level_image'] is None:843 image_name = driver_level_json['level_image']844 else:845 #เช็ค path และลบรูปเก่า846 if driver_level_json['level_image'] is not None:847 if os.path.exists("static/images/driver_level/"+driver_level_json['level_image']):848 os.remove("static/images/driver_level/"+driver_level_json['level_image'])849 #generate token850 generate_token = get_random_token(40)851 check_upload_image = upload_driver_level_image(params['level_image'], generate_token)852 if check_upload_image is None:853 image_name = None854 else:855 image_name = check_upload_image856 if params['level_status'] is None:857 level_status = driver_level_json['level_status']858 elif params['level_status'] == "0":859 level_status = "0"860 else:861 level_status = "1"862 # update data863 where_param = { "_id": ObjectId(params['level_id']) }864 value_param = {865 "$set":866 {867 "level_name_en": params['level_name_en'].strip(),868 "level_name_th": params['level_name_th'].strip(),869 "level_detail_en": params['level_detail_en'].strip(),870 "level_detail_th": params['level_detail_th'].strip(),871 "level_priority": int(params['level_priority']),872 "level_image": image_name,873 "level_status": level_status,874 "updated_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S')875 }876 }877 if db.driver_level.update(where_param , value_param):878 result = {879 "status" : True,880 "msg" : "Edit driver level success."881 }882 else:883 result = {884 "status" : False,885 "msg" : "Data update failed."886 }887 else:888 result = { 889 "status" : False,890 "error_code" : 401,891 "msg" : "Unauthorized."892 }893 else:894 result = { 895 "status" : False,896 "msg" : "Please check your parameters."897 }898 #set log detail899 user_type = "admin"900 function_name = "edit_driver_level"901 request_headers = request.headers902 params_get = None903 params_post = params904 set_api_log(user_type , admin_id , function_name , request_headers , params_get , params_post , result)905 return result906def delete_driver_level(request):907 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false908 isset_accept = "Accept" in request.headers909 isset_content_type = "Content-Type" in request.headers910 isset_token = "Authorization" in request.headers911 admin_id = None912 params = json.loads(request.data)913 #เช็ค parameter ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false914 isset_app_version = "app_version" in params915 isset_level_id = "level_id" in params916 if isset_accept and isset_content_type and isset_token and isset_app_version and isset_level_id:917 #เช็ค token ว่า expire แล้วหรือยัง918 token = request.headers['Authorization']919 check_token = check_token_expire_backend(token)920 if check_token:921 admin_info = get_admin_info(token)922 admin_id = admin_info['_id']['$oid']923 # update data924 where_param = { "_id": ObjectId(params['level_id']) }925 value_param = {926 "$set":927 {928 "level_status": "0",929 "updated_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S')930 }931 }932 if db.driver_level.update(where_param , value_param):933 result = {934 "status" : True,935 "msg" : "Delete driver level success."936 }937 else:938 result = {939 "status" : False,940 "msg" : "Data update failed."941 }942 else:943 result = { 944 "status" : False,945 "error_code" : 401,946 "msg" : "Unauthorized."947 }948 else:949 result = { 950 "status" : False,951 "msg" : "Please check your parameters."952 }953 #set log detail954 user_type = "admin"955 function_name = "delete_driver_level"956 request_headers = request.headers957 params_get = None958 params_post = params959 set_api_log(user_type , admin_id , function_name , request_headers , params_get , params_post , result)960 return result961def payment_channel_list_backend(request):962 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false963 isset_accept = "Accept" in request.headers964 isset_content_type = "Content-Type" in request.headers965 admin_id = None966 if isset_accept and isset_content_type:967 payment_channel = db.payment_channel.find()968 payment_channel_list = []969 if payment_channel is not None:970 #เอาค่าที่ได้จาก query มาแปลงจาก object เป็น json971 payment_channel_object = dumps(payment_channel)972 payment_channel_json = json.loads(payment_channel_object)973 payment_channel_list = []974 for i in range(len(payment_channel_json)):975 if payment_channel_json[i]['account_status'] == "1":976 account_status_show = "เปิดใช้งาน"977 else:978 account_status_show = "ปิดใช้งาน"979 payment_channel_list.append({"id" : payment_channel_json[i]['_id']['$oid'],"account_name": payment_channel_json[i]['account_name'],"account_number": payment_channel_json[i]['account_number'],"bank_name_en": payment_channel_json[i]['bank_name_en'],"bank_name_th": payment_channel_json[i]['bank_name_th'],"bank_logo": payment_channel_json[i]['bank_logo'],"account_status": payment_channel_json[i]['account_status'],"account_status_show": account_status_show})980 result = {981 "status" : True,982 "msg" : "Get payment channel success.",983 "data" : payment_channel_list984 }985 else:986 result = { 987 "status" : False,988 "msg" : "Please check your parameters."989 }990 #set log detail991 user_type = "admin"992 function_name = "payment_channel_list_backend"993 request_headers = request.headers994 params_get = None995 params_post = None996 set_api_log(user_type , admin_id , function_name , request_headers , params_get , params_post , result)997 return result998def add_payment_channel(request):999 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false1000 isset_accept = "Accept" in request.headers1001 isset_content_type = "Content-Type" in request.headers1002 isset_token = "Authorization" in request.headers1003 admin_id = None1004 params = json.loads(request.data)1005 #เช็ค parameter ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false1006 isset_app_version = "app_version" in params1007 isset_account_name = "account_name" in params1008 isset_account_number = "account_number" in params1009 isset_bank_name_en = "bank_name_en" in params1010 isset_bank_name_th = "bank_name_th" in params1011 isset_account_status = "account_status" in params1012 isset_bank_logo = "bank_logo" in params1013 if isset_accept and isset_content_type and isset_token and isset_app_version and isset_account_name and isset_account_number and isset_bank_name_en and isset_bank_name_th and isset_account_status and isset_bank_logo:1014 #เช็ค token ว่า expire แล้วหรือยัง1015 token = request.headers['Authorization']1016 check_token = check_token_expire_backend(token)1017 if check_token:1018 admin_info = get_admin_info(token)1019 admin_id = admin_info['_id']['$oid']1020 check_account = db.payment_channel.find({"account_name": params['account_name'].strip() , "account_number": params['account_number'].strip()}).count()1021 if check_account > 0:1022 result = {1023 "status" : False,1024 "msg" : "Account has been used."1025 }1026 else:1027 if params['bank_logo'] is None:1028 image_name = None1029 else:1030 #generate token1031 generate_token = get_random_token(40)1032 check_upload_image = upload_bank_logo(params['bank_logo'], generate_token)1033 if check_upload_image is None:1034 image_name = None1035 else:1036 image_name = check_upload_image1037 if params['account_status'] == "0":1038 account_status = "0"1039 else:1040 account_status = "1"1041 data = { 1042 "account_name": params['account_name'].strip(),1043 "account_number": params['account_number'].strip(),1044 "bank_name_en": params['bank_name_en'].strip(),1045 "bank_name_th": params['bank_name_th'].strip(),1046 "bank_logo": image_name,1047 "account_status": account_status,1048 "created_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S'),1049 "updated_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S')1050 }1051 if db.payment_channel.insert_one(data):1052 result = {1053 "status" : True,1054 "msg" : "Add payment channel success."1055 }1056 else:1057 result = {1058 "status" : False,1059 "msg" : "Data insert failed."1060 }1061 else:1062 result = { 1063 "status" : False,1064 "error_code" : 401,1065 "msg" : "Unauthorized."1066 }1067 else:1068 result = { 1069 "status" : False,1070 "msg" : "Please check your parameters."1071 }1072 #set log detail1073 user_type = "admin"1074 function_name = "add_payment_channel"1075 request_headers = request.headers1076 params_get = None1077 params_post = params1078 set_api_log(user_type , admin_id , function_name , request_headers , params_get , params_post , result)1079 return result1080def edit_payment_channel(request):1081 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false1082 isset_accept = "Accept" in request.headers1083 isset_content_type = "Content-Type" in request.headers1084 isset_token = "Authorization" in request.headers1085 admin_id = None1086 params = json.loads(request.data)1087 #เช็ค parameter ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false1088 isset_app_version = "app_version" in params1089 isset_account_id = "account_id" in params1090 isset_account_name = "account_name" in params1091 isset_account_number = "account_number" in params1092 isset_bank_name_en = "bank_name_en" in params1093 isset_bank_name_th = "bank_name_th" in params1094 isset_account_status = "account_status" in params1095 isset_bank_logo = "bank_logo" in params1096 if isset_accept and isset_content_type and isset_token and isset_app_version and isset_account_id and isset_account_name and isset_account_number and isset_bank_name_en and isset_bank_name_th and isset_account_status and isset_bank_logo:1097 #เช็ค token ว่า expire แล้วหรือยัง1098 token = request.headers['Authorization']1099 check_token = check_token_expire_backend(token)1100 if check_token:1101 admin_info = get_admin_info(token)1102 admin_id = admin_info['_id']['$oid']1103 check_account = db.payment_channel.find({1104 "_id": {"$ne": ObjectId(params['account_id'])},1105 "account_name": params['account_name'].strip(),1106 "account_number": params['account_number'].strip()1107 }).count()1108 if check_account > 0:1109 result = {1110 "status" : False,1111 "msg" : "Account has been used."1112 }1113 else:1114 payment_channel = db.payment_channel.find_one({"_id": ObjectId(params['account_id'])})1115 #เอาค่าที่ได้จาก query มาแปลงจาก object เป็น json1116 payment_channel_object = dumps(payment_channel)1117 payment_channel_json = json.loads(payment_channel_object)1118 #ถ้าไม่มีการแก้ไขรูป profile (bank_logo เป็น null) ไม่ต้องอัพเดตรูป 1119 if params['bank_logo'] is None:1120 image_name = payment_channel_json['bank_logo']1121 else:1122 #เช็ค path และลบรูปเก่า1123 if payment_channel_json['bank_logo'] is not None:1124 if os.path.exists("static/images/bank/"+payment_channel_json['bank_logo']):1125 os.remove("static/images/bank/"+payment_channel_json['bank_logo'])1126 1127 #generate token1128 generate_token = get_random_token(40)1129 check_upload_image = upload_bank_logo(params['bank_logo'], generate_token)1130 if check_upload_image is None:1131 image_name = None1132 else:1133 image_name = check_upload_image1134 if params['account_status'] is None:1135 account_status = payment_channel_json['account_status']1136 elif params['account_status'] == "0":1137 account_status = "0"1138 else:1139 account_status = "1"1140 # update data1141 where_param = { "_id": ObjectId(params['account_id']) }1142 value_param = {1143 "$set":1144 {1145 "account_name": params['account_name'].strip(),1146 "account_number": params['account_number'].strip(),1147 "bank_name_en": params['bank_name_en'].strip(),1148 "bank_name_th": params['bank_name_th'].strip(),1149 "bank_logo": image_name,1150 "account_status": account_status,1151 "updated_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S')1152 }1153 }1154 if db.payment_channel.update(where_param , value_param):1155 result = {1156 "status" : True,1157 "msg" : "Edit payment channel success."1158 }1159 else:1160 result = {1161 "status" : False,1162 "msg" : "Data update failed."1163 }1164 else:1165 result = { 1166 "status" : False,1167 "error_code" : 401,1168 "msg" : "Unauthorized."1169 }1170 else:1171 result = { 1172 "status" : False,1173 "msg" : "Please check your parameters."1174 }1175 #set log detail1176 user_type = "admin"1177 function_name = "edit_payment_channel"1178 request_headers = request.headers1179 params_get = None1180 params_post = params1181 set_api_log(user_type , admin_id , function_name , request_headers , params_get , params_post , result)1182 return result1183def delete_payment_channel(request):1184 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false1185 isset_accept = "Accept" in request.headers1186 isset_content_type = "Content-Type" in request.headers1187 isset_token = "Authorization" in request.headers1188 admin_id = None1189 params = json.loads(request.data)1190 #เช็ค parameter ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false1191 isset_app_version = "app_version" in params1192 isset_account_id = "account_id" in params1193 if isset_accept and isset_content_type and isset_token and isset_app_version and isset_account_id:1194 #เช็ค token ว่า expire แล้วหรือยัง1195 token = request.headers['Authorization']1196 check_token = check_token_expire_backend(token)1197 if check_token:1198 admin_info = get_admin_info(token)1199 admin_id = admin_info['_id']['$oid']1200 #update data1201 where_param = { "_id": ObjectId(params['account_id']) }1202 value_param = {1203 "$set":1204 {1205 "account_status": "0",1206 "updated_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S')1207 }1208 }1209 if db.payment_channel.update(where_param , value_param):1210 result = {1211 "status" : True,1212 "msg" : "Delete payment channel success."1213 }1214 else:1215 result = {1216 "status" : False,1217 "msg" : "Data update failed."1218 }1219 else:1220 result = { 1221 "status" : False,1222 "error_code" : 401,1223 "msg" : "Unauthorized."1224 }1225 else:1226 result = { 1227 "status" : False,1228 "msg" : "Please check your parameters."1229 }1230 #set log detail1231 user_type = "admin"1232 function_name = "delete_payment_channel"1233 request_headers = request.headers1234 params_get = None1235 params_post = params1236 set_api_log(user_type , admin_id , function_name , request_headers , params_get , params_post , result)1237 return result1238def get_emergency_call(request):1239 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false1240 isset_accept = "Accept" in request.headers1241 isset_content_type = "Content-Type" in request.headers1242 admin_id = None1243 if isset_accept and isset_content_type:1244 emergency_call = db.emergency_call.find_one()1245 1246 if emergency_call is None:1247 result = { 1248 "status" : False,1249 "msg" : "Data not found."1250 }1251 else:1252 #เอาค่าที่ได้จาก query มาแปลงจาก object เป็น json1253 emergency_call_object = dumps(emergency_call)1254 emergency_call_json = json.loads(emergency_call_object)1255 result = {1256 "status" : True,1257 "msg" : "Get emergency call success.",1258 "emergency_call_id" : emergency_call_json['_id']['$oid'],1259 "call_customer_admin" : emergency_call_json['call_customer_admin'],1260 "call_driver_admin" : emergency_call_json['call_driver_admin']1261 }1262 else:1263 result = { 1264 "status" : False,1265 "msg" : "Please check your parameters."1266 }1267 #set log detail1268 user_type = "admin"1269 function_name = "get_emergency_call"1270 request_headers = request.headers1271 params_get = None1272 params_post = None1273 set_api_log(user_type , admin_id , function_name , request_headers , params_get , params_post , result)1274 return result1275def edit_emergency_call(request):1276 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false1277 isset_accept = "Accept" in request.headers1278 isset_content_type = "Content-Type" in request.headers1279 isset_token = "Authorization" in request.headers1280 admin_id = None1281 params = json.loads(request.data)1282 #เช็ค parameter ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false1283 isset_app_version = "app_version" in params1284 isset_emergency_call_id = "emergency_call_id" in params1285 isset_call_customer_admin = "call_customer_admin" in params1286 isset_call_driver_admin = "call_driver_admin" in params1287 if isset_accept and isset_content_type and isset_token and isset_app_version and isset_emergency_call_id and isset_call_customer_admin and isset_call_driver_admin:1288 #เช็ค token ว่า expire แล้วหรือยัง1289 token = request.headers['Authorization']1290 check_token = check_token_expire_backend(token)1291 if check_token:1292 admin_info = get_admin_info(token)1293 admin_id = admin_info['_id']['$oid']1294 #update data1295 where_param = { "_id": ObjectId(params['emergency_call_id']) }1296 value_param = {1297 "$set":1298 {1299 "call_customer_admin": params['call_customer_admin'].strip(),1300 "call_driver_admin": params['call_driver_admin'].strip(),1301 "updated_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S')1302 }1303 }1304 if db.emergency_call.update(where_param , value_param):1305 result = {1306 "status" : True,1307 "msg" : "Edit emergency call success."1308 }1309 else:1310 result = {1311 "status" : False,1312 "msg" : "Data update failed."1313 }1314 else:1315 result = { 1316 "status" : False,1317 "error_code" : 401,1318 "msg" : "Unauthorized."1319 }1320 else:1321 result = { 1322 "status" : False,1323 "msg" : "Please check your parameters."1324 }1325 #set log detail1326 user_type = "admin"1327 function_name = "edit_emergency_call"1328 request_headers = request.headers1329 params_get = None1330 params_post = params1331 set_api_log(user_type , admin_id , function_name , request_headers , params_get , params_post , result)1332 return result1333def region_list(request):1334 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false1335 isset_accept = "Accept" in request.headers1336 isset_content_type = "Content-Type" in request.headers1337 admin_id = None1338 if isset_accept and isset_content_type:1339 region = db.region.find()1340 if region is None:1341 result = { 1342 "status" : False,1343 "msg" : "Data not found."1344 }1345 else:1346 #เอาค่าที่ได้จาก query มาแปลงจาก object เป็น json1347 region_object = dumps(region)1348 region_json = json.loads(region_object)1349 region_list = []1350 for i in range(len(region_json)):1351 region_list.append({"id" : region_json[i]['_id']['$oid'],"region_code": region_json[i]['region_code'],"region_name_en": region_json[i]['region_name_en'],"region_name_th": region_json[i]['region_name_th']})1352 result = {1353 "status" : True,1354 "msg" : "Get region success.",1355 "data" : region_list1356 }1357 else:1358 result = { 1359 "status" : False,1360 "msg" : "Please check your parameters."1361 }1362 #set log detail1363 user_type = "admin"1364 function_name = "region_list"1365 request_headers = request.headers1366 params_get = None1367 params_post = None1368 set_api_log(user_type , admin_id , function_name , request_headers , params_get , params_post , result)1369 return result1370def province_list_backend(request):1371 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false1372 isset_accept = "Accept" in request.headers1373 isset_content_type = "Content-Type" in request.headers1374 admin_id = None1375 if isset_accept and isset_content_type:1376 province = db.province.find({"province_status": "1"})1377 if province is None:1378 result = { 1379 "status" : False,1380 "msg" : "Data not found."1381 }1382 else:1383 #เอาค่าที่ได้จาก query มาแปลงจาก object เป็น json1384 province_object = dumps(province)1385 province_json = json.loads(province_object)1386 province_list = []1387 for i in range(len(province_json)):1388 province_list.append({"id" : province_json[i]['_id']['$oid'],"province_code": province_json[i]['province_code'],"province_en": province_json[i]['province_en'],"province_th": province_json[i]['province_th'],"region_code": province_json[i]['region_code'],"region_name": province_json[i]['region_name']})1389 result = {1390 "status" : True,1391 "msg" : "Get province success.",1392 "data" : province_list1393 }1394 else:1395 result = { 1396 "status" : False,1397 "msg" : "Please check your parameters."1398 }1399 #set log detail1400 user_type = "admin"1401 function_name = "province_list_backend"1402 request_headers = request.headers1403 params_get = None1404 params_post = None1405 set_api_log(user_type , admin_id , function_name , request_headers , params_get , params_post , result)1406 return result1407def add_province(request):1408 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false1409 isset_accept = "Accept" in request.headers1410 isset_content_type = "Content-Type" in request.headers1411 isset_token = "Authorization" in request.headers1412 admin_id = None1413 params = json.loads(request.data)1414 #เช็ค parameter ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false1415 isset_app_version = "app_version" in params1416 isset_province_code = "province_code" in params1417 isset_province_en = "province_en" in params1418 isset_province_th = "province_th" in params1419 isset_region_code = "region_code" in params1420 if isset_accept and isset_content_type and isset_token and isset_app_version and isset_province_code and isset_province_en and isset_province_th and isset_region_code:1421 #เช็ค token ว่า expire แล้วหรือยัง1422 token = request.headers['Authorization']1423 check_token = check_token_expire_backend(token)1424 if check_token:1425 admin_info = get_admin_info(token)1426 admin_id = admin_info['_id']['$oid']1427 check_province = db.province.find({1428 "$or": [1429 {"province_code": params['province_code'].strip()},1430 {"province_en": params['province_en'].strip()},1431 {"province_th": params['province_th'].strip()}1432 ]}).count()1433 if check_province > 0:1434 result = {1435 "status" : False,1436 "msg" : "Province has been used."1437 }1438 else:1439 region = db.region.find_one({"region_code": params['region_code'].strip()})1440 if region is None:1441 result = { 1442 "status" : False,1443 "msg" : "Region not found."1444 }1445 else:1446 #เอาค่าที่ได้จาก query มาแปลงจาก object เป็น json1447 region_object = dumps(region)1448 region_json = json.loads(region_object)1449 data = { 1450 "province_code": params['province_code'].strip(),1451 "province_en": params['province_en'].strip(),1452 "province_th": params['province_th'].strip(),1453 "region_code": params['region_code'].strip(),1454 "region_name": region_json['region_name_th'],1455 "province_status": "1",1456 "created_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S'),1457 "updated_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S')1458 }1459 if db.province.insert_one(data):1460 result = {1461 "status" : True,1462 "msg" : "Add province success."1463 }1464 else:1465 result = {1466 "status" : False,1467 "msg" : "Data insert failed."1468 }1469 else:1470 result = { 1471 "status" : False,1472 "error_code" : 401,1473 "msg" : "Unauthorized."1474 }1475 else:1476 result = { 1477 "status" : False,1478 "msg" : "Please check your parameters."1479 }1480 #set log detail1481 user_type = "admin"1482 function_name = "add_province"1483 request_headers = request.headers1484 params_get = None1485 params_post = params1486 set_api_log(user_type , admin_id , function_name , request_headers , params_get , params_post , result)1487 return result1488def edit_province(request):1489 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false1490 isset_accept = "Accept" in request.headers1491 isset_content_type = "Content-Type" in request.headers1492 isset_token = "Authorization" in request.headers1493 admin_id = None1494 params = json.loads(request.data)1495 #เช็ค parameter ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false1496 isset_app_version = "app_version" in params1497 isset_province_id = "province_id" in params1498 isset_province_code = "province_code" in params1499 isset_province_en = "province_en" in params1500 isset_province_th = "province_th" in params1501 isset_region_code = "region_code" in params1502 isset_province_status = "province_status" in params1503 if isset_accept and isset_content_type and isset_token and isset_app_version and isset_province_id and isset_province_code and isset_province_en and isset_province_th and isset_region_code and isset_province_status:1504 #เช็ค token ว่า expire แล้วหรือยัง1505 token = request.headers['Authorization']1506 check_token = check_token_expire_backend(token)1507 if check_token:1508 admin_info = get_admin_info(token)1509 admin_id = admin_info['_id']['$oid']1510 check_province = db.province.find({1511 "$or": [1512 {"province_code": params['province_code'].strip()},1513 {"province_en": params['province_en'].strip()},1514 {"province_th": params['province_th'].strip()}1515 ],1516 "$and": [1517 {"_id": {"$ne": ObjectId(params['province_id'])}}1518 ]}).count()1519 if check_province > 0:1520 result = {1521 "status" : False,1522 "msg" : "Province has been used."1523 }1524 else:1525 province = db.province.find_one({"_id": ObjectId(params['province_id'])})1526 region = db.region.find_one({"region_code": params['region_code']})1527 if province is None:1528 result = { 1529 "status" : False,1530 "msg" : "Province not found."1531 }1532 elif region is None:1533 result = { 1534 "status" : False,1535 "msg" : "Region not found."1536 }1537 else:1538 #เอาค่าที่ได้จาก query มาแปลงจาก object เป็น json1539 province_object = dumps(province)1540 province_json = json.loads(province_object)1541 region_object = dumps(region)1542 region_json = json.loads(region_object)1543 if params['province_status'] is None:1544 province_status = province_json['province_status']1545 elif params['province_status'] == "0":1546 province_status = "0"1547 else:1548 province_status = "1"1549 # update data1550 where_param = { "_id": ObjectId(params['province_id']) }1551 value_param = {1552 "$set":1553 {1554 "province_code": params['province_code'].strip(),1555 "province_en": params['province_en'].strip(),1556 "province_th": params['province_th'].strip(),1557 "region_code": params['region_code'].strip(),1558 "region_name": region_json['region_name_th'],1559 "province_status": province_status,1560 "updated_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S')1561 }1562 }1563 if db.province.update(where_param , value_param):1564 result = {1565 "status" : True,1566 "msg" : "Edit province success."1567 }1568 else:1569 result = {1570 "status" : False,1571 "msg" : "Data update failed."1572 }1573 else:1574 result = { 1575 "status" : False,1576 "error_code" : 401,1577 "msg" : "Unauthorized."1578 }1579 else:1580 result = { 1581 "status" : False,1582 "msg" : "Please check your parameters."1583 }1584 #set log detail1585 user_type = "admin"1586 function_name = "edit_province"1587 request_headers = request.headers1588 params_get = None1589 params_post = params1590 set_api_log(user_type , admin_id , function_name , request_headers , params_get , params_post , result)1591 return result1592def delete_province(request):1593 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false1594 isset_accept = "Accept" in request.headers1595 isset_content_type = "Content-Type" in request.headers1596 isset_token = "Authorization" in request.headers1597 admin_id = None1598 params = json.loads(request.data)1599 #เช็ค parameter ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false1600 isset_app_version = "app_version" in params1601 isset_province_id = "province_id" in params1602 if isset_accept and isset_content_type and isset_token and isset_app_version and isset_province_id:1603 #เช็ค token ว่า expire แล้วหรือยัง1604 token = request.headers['Authorization']1605 check_token = check_token_expire_backend(token)1606 if check_token:1607 admin_info = get_admin_info(token)1608 admin_id = admin_info['_id']['$oid']1609 # update data1610 where_param = { "_id": ObjectId(params['province_id']) }1611 value_param = {1612 "$set":1613 {1614 "province_status": "0",1615 "updated_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S')1616 }1617 }1618 if db.province.update(where_param , value_param):1619 result = {1620 "status" : True,1621 "msg" : "Delete province success."1622 }1623 else:1624 result = {1625 "status" : False,1626 "msg" : "Data update failed."1627 }1628 else:1629 result = { 1630 "status" : False,1631 "error_code" : 401,1632 "msg" : "Unauthorized."1633 }1634 else:1635 result = { 1636 "status" : False,1637 "msg" : "Please check your parameters."1638 }1639 #set log detail1640 user_type = "admin"1641 function_name = "delete_province"1642 request_headers = request.headers1643 params_get = None1644 params_post = params1645 set_api_log(user_type , admin_id , function_name , request_headers , params_get , params_post , result)1646 return result1647def district_list_backend(request):1648 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false1649 isset_accept = "Accept" in request.headers1650 isset_content_type = "Content-Type" in request.headers1651 admin_id = None1652 params = json.loads(request.data)1653 #เช็ค parameter ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false1654 isset_app_version = "app_version" in params1655 isset_province_code = "province_code" in params1656 if isset_accept and isset_content_type and isset_app_version and isset_province_code:1657 if params['province_code'] is None:1658 district = db.district.find({"district_status": "1"})1659 else:1660 district = db.district.find({1661 "province_code": params['province_code'],1662 "district_status": "1"1663 })1664 if district is None:1665 result = { 1666 "status" : False,1667 "msg" : "Data not found."1668 }1669 else:1670 #เอาค่าที่ได้จาก query มาแปลงจาก object เป็น json1671 district_object = dumps(district)1672 district_json = json.loads(district_object)1673 district_list = []1674 for i in range(len(district_json)):1675 district_list.append({"id" : district_json[i]['_id']['$oid'],"district_code": district_json[i]['district_code'],"district_en": district_json[i]['district_en'],"district_th": district_json[i]['district_th'],"province_name": district_json[i]['province_name']})1676 result = {1677 "status" : True,1678 "msg" : "Get district success.",1679 "data" : district_list1680 }1681 else:1682 result = { 1683 "status" : False,1684 "msg" : "Please check your parameters."1685 }1686 #set log detail1687 user_type = "admin"1688 function_name = "district_list_backend"1689 request_headers = request.headers1690 params_get = None1691 params_post = params1692 set_api_log(user_type , admin_id , function_name , request_headers , params_get , params_post , result)1693 return result1694def add_district(request):1695 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false1696 isset_accept = "Accept" in request.headers1697 isset_content_type = "Content-Type" in request.headers1698 isset_token = "Authorization" in request.headers1699 admin_id = None1700 params = json.loads(request.data)1701 #เช็ค parameter ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false1702 isset_app_version = "app_version" in params1703 isset_district_code = "district_code" in params1704 isset_district_en = "district_en" in params1705 isset_district_th = "district_th" in params1706 isset_province_code = "province_code" in params1707 if isset_accept and isset_content_type and isset_token and isset_app_version and isset_district_code and isset_district_en and isset_district_th and isset_province_code:1708 #เช็ค token ว่า expire แล้วหรือยัง1709 token = request.headers['Authorization']1710 check_token = check_token_expire_backend(token)1711 if check_token:1712 admin_info = get_admin_info(token)1713 admin_id = admin_info['_id']['$oid']1714 check_district = db.district.find({1715 "$or": [1716 {"district_code": params['district_code'].strip()},1717 {"district_en": params['district_en'].strip()},1718 {"district_th": params['district_th'].strip()}1719 ]}).count()1720 if check_district > 0:1721 result = {1722 "status" : False,1723 "msg" : "District has been used."1724 }1725 else:1726 province = db.province.find_one({"province_code": params['province_code']})1727 if province is None:1728 result = { 1729 "status" : False,1730 "msg" : "Province not found."1731 }1732 else:1733 #เอาค่าที่ได้จาก query มาแปลงจาก object เป็น json1734 province_object = dumps(province)1735 province_json = json.loads(province_object)1736 data = { 1737 "district_code": params['district_code'].strip(),1738 "district_en": params['district_en'].strip(),1739 "district_th": params['district_th'].strip(),1740 "province_code": params['province_code'].strip(),1741 "province_name": province_json['province_th'],1742 "district_status": "1",1743 "created_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S'),1744 "updated_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S')1745 }1746 if db.district.insert_one(data):1747 result = {1748 "status" : True,1749 "msg" : "Add district success."1750 }1751 else:1752 result = {1753 "status" : False,1754 "msg" : "Data insert failed."1755 }1756 else:1757 result = { 1758 "status" : False,1759 "error_code" : 401,1760 "msg" : "Unauthorized."1761 }1762 else:1763 result = { 1764 "status" : False,1765 "msg" : "Please check your parameters."1766 }1767 #set log detail1768 user_type = "admin"1769 function_name = "add_district"1770 request_headers = request.headers1771 params_get = None1772 params_post = params1773 set_api_log(user_type , admin_id , function_name , request_headers , params_get , params_post , result)1774 return result1775def edit_district(request):1776 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false1777 isset_accept = "Accept" in request.headers1778 isset_content_type = "Content-Type" in request.headers1779 isset_token = "Authorization" in request.headers1780 admin_id = None1781 params = json.loads(request.data)1782 #เช็ค parameter ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false1783 isset_app_version = "app_version" in params1784 isset_district_id = "district_id" in params1785 isset_district_code = "district_code" in params1786 isset_district_en = "district_en" in params1787 isset_district_th = "district_th" in params1788 isset_province_code = "province_code" in params1789 isset_district_status = "district_status" in params1790 if isset_accept and isset_content_type and isset_token and isset_app_version and isset_district_id and isset_district_code and isset_district_en and isset_district_th and isset_province_code and isset_district_status:1791 #เช็ค token ว่า expire แล้วหรือยัง1792 token = request.headers['Authorization']1793 check_token = check_token_expire_backend(token)1794 if check_token:1795 admin_info = get_admin_info(token)1796 admin_id = admin_info['_id']['$oid']1797 check_district = db.district.find({1798 "$or": [1799 {"district_code": params['district_code'].strip()},1800 {"district_en": params['district_en'].strip()},1801 {"district_th": params['district_th'].strip()}1802 ],1803 "$and": [1804 {"_id": {"$ne": ObjectId(params['district_id'])}}1805 ]}).count()1806 if check_district > 0:1807 result = {1808 "status" : False,1809 "msg" : "District has been used."1810 }1811 else:1812 district = db.district.find_one({"_id": ObjectId(params['district_id'])})1813 province = db.province.find_one({"province_code": params['province_code']})1814 1815 if district is None:1816 result = { 1817 "status" : False,1818 "msg" : "District not found."1819 }1820 elif province is None:1821 result = { 1822 "status" : False,1823 "msg" : "Province not found."1824 }1825 else:1826 #เอาค่าที่ได้จาก query มาแปลงจาก object เป็น json1827 district_object = dumps(district)1828 district_json = json.loads(district_object)1829 province_object = dumps(province)1830 province_json = json.loads(province_object)1831 if params['district_status'] is None:1832 district_status = district_json['district_status']1833 elif params['district_status'] == "0":1834 district_status = "0"1835 else:1836 district_status = "1"1837 # update data1838 where_param = { "_id": ObjectId(params['district_id']) }1839 value_param = {1840 "$set":1841 {1842 "district_code": params['district_code'].strip(),1843 "district_en": params['district_en'].strip(),1844 "district_th": params['district_th'].strip(),1845 "province_code": params['province_code'].strip(),1846 "province_name": province_json['province_th'],1847 "district_status": district_status,1848 "updated_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S')1849 }1850 }1851 if db.district.update(where_param , value_param):1852 result = {1853 "status" : True,1854 "msg" : "Edit district success."1855 }1856 else:1857 result = {1858 "status" : False,1859 "msg" : "Data update failed."1860 }1861 else:1862 result = { 1863 "status" : False,1864 "error_code" : 401,1865 "msg" : "Unauthorized."1866 }1867 else:1868 result = { 1869 "status" : False,1870 "msg" : "Please check your parameters."1871 }1872 #set log detail1873 user_type = "admin"1874 function_name = "edit_district"1875 request_headers = request.headers1876 params_get = None1877 params_post = params1878 set_api_log(user_type , admin_id , function_name , request_headers , params_get , params_post , result)1879 return result1880def delete_district(request):1881 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false1882 isset_accept = "Accept" in request.headers1883 isset_content_type = "Content-Type" in request.headers1884 isset_token = "Authorization" in request.headers1885 admin_id = None1886 params = json.loads(request.data)1887 #เช็ค parameter ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false1888 isset_app_version = "app_version" in params1889 isset_district_id = "district_id" in params1890 if isset_accept and isset_content_type and isset_token and isset_app_version and isset_district_id:1891 #เช็ค token ว่า expire แล้วหรือยัง1892 token = request.headers['Authorization']1893 check_token = check_token_expire_backend(token)1894 if check_token:1895 admin_info = get_admin_info(token)1896 admin_id = admin_info['_id']['$oid']1897 # update data1898 where_param = { "_id": ObjectId(params['district_id']) }1899 value_param = {1900 "$set":1901 {1902 "district_status": "0",1903 "updated_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S')1904 }1905 }1906 if db.district.update(where_param , value_param):1907 result = {1908 "status" : True,1909 "msg" : "Delete district success."1910 }1911 else:1912 result = {1913 "status" : False,1914 "msg" : "Data update failed."1915 }1916 else:1917 result = { 1918 "status" : False,1919 "error_code" : 401,1920 "msg" : "Unauthorized."1921 }1922 else:1923 result = { 1924 "status" : False,1925 "msg" : "Please check your parameters."1926 }1927 #set log detail1928 user_type = "admin"1929 function_name = "delete_district"1930 request_headers = request.headers1931 params_get = None1932 params_post = params1933 set_api_log(user_type , admin_id , function_name , request_headers , params_get , params_post , result)1934 return result1935def sub_district_list_backend(request):1936 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false1937 isset_accept = "Accept" in request.headers1938 isset_content_type = "Content-Type" in request.headers1939 admin_id = None1940 params = json.loads(request.data)1941 #เช็ค parameter ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false1942 isset_app_version = "app_version" in params1943 isset_district_code = "district_code" in params1944 if isset_accept and isset_content_type and isset_app_version and isset_district_code:1945 if params['district_code'] is None:1946 sub_district = db.sub_district.find({"sub_district_status": "1"})1947 else:1948 sub_district = db.sub_district.find({1949 "district_code": params['district_code'],1950 "sub_district_status": "1"1951 })1952 if sub_district is None:1953 result = { 1954 "status" : False,1955 "msg" : "Data not found."1956 }1957 else:1958 #เอาค่าที่ได้จาก query มาแปลงจาก object เป็น json1959 sub_district_object = dumps(sub_district)1960 sub_district_json = json.loads(sub_district_object)1961 sub_district_list = []1962 for i in range(len(sub_district_json)):1963 sub_district_list.append({"sub_district_id" : sub_district_json[i]['_id']['$oid'],"sub_district_code": sub_district_json[i]['sub_district_code'],"sub_district_en": sub_district_json[i]['sub_district_en'],"sub_district_th": sub_district_json[i]['sub_district_th'],"postcode": sub_district_json[i]['postcode'],"district_code": sub_district_json[i]['district_code'],"district_en": sub_district_json[i]['district_en'],"district_th": sub_district_json[i]['district_th'],"province_code": sub_district_json[i]['province_code'],"province_en": sub_district_json[i]['province_en'],"province_th": sub_district_json[i]['province_th']})1964 result = {1965 "status" : True,1966 "msg" : "Get sub-district success.",1967 "data" : sub_district_list1968 }1969 else:1970 result = { 1971 "status" : False,1972 "msg" : "Please check your parameters."1973 }1974 #set log detail1975 user_type = "admin"1976 function_name = "sub_district_list_backend"1977 request_headers = request.headers1978 params_get = None1979 params_post = params1980 set_api_log(user_type , admin_id , function_name , request_headers , params_get , params_post , result)1981 return result1982def add_sub_district(request):1983 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false1984 isset_accept = "Accept" in request.headers1985 isset_content_type = "Content-Type" in request.headers1986 isset_token = "Authorization" in request.headers1987 admin_id = None1988 params = json.loads(request.data)1989 #เช็ค parameter ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false1990 isset_app_version = "app_version" in params1991 isset_sub_district_code = "sub_district_code" in params1992 isset_sub_district_en = "sub_district_en" in params1993 isset_sub_district_th = "sub_district_th" in params1994 isset_postcode = "postcode" in params1995 isset_district_code = "district_code" in params1996 isset_province_code = "province_code" in params1997 if isset_accept and isset_content_type and isset_token and isset_app_version and isset_sub_district_code and isset_sub_district_en and isset_sub_district_th and isset_postcode and isset_district_code and isset_province_code:1998 #เช็ค token ว่า expire แล้วหรือยัง1999 token = request.headers['Authorization']2000 check_token = check_token_expire_backend(token)2001 if check_token:2002 admin_info = get_admin_info(token)2003 admin_id = admin_info['_id']['$oid']2004 check_sub_district = db.sub_district.find({"sub_district_code": params['sub_district_code']}).count()2005 if check_sub_district > 0:2006 result = {2007 "status" : False,2008 "msg" : "Sub-district has been used."2009 }2010 else:2011 district = db.district.find_one({"district_code": params['district_code'].strip()})2012 province = db.province.find_one({"province_code": params['province_code'].strip()})2013 if district is None:2014 result = { 2015 "status" : False,2016 "msg" : "District not found."2017 }2018 elif province is None:2019 result = { 2020 "status" : False,2021 "msg" : "Province not found."2022 }2023 else:2024 #เอาค่าที่ได้จาก query มาแปลงจาก object เป็น json2025 district_object = dumps(district)2026 district_json = json.loads(district_object)2027 province_object = dumps(province)2028 province_json = json.loads(province_object)2029 data = { 2030 "sub_district_code": params['sub_district_code'].strip(),2031 "sub_district_en": params['sub_district_en'].strip(),2032 "sub_district_th": params['sub_district_th'].strip(),2033 "postcode": params['postcode'].strip(),2034 "district_code": params['district_code'].strip(),2035 "district_en": district_json['district_en'],2036 "district_th": district_json['district_th'],2037 "province_code": params['province_code'].strip(),2038 "province_en": province_json['province_en'],2039 "province_th": province_json['province_th'],2040 "sub_district_status": "1",2041 "created_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S'),2042 "updated_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S')2043 }2044 if db.sub_district.insert_one(data):2045 result = {2046 "status" : True,2047 "msg" : "Add sub-district success."2048 }2049 else:2050 result = {2051 "status" : False,2052 "msg" : "Data insert failed."2053 }2054 else:2055 result = { 2056 "status" : False,2057 "error_code" : 401,2058 "msg" : "Unauthorized."2059 }2060 else:2061 result = { 2062 "status" : False,2063 "msg" : "Please check your parameters."2064 }2065 #set log detail2066 user_type = "admin"2067 function_name = "add_sub_district"2068 request_headers = request.headers2069 params_get = None2070 params_post = params2071 set_api_log(user_type , admin_id , function_name , request_headers , params_get , params_post , result)2072 return result2073def edit_sub_district(request):2074 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false2075 isset_accept = "Accept" in request.headers2076 isset_content_type = "Content-Type" in request.headers2077 isset_token = "Authorization" in request.headers2078 admin_id = None2079 params = json.loads(request.data)2080 #เช็ค parameter ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false2081 isset_app_version = "app_version" in params2082 isset_sub_district_id = "sub_district_id" in params2083 isset_sub_district_code = "sub_district_code" in params2084 isset_sub_district_en = "sub_district_en" in params2085 isset_sub_district_th = "sub_district_th" in params2086 isset_postcode = "postcode" in params2087 isset_district_code = "district_code" in params2088 isset_province_code = "province_code" in params2089 isset_sub_district_status = "sub_district_status" in params2090 if isset_accept and isset_content_type and isset_token and isset_app_version and isset_sub_district_id and isset_sub_district_code and isset_sub_district_en and isset_sub_district_th and isset_postcode and isset_district_code and isset_province_code and isset_sub_district_status:2091 #เช็ค token ว่า expire แล้วหรือยัง2092 token = request.headers['Authorization']2093 check_token = check_token_expire_backend(token)2094 if check_token:2095 admin_info = get_admin_info(token)2096 admin_id = admin_info['_id']['$oid']2097 check_sub_district = db.sub_district.find({2098 "sub_district_code": params['sub_district_code'].strip(),2099 "$and": [2100 {"_id": {"$ne": ObjectId(params['sub_district_id'])}}2101 ]}).count()2102 if check_sub_district > 0:2103 result = {2104 "status" : False,2105 "msg" : "Sub-district has been used."2106 }2107 else:2108 sub_district = db.sub_district.find_one({"_id": ObjectId(params['sub_district_id'])})2109 district = db.district.find_one({"district_code": params['district_code'].strip()})2110 province = db.province.find_one({"province_code": params['province_code'].strip()})2111 if district is None:2112 result = { 2113 "status" : False,2114 "msg" : "Sub-district not found."2115 }2116 elif district is None:2117 result = { 2118 "status" : False,2119 "msg" : "District not found."2120 }2121 elif province is None:2122 result = { 2123 "status" : False,2124 "msg" : "Province not found."2125 }2126 else:2127 #เอาค่าที่ได้จาก query มาแปลงจาก object เป็น json2128 sub_district_object = dumps(sub_district)2129 sub_district_json = json.loads(sub_district_object)2130 district_object = dumps(district)2131 district_json = json.loads(district_object)2132 province_object = dumps(province)2133 province_json = json.loads(province_object)2134 if params['sub_district_status'] is None:2135 sub_district_status = sub_district_json['sub_district_status']2136 elif params['sub_district_status'] == "0":2137 sub_district_status = "0"2138 else:2139 sub_district_status = "1"2140 # update data2141 where_param = { "_id": ObjectId(params['sub_district_id']) }2142 value_param = {2143 "$set":2144 {2145 "sub_district_code": params['sub_district_code'].strip(),2146 "sub_district_en": params['sub_district_en'].strip(),2147 "sub_district_th": params['sub_district_th'].strip(),2148 "postcode": params['postcode'].strip(),2149 "district_code": params['district_code'].strip(),2150 "district_en": district_json['district_en'],2151 "district_th": district_json['district_th'],2152 "province_code": params['province_code'].strip(),2153 "province_en": province_json['province_en'],2154 "province_th": province_json['province_th'],2155 "sub_district_status": sub_district_status,2156 "updated_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S')2157 }2158 }2159 if db.sub_district.update(where_param , value_param):2160 result = {2161 "status" : True,2162 "msg" : "Edit sub-district success."2163 }2164 else:2165 result = {2166 "status" : False,2167 "msg" : "Data update failed."2168 }2169 else:2170 result = { 2171 "status" : False,2172 "error_code" : 401,2173 "msg" : "Unauthorized."2174 }2175 else:2176 result = { 2177 "status" : False,2178 "msg" : "Please check your parameters."2179 }2180 #set log detail2181 user_type = "admin"2182 function_name = "edit_sub_district"2183 request_headers = request.headers2184 params_get = None2185 params_post = params2186 set_api_log(user_type , admin_id , function_name , request_headers , params_get , params_post , result)2187 return result2188def delete_sub_district(request):2189 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false2190 isset_accept = "Accept" in request.headers2191 isset_content_type = "Content-Type" in request.headers2192 isset_token = "Authorization" in request.headers2193 admin_id = None2194 params = json.loads(request.data)2195 #เช็ค parameter ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false2196 isset_app_version = "app_version" in params2197 isset_sub_district_id = "sub_district_id" in params2198 if isset_accept and isset_content_type and isset_token and isset_app_version and isset_sub_district_id:2199 #เช็ค token ว่า expire แล้วหรือยัง2200 token = request.headers['Authorization']2201 check_token = check_token_expire_backend(token)2202 if check_token:2203 admin_info = get_admin_info(token)2204 admin_id = admin_info['_id']['$oid']2205 # update data2206 where_param = { "_id": ObjectId(params['sub_district_id']) }2207 value_param = {2208 "$set":2209 {2210 "sub_district_status": "0",2211 "updated_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S')2212 }2213 }2214 if db.sub_district.update(where_param , value_param):2215 result = {2216 "status" : True,2217 "msg" : "Delete sub-district success."2218 }2219 else:2220 result = {2221 "status" : False,2222 "msg" : "Data update failed."2223 }2224 else:2225 result = { 2226 "status" : False,2227 "error_code" : 401,2228 "msg" : "Unauthorized."2229 }2230 else:2231 result = { 2232 "status" : False,2233 "msg" : "Please check your parameters."2234 }2235 #set log detail2236 user_type = "admin"2237 function_name = "delete_sub_district"2238 request_headers = request.headers2239 params_get = None2240 params_post = params2241 set_api_log(user_type , admin_id , function_name , request_headers , params_get , params_post , result)2242 return result2243def get_address_info_backend(request):2244 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false2245 isset_accept = "Accept" in request.headers2246 isset_content_type = "Content-Type" in request.headers2247 isset_token = "Authorization" in request.headers2248 member_id = None2249 params = json.loads(request.data)2250 #เช็ค parameter ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false2251 isset_app_version = "app_version" in params2252 isset_postcode = "postcode" in params2253 if isset_accept and isset_content_type and isset_token and isset_app_version and isset_postcode:2254 #เช็ค token ว่า expire แล้วหรือยัง2255 token = request.headers['Authorization']2256 check_token = check_token_expire_backend(token)2257 if check_token:2258 admin_info = get_admin_info(token)2259 admin_id = admin_info['_id']['$oid']2260 2261 postcode = db.postcode.find({2262 "postcode": params['postcode'],2263 "postcode_status": "1"2264 })2265 if postcode is None:2266 result = { 2267 "status" : False,2268 "msg" : "Data not found." 2269 }2270 else:2271 #เอาค่าที่ได้จาก query มาแปลงจาก object เป็น json2272 postcode_object = dumps(postcode)2273 postcode_json = json.loads(postcode_object)2274 address_info_list = []2275 for i in range(len(postcode_json)):2276 sub_district_name = postcode_json[i]['sub_district_th']2277 district_name = postcode_json[i]['district_th']2278 province_name = postcode_json[i]['province_th']2279 address_info_list.append({2280 "postcode": postcode_json[i]['postcode'],2281 "sub_district_code": postcode_json[i]['sub_district_code'],2282 "sub_district_name": sub_district_name,2283 "district_code": postcode_json[i]['district_code'],2284 "district_name": district_name,2285 "province_code": postcode_json[i]['province_code'],2286 "province_name": province_name2287 })2288 result = {2289 "status" : True,2290 "msg" : "Get address info success.", 2291 "data" : address_info_list2292 }2293 else:2294 result = { 2295 "status" : False,2296 "error_code" : 401,2297 "msg" : "Unauthorized."2298 }2299 else:2300 result = { 2301 "status" : False,2302 "msg" : "Please check your parameters."2303 }2304 #set log detail2305 user_type = "admin"2306 function_name = "get_address_info"2307 request_headers = request.headers2308 params_get = None2309 params_post = params2310 set_api_log(user_type , admin_id , function_name , request_headers , params_get , params_post , result)2311 return result2312def text_list(request):2313 # เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false2314 isset_accept = "Accept" in request.headers2315 isset_content_type = "Content-Type" in request.headers2316 admin_id = None2317 if isset_accept and isset_content_type:2318 with open('static/language/mobile_customer.json', 'r', encoding='utf-8') as json_file:2319 data_customer = json.load(json_file)2320 2321 with open('static/language/mobile_driver.json', 'r', encoding='utf-8') as json_file:2322 data_driver = json.load(json_file)2323 2324 with open('static/language/web_frontend.json', 'r', encoding='utf-8') as json_file:2325 data_web = json.load(json_file)2326 text_list = []2327 for key_customer in data_customer['language_data'].keys():2328 text_list.append({"user_type" : "customer","text_code" : key_customer,"text_en": data_customer['language_data'][key_customer]['EN'],"text_th": data_customer['language_data'][key_customer]['TH']})2329 for key_driver in data_driver['language_data'].keys():2330 text_list.append({"user_type" : "driver","text_code" : key_driver,"text_en": data_driver['language_data'][key_driver]['EN'],"text_th": data_driver['language_data'][key_driver]['TH']})2331 for key_web in data_web['language_data'].keys():2332 text_list.append({"user_type" : "web","text_code" : key_web,"text_en": data_web['language_data'][key_web]['EN'],"text_th": data_web['language_data'][key_web]['TH']})2333 result = { 2334 "status" : True,2335 "msg" : "Get text success.",2336 "data" : text_list2337 }2338 else:2339 result = { 2340 "status" : False,2341 "msg" : "Please check your parameters."2342 }2343 #set log detail2344 user_type = "admin"2345 function_name = "text_list"2346 request_headers = request.headers2347 params_get = None2348 params_post = None2349 set_api_log(user_type , admin_id , function_name , request_headers , params_get , params_post , result)2350 return result2351 2352def add_text(request):2353 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false2354 isset_accept = "Accept" in request.headers2355 isset_content_type = "Content-Type" in request.headers2356 isset_token = "Authorization" in request.headers2357 admin_id = None2358 params = json.loads(request.data)2359 #เช็ค parameter ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false2360 isset_app_version = "app_version" in params2361 isset_user_type = "user_type" in params2362 isset_text_code = "text_code" in params2363 isset_text_en = "text_en" in params2364 isset_text_th = "text_th" in params2365 if isset_accept and isset_content_type and isset_token and isset_app_version and isset_user_type and isset_text_code and isset_text_en and isset_text_th:2366 #เช็ค token ว่า expire แล้วหรือยัง2367 token = request.headers['Authorization']2368 check_token = check_token_expire_backend(token)2369 if check_token:2370 admin_info = get_admin_info(token)2371 admin_id = admin_info['_id']['$oid']2372 if params['user_type'] == "customer":2373 with open('static/language/mobile_customer.json', 'r', encoding='utf-8') as json_file:2374 data = json.load(json_file)2375 elif params['user_type'] == "driver":2376 with open('static/language/mobile_driver.json', 'r', encoding='utf-8') as json_file:2377 data = json.load(json_file)2378 else:2379 with open('static/language/web_frontend.json', 'r', encoding='utf-8') as json_file:2380 data = json.load(json_file)2381 #ถ้าเจอ text_code ใน language_data จะไม่สามารถเพิ่มข้อมูลได้2382 if params['text_code'] in data['language_data']:2383 result = {2384 "status" : False,2385 "msg" : "Text code has been used."2386 }2387 else:2388 text_dict = {2389 params['text_code']: {2390 "TH": params['text_th'],2391 "EN": params['text_en']2392 }2393 }2394 #เพิ่ม text ใหม่ใส่ language_data2395 data['language_data'].update(text_dict) 2396 language_all = {2397 "language_list" : data['language_list'],2398 "language_data" : data['language_data']2399 }2400 try:2401 if params['user_type'] == "customer":2402 with open('static/language/mobile_customer.json','w', encoding='utf8') as f: 2403 json.dump(language_all, f, indent=2, ensure_ascii=False)2404 elif params['user_type'] == "driver":2405 with open('static/language/mobile_driver.json','w', encoding='utf8') as f: 2406 json.dump(language_all, f, indent=2, ensure_ascii=False)2407 else:2408 with open('static/language/web_frontend.json','w', encoding='utf8') as f: 2409 json.dump(language_all, f, indent=2, ensure_ascii=False)2410 result = {2411 "status" : True,2412 "msg" : "Add text success."2413 }2414 except:2415 result = {2416 "status" : False,2417 "msg" : "Data insert failed."2418 }2419 else:2420 result = { 2421 "status" : False,2422 "error_code" : 401,2423 "msg" : "Unauthorized."2424 }2425 else:2426 result = { 2427 "status" : False,2428 "msg" : "Please check your parameters."2429 }2430 #set log detail2431 user_type = "admin"2432 function_name = "add_text"2433 request_headers = request.headers2434 params_get = None2435 params_post = params2436 set_api_log(user_type , admin_id , function_name , request_headers , params_get , params_post , result)2437 return result2438def edit_text(request):2439 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false2440 isset_accept = "Accept" in request.headers2441 isset_content_type = "Content-Type" in request.headers2442 isset_token = "Authorization" in request.headers2443 admin_id = None2444 params = json.loads(request.data)2445 #เช็ค parameter ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false2446 isset_app_version = "app_version" in params2447 isset_user_type = "user_type" in params2448 isset_text_code = "text_code" in params2449 isset_text_en = "text_en" in params2450 isset_text_th = "text_th" in params2451 if isset_accept and isset_content_type and isset_token and isset_app_version and isset_user_type and isset_text_code and isset_text_en and isset_text_th:2452 #เช็ค token ว่า expire แล้วหรือยัง2453 token = request.headers['Authorization']2454 check_token = check_token_expire_backend(token)2455 if check_token:2456 admin_info = get_admin_info(token)2457 admin_id = admin_info['_id']['$oid']2458 if params['user_type'] == "customer":2459 with open('static/language/mobile_customer.json', 'r', encoding='utf-8') as json_file:2460 data = json.load(json_file)2461 elif params['user_type'] == "driver":2462 with open('static/language/mobile_driver.json', 'r', encoding='utf-8') as json_file:2463 data = json.load(json_file)2464 else:2465 with open('static/language/web_frontend.json', 'r', encoding='utf-8') as json_file:2466 data = json.load(json_file)2467 #ถ้าเจอ text_code ใน language_data ถึงจะแก้ไขได้2468 if params['text_code'] in data['language_data']:2469 #แก้ไขข้อมูล2470 data['language_data'][params['text_code']]['TH'] = params['text_th']2471 data['language_data'][params['text_code']]['EN'] = params['text_en']2472 language_all = {2473 "language_list" : data['language_list'],2474 "language_data" : data['language_data']2475 }2476 try:2477 if params['user_type'] == "customer":2478 with open('static/language/mobile_customer.json','w', encoding='utf8') as f: 2479 json.dump(language_all, f, indent=2, ensure_ascii=False)2480 elif params['user_type'] == "driver":2481 with open('static/language/mobile_customer.json','w', encoding='utf8') as f: 2482 json.dump(language_all, f, indent=2, ensure_ascii=False)2483 else:2484 with open('static/language/web_frontend.json','w', encoding='utf8') as f: 2485 json.dump(language_all, f, indent=2, ensure_ascii=False)2486 result = {2487 "status" : True,2488 "msg" : "Edit text success."2489 }2490 except:2491 result = {2492 "status" : False,2493 "msg" : "Data update failed."2494 }2495 else:2496 result = {2497 "status" : False,2498 "msg" : "Text code not found."2499 }2500 else:2501 result = { 2502 "status" : False,2503 "error_code" : 401,2504 "msg" : "Unauthorized."2505 }2506 else:2507 result = { 2508 "status" : False,2509 "msg" : "Please check your parameters."2510 }2511 #set log detail2512 user_type = "admin"2513 function_name = "edit_text"2514 request_headers = request.headers2515 params_get = None2516 params_post = params2517 set_api_log(user_type , admin_id , function_name , request_headers , params_get , params_post , result)2518 return result2519def delete_text(request):2520 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false2521 isset_accept = "Accept" in request.headers2522 isset_content_type = "Content-Type" in request.headers2523 isset_token = "Authorization" in request.headers2524 admin_id = None2525 params = json.loads(request.data)2526 #เช็ค parameter ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false2527 isset_app_version = "app_version" in params2528 isset_user_type = "user_type" in params2529 isset_text_code = "text_code" in params2530 if isset_accept and isset_content_type and isset_token and isset_app_version and isset_user_type and isset_text_code:2531 #เช็ค token ว่า expire แล้วหรือยัง2532 token = request.headers['Authorization']2533 check_token = check_token_expire_backend(token)2534 if check_token:2535 admin_info = get_admin_info(token)2536 admin_id = admin_info['_id']['$oid']2537 if params['user_type'] == "customer":2538 with open('static/language/mobile_customer.json', 'r', encoding='utf-8') as json_file:2539 data = json.load(json_file)2540 elif params['user_type'] == "driver":2541 with open('static/language/mobile_driver.json', 'r', encoding='utf-8') as json_file:2542 data = json.load(json_file)2543 else:2544 with open('static/language/web_frontend.json', 'r', encoding='utf-8') as json_file:2545 data = json.load(json_file)2546 #ถ้าเจอ text_code ใน language_data ถึงจะลบได้2547 if params['text_code'] in data['language_data']:2548 #ลบข้อมูล2549 del data['language_data'][params['text_code']]2550 language_all = {2551 "language_list" : data['language_list'],2552 "language_data" : data['language_data']2553 }2554 try:2555 if params['user_type'] == "customer":2556 with open('static/language/mobile_customer.json','w', encoding='utf8') as f: 2557 json.dump(language_all, f, indent=2, ensure_ascii=False)2558 elif params['user_type'] == "driver":2559 with open('static/language/mobile_customer.json','w', encoding='utf8') as f: 2560 json.dump(language_all, f, indent=2, ensure_ascii=False)2561 else:2562 with open('static/language/web_frontend.json','w', encoding='utf8') as f: 2563 json.dump(language_all, f, indent=2, ensure_ascii=False)2564 result = {2565 "status" : True,2566 "msg" : "Delete text success."2567 }2568 except:2569 result = {2570 "status" : False,2571 "msg" : "Delete text failed."2572 }2573 else:2574 result = {2575 "status" : False,2576 "msg" : "Text code not found."2577 }2578 else:2579 result = { 2580 "status" : False,2581 "error_code" : 401,2582 "msg" : "Unauthorized."2583 }2584 else:2585 result = { 2586 "status" : False,2587 "msg" : "Please check your parameters."2588 }2589 #set log detail2590 user_type = "admin"2591 function_name = "delete_text"2592 request_headers = request.headers2593 params_get = None2594 params_post = params2595 set_api_log(user_type , admin_id , function_name , request_headers , params_get , params_post , result)2596 return result2597def communication_list(request):2598 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false2599 isset_accept = "Accept" in request.headers2600 isset_content_type = "Content-Type" in request.headers2601 admin_id = None2602 if isset_accept and isset_content_type:2603 communication = db.communication.find()2604 if communication is None:2605 result = { 2606 "status" : False,2607 "msg" : "Data not found."2608 }2609 else:2610 #เอาค่าที่ได้จาก query มาแปลงจาก object เป็น json2611 communication_object = dumps(communication)2612 communication_json = json.loads(communication_object)2613 communication_list = []2614 for i in range(len(communication_json)):2615 communication_list.append({"id" : communication_json[i]['_id']['$oid'],"lang_name_en": communication_json[i]['lang_name_en'],"lang_name_th": communication_json[i]['lang_name_th'],"lang_code": communication_json[i]['lang_code'],"flag_image": communication_json[i]['flag_image']})2616 result = {2617 "status" : True,2618 "msg" : "Get communication success.",2619 "data" : communication_list2620 }2621 else:2622 result = { 2623 "status" : False,2624 "msg" : "Please check your parameters."2625 }2626 #set log detail2627 user_type = "admin"2628 function_name = "communication_list"2629 request_headers = request.headers2630 params_get = None2631 params_post = None2632 set_api_log(user_type , admin_id , function_name , request_headers , params_get , params_post , result)2633 return result2634def edit_communication(request):2635 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false2636 isset_accept = "Accept" in request.headers2637 isset_content_type = "Content-Type" in request.headers2638 isset_token = "Authorization" in request.headers2639 admin_id = None2640 params = json.loads(request.data)2641 #เช็ค parameter ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false2642 isset_app_version = "app_version" in params2643 isset_communication_id = "communication_id" in params2644 isset_lang_name_en = "lang_name_en" in params2645 isset_lang_name_th = "lang_name_th" in params2646 isset_lang_code = "lang_code" in params2647 isset_flag_image = "flag_image" in params2648 if isset_accept and isset_content_type and isset_token and isset_app_version and isset_communication_id and isset_lang_name_en and isset_lang_name_th and isset_lang_code and isset_flag_image:2649 #เช็ค token ว่า expire แล้วหรือยัง2650 token = request.headers['Authorization']2651 check_token = check_token_expire_backend(token)2652 if check_token:2653 admin_info = get_admin_info(token)2654 admin_id = admin_info['_id']['$oid']2655 check_lang_name = db.communication.find({2656 "$or": [2657 {"lang_name_en": params['lang_name_en'].strip()},2658 {"lang_name_th": params['lang_name_th'].strip()}2659 ],2660 "$and": [2661 {"_id": {"$ne": ObjectId(params['communication_id'])}}2662 ]}).count()2663 if check_lang_name > 0:2664 result = {2665 "status" : False,2666 "msg" : "Communication has been used."2667 }2668 else:2669 #ถ้าไม่มีการแก้ไขรูป flag (flag_image เป็น null) ไม่ต้องอัพเดตรูป 2670 if params['flag_image'] is None:2671 image_name = "flag_"+params['lang_code']+".png"2672 else:2673 #เช็ค path และลบรูปเก่า2674 if os.path.exists("static/images/flag/flag_"+params['lang_code']+".png"):2675 os.remove("static/images/flag/flag_"+params['lang_code']+".png")2676 2677 check_upload_image = upload_flag_image(params['flag_image'], "flag_"+params['lang_code'])2678 if check_upload_image is None:2679 image_name = None2680 else:2681 image_name = check_upload_image2682 # update data2683 where_param = { "_id": ObjectId(params['communication_id']) }2684 value_param = {2685 "$set":2686 {2687 "lang_name_en": params['lang_name_en'].strip(),2688 "lang_name_th": params['lang_name_th'].strip(),2689 "flag_image": image_name,2690 "updated_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S')2691 }2692 }2693 if db.communication.update(where_param , value_param):2694 result = {2695 "status" : True,2696 "msg" : "Edit communication success."2697 }2698 else:2699 result = {2700 "status" : False,2701 "msg" : "Data update failed."2702 }2703 else:2704 result = { 2705 "status" : False,2706 "error_code" : 401,2707 "msg" : "Unauthorized."2708 }2709 else:2710 result = { 2711 "status" : False,2712 "msg" : "Please check your parameters."2713 }2714 #set log detail2715 user_type = "admin"2716 function_name = "edit_communication"2717 request_headers = request.headers2718 params_get = None2719 params_post = params2720 set_api_log(user_type , admin_id , function_name , request_headers , params_get , params_post , result)2721 return result2722def get_contact_us_backend(request):2723 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false2724 isset_accept = "Accept" in request.headers2725 isset_content_type = "Content-Type" in request.headers2726 admin_id = None2727 if isset_accept and isset_content_type:2728 contact_us = db.contact_us.find_one()2729 2730 if contact_us is None:2731 result = { 2732 "status" : False,2733 "msg" : "Data not found."2734 }2735 else:2736 #เอาค่าที่ได้จาก query มาแปลงจาก object เป็น json2737 contact_us_object = dumps(contact_us)2738 contact_us_json = json.loads(contact_us_object)2739 result = {2740 "status" : True,2741 "msg" : "Get contact us success.",2742 "contact_id" : contact_us_json['_id']['$oid'],2743 "contact_address_en" : contact_us_json['contact_address_en'],2744 "contact_address_th" : contact_us_json['contact_address_th'],2745 "contact_email" : contact_us_json['contact_email'],2746 "contact_tel" : contact_us_json['contact_tel']2747 }2748 else:2749 result = { 2750 "status" : False,2751 "msg" : "Please check your parameters."2752 }2753 #set log detail2754 user_type = "admin"2755 function_name = "get_contact_us_backend"2756 request_headers = request.headers2757 params_get = None2758 params_post = None2759 set_api_log(user_type , admin_id , function_name , request_headers , params_get , params_post , result)2760 return result2761def edit_contact_us(request):2762 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false2763 isset_accept = "Accept" in request.headers2764 isset_content_type = "Content-Type" in request.headers2765 isset_token = "Authorization" in request.headers2766 admin_id = None2767 params = json.loads(request.data)2768 #เช็ค parameter ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false2769 isset_app_version = "app_version" in params2770 isset_contact_id = "contact_id" in params2771 isset_contact_address_en = "contact_address_en" in params2772 isset_contact_address_th = "contact_address_th" in params2773 isset_contact_email = "contact_email" in params2774 isset_contact_tel = "contact_tel" in params2775 if isset_accept and isset_content_type and isset_token and isset_app_version and isset_contact_id and isset_contact_address_en and isset_contact_address_th and isset_contact_email and isset_contact_tel:2776 #เช็ค token ว่า expire แล้วหรือยัง2777 token = request.headers['Authorization']2778 check_token = check_token_expire_backend(token)2779 if check_token:2780 admin_info = get_admin_info(token)2781 admin_id = admin_info['_id']['$oid']2782 # update data2783 where_param = { "_id": ObjectId(params['contact_id']) }2784 value_param = {2785 "$set":2786 {2787 "contact_address_en": params['contact_address_en'].strip(),2788 "contact_address_th": params['contact_address_th'].strip(),2789 "contact_email": params['contact_email'].strip(),2790 "contact_tel": params['contact_tel'].strip(),2791 "updated_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S')2792 }2793 }2794 if db.contact_us.update(where_param , value_param):2795 result = {2796 "status" : True,2797 "msg" : "Edit contact us success."2798 }2799 else:2800 result = {2801 "status" : False,2802 "msg" : "Data update failed."2803 }2804 else:2805 result = { 2806 "status" : False,2807 "error_code" : 401,2808 "msg" : "Unauthorized."2809 }2810 else:2811 result = { 2812 "status" : False,2813 "msg" : "Please check your parameters."2814 }2815 #set log detail2816 user_type = "admin"2817 function_name = "edit_contact_us"2818 request_headers = request.headers2819 params_get = None2820 params_post = params2821 set_api_log(user_type , admin_id , function_name , request_headers , params_get , params_post , result)2822 return result2823def contact_topic_list(request):2824 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false2825 isset_accept = "Accept" in request.headers2826 isset_content_type = "Content-Type" in request.headers2827 admin_id = None2828 if isset_accept and isset_content_type:2829 contact_topic = db.contact_topic.find({"topic_status": "1"})2830 if contact_topic is not None:2831 #เอาค่าที่ได้จาก query มาแปลงจาก object เป็น json2832 contact_topic_object = dumps(contact_topic)2833 contact_topic_json = json.loads(contact_topic_object)2834 contact_topic_list = []2835 for i in range(len(contact_topic_json)):2836 if contact_topic_json[i]['topic_status'] == "1":2837 topic_status_text = "เปิดใช้งาน"2838 else:2839 topic_status_text = "ปิดใช้งาน"2840 contact_topic_list.append({2841 "id" : contact_topic_json[i]['_id']['$oid'],2842 "topic_en": contact_topic_json[i]['topic_en'],2843 "topic_th": contact_topic_json[i]['topic_th'],2844 "topic_status": contact_topic_json[i]['topic_status'],2845 "topic_status_text": topic_status_text2846 })2847 result = {2848 "status" : True,2849 "msg" : "Get contact topic success.",2850 "data" : contact_topic_list2851 }2852 else:2853 result = { 2854 "status" : False,2855 "msg" : "Please check your parameters."2856 }2857 #set log detail2858 user_type = "admin"2859 function_name = "contact_topic_list"2860 request_headers = request.headers2861 params_get = None2862 params_post = None2863 set_api_log(user_type , admin_id , function_name , request_headers , params_get , params_post , result)2864 return result2865def add_contact_topic(request):2866 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false2867 isset_accept = "Accept" in request.headers2868 isset_content_type = "Content-Type" in request.headers2869 isset_token = "Authorization" in request.headers2870 admin_id = None2871 params = json.loads(request.data)2872 #เช็ค parameter ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false2873 isset_app_version = "app_version" in params2874 isset_topic_en = "topic_en" in params2875 isset_topic_th = "topic_th" in params2876 if isset_accept and isset_content_type and isset_token and isset_app_version and isset_topic_en and isset_topic_th:2877 #เช็ค token ว่า expire แล้วหรือยัง2878 token = request.headers['Authorization']2879 check_token = check_token_expire_backend(token)2880 if check_token:2881 admin_info = get_admin_info(token)2882 admin_id = admin_info['_id']['$oid']2883 data = { 2884 "topic_en": params['topic_en'].strip(),2885 "topic_th": params['topic_th'].strip(),2886 "topic_status": "1",2887 "created_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S'),2888 "updated_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S')2889 }2890 if db.contact_topic.insert_one(data):2891 result = {2892 "status" : True,2893 "msg" : "Add contact topic success."2894 }2895 else:2896 result = {2897 "status" : False,2898 "msg" : "Data insert failed."2899 }2900 else:2901 result = { 2902 "status" : False,2903 "error_code" : 401,2904 "msg" : "Unauthorized."2905 }2906 else:2907 result = { 2908 "status" : False,2909 "msg" : "Please check your parameters."2910 }2911 #set log detail2912 user_type = "admin"2913 function_name = "add_contact_topic"2914 request_headers = request.headers2915 params_get = None2916 params_post = params2917 set_api_log(user_type , admin_id , function_name , request_headers , params_get , params_post , result)2918 return result2919def edit_contact_topic(request):2920 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false2921 isset_accept = "Accept" in request.headers2922 isset_content_type = "Content-Type" in request.headers2923 isset_token = "Authorization" in request.headers2924 admin_id = None2925 params = json.loads(request.data)2926 #เช็ค parameter ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false2927 isset_app_version = "app_version" in params2928 isset_topic_id = "topic_id" in params2929 isset_topic_en = "topic_en" in params2930 isset_topic_th = "topic_th" in params2931 isset_topic_status = "topic_status" in params2932 if isset_accept and isset_content_type and isset_token and isset_app_version and isset_topic_id and isset_topic_en and isset_topic_th and isset_topic_status:2933 #เช็ค token ว่า expire แล้วหรือยัง2934 token = request.headers['Authorization']2935 check_token = check_token_expire_backend(token)2936 if check_token:2937 admin_info = get_admin_info(token)2938 admin_id = admin_info['_id']['$oid']2939 contact_topic = db.contact_topic.find_one({"_id": ObjectId(params['topic_id'])})2940 2941 if contact_topic is None:2942 result = { 2943 "status" : False,2944 "msg" : "Data not found."2945 }2946 else:2947 #เอาค่าที่ได้จาก query มาแปลงจาก object เป็น json2948 contact_topic_object = dumps(contact_topic)2949 contact_topic_json = json.loads(contact_topic_object)2950 if params['topic_status'] is None:2951 topic_status = contact_topic_json['topic_status']2952 elif params['topic_status'] == "0":2953 topic_status = "0"2954 else:2955 topic_status = "1"2956 # update data2957 where_param = { "_id": ObjectId(params['topic_id']) }2958 value_param = {2959 "$set":2960 {2961 "topic_en": params['topic_en'].strip(),2962 "topic_th": params['topic_th'].strip(),2963 "topic_status": topic_status,2964 "updated_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S')2965 }2966 }2967 if db.contact_topic.update(where_param , value_param):2968 result = {2969 "status" : True,2970 "msg" : "Edit contact topic success."2971 }2972 else:2973 result = {2974 "status" : False,2975 "msg" : "Data update failed."2976 }2977 else:2978 result = { 2979 "status" : False,2980 "error_code" : 401,2981 "msg" : "Unauthorized."2982 }2983 else:2984 result = { 2985 "status" : False,2986 "msg" : "Please check your parameters."2987 }2988 #set log detail2989 user_type = "admin"2990 function_name = "edit_contact_topic"2991 request_headers = request.headers2992 params_get = None2993 params_post = params2994 set_api_log(user_type , admin_id , function_name , request_headers , params_get , params_post , result)2995 return result2996def delete_contact_topic(request):2997 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false2998 isset_accept = "Accept" in request.headers2999 isset_content_type = "Content-Type" in request.headers3000 isset_token = "Authorization" in request.headers3001 admin_id = None3002 params = json.loads(request.data)3003 #เช็ค parameter ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false3004 isset_app_version = "app_version" in params3005 isset_topic_id = "topic_id" in params3006 if isset_accept and isset_content_type and isset_token and isset_app_version and isset_topic_id:3007 #เช็ค token ว่า expire แล้วหรือยัง3008 token = request.headers['Authorization']3009 check_token = check_token_expire_backend(token)3010 if check_token:3011 admin_info = get_admin_info(token)3012 admin_id = admin_info['_id']['$oid']3013 # update data3014 where_param = { "_id": ObjectId(params['topic_id']) }3015 value_param = {3016 "$set":3017 {3018 "topic_status": "0",3019 "updated_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S')3020 }3021 }3022 if db.contact_topic.update(where_param , value_param):3023 result = {3024 "status" : True,3025 "msg" : "Delete contact topic success."3026 }3027 else:3028 result = {3029 "status" : False,3030 "msg" : "Data update failed."3031 }3032 else:3033 result = { 3034 "status" : False,3035 "error_code" : 401,3036 "msg" : "Unauthorized."3037 }3038 else:3039 result = { 3040 "status" : False,3041 "msg" : "Please check your parameters."3042 }3043 #set log detail3044 user_type = "admin"3045 function_name = "delete_contact_topic"3046 request_headers = request.headers3047 params_get = None3048 params_post = params3049 set_api_log(user_type , admin_id , function_name , request_headers , params_get , params_post , result)3050 return result3051def service_rating_question_list(request):3052 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false3053 isset_accept = "Accept" in request.headers3054 isset_content_type = "Content-Type" in request.headers3055 admin_id = None3056 if isset_accept and isset_content_type:3057 service_rating_question = db.service_rating_question.find()3058 if service_rating_question is not None:3059 #เอาค่าที่ได้จาก query มาแปลงจาก object เป็น json3060 service_rating_question_object = dumps(service_rating_question)3061 service_rating_question_json = json.loads(service_rating_question_object)3062 service_rating_question_list = []3063 for i in range(len(service_rating_question_json)):3064 service_rating_question_list.append({"id" : service_rating_question_json[i]['_id']['$oid'],"question_en": service_rating_question_json[i]['question_en'],"question_th": service_rating_question_json[i]['question_th']})3065 result = {3066 "status" : True,3067 "msg" : "Get service rating question success.",3068 "data" : service_rating_question_list3069 }3070 else:3071 result = { 3072 "status" : False,3073 "msg" : "Please check your parameters."3074 }3075 #set log detail3076 user_type = "admin"3077 function_name = "service_rating_question_list"3078 request_headers = request.headers3079 params_get = None3080 params_post = None3081 set_api_log(user_type , admin_id , function_name , request_headers , params_get , params_post , result)3082 return result3083def edit_service_rating_question(request):3084 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false3085 isset_accept = "Accept" in request.headers3086 isset_content_type = "Content-Type" in request.headers3087 isset_token = "Authorization" in request.headers3088 admin_id = None3089 params = json.loads(request.data)3090 #เช็ค parameter ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false3091 isset_app_version = "app_version" in params3092 isset_question_id = "question_id" in params3093 isset_question_en = "question_en" in params3094 isset_question_th = "question_th" in params3095 if isset_accept and isset_content_type and isset_token and isset_app_version and isset_question_id and isset_question_en and isset_question_th:3096 #เช็ค token ว่า expire แล้วหรือยัง3097 token = request.headers['Authorization']3098 check_token = check_token_expire_backend(token)3099 if check_token:3100 admin_info = get_admin_info(token)3101 admin_id = admin_info['_id']['$oid']3102 # update data3103 where_param = { "_id": ObjectId(params['question_id']) }3104 value_param = {3105 "$set":3106 {3107 "question_en": params['question_en'].strip(),3108 "question_th": params['question_th'].strip(),3109 "updated_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S')3110 }3111 }3112 if db.service_rating_question.update(where_param , value_param):3113 result = {3114 "status" : True,3115 "msg" : "Edit service rating question success."3116 }3117 else:3118 result = {3119 "status" : False,3120 "msg" : "Data update failed."3121 }3122 else:3123 result = { 3124 "status" : False,3125 "error_code" : 401,3126 "msg" : "Unauthorized."3127 }3128 else:3129 result = { 3130 "status" : False,3131 "msg" : "Please check your parameters."3132 }3133 #set log detail3134 user_type = "admin"3135 function_name = "edit_service_rating_question"3136 request_headers = request.headers3137 params_get = None3138 params_post = params3139 set_api_log(user_type , admin_id , function_name , request_headers , params_get , params_post , result)3140 return result3141def service_area_list(request):3142 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false3143 isset_accept = "Accept" in request.headers3144 isset_content_type = "Content-Type" in request.headers3145 admin_id = None3146 if isset_accept and isset_content_type:3147 service_area = db.service_area.find()3148 if service_area is None:3149 result = { 3150 "status" : False,3151 "msg" : "Data not found."3152 }3153 else:3154 #เอาค่าที่ได้จาก query มาแปลงจาก object เป็น json3155 service_area_object = dumps(service_area)3156 service_area_json = json.loads(service_area_object)3157 service_area_list = []3158 for i in range(len(service_area_json)):3159 service_area_list.append({"id" : service_area_json[i]['_id']['$oid'],"name_en": service_area_json[i]['service_area_name_en'],"name_th": service_area_json[i]['service_area_name_th']})3160 result = {3161 "status" : True,3162 "msg" : "Get service area success.",3163 "data" : service_area_list3164 }3165 else:3166 result = { 3167 "status" : False,3168 "msg" : "Please check your parameters."3169 }3170 #set log detail3171 user_type = "admin"3172 function_name = "service_area_list"3173 request_headers = request.headers3174 params_get = None3175 params_post = None3176 set_api_log(user_type , admin_id , function_name , request_headers , params_get , params_post , result)3177 return result3178def add_service_area(request):3179 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false3180 isset_accept = "Accept" in request.headers3181 isset_content_type = "Content-Type" in request.headers3182 isset_token = "Authorization" in request.headers3183 admin_id = None3184 params = json.loads(request.data)3185 #เช็ค parameter ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false3186 isset_app_version = "app_version" in params3187 isset_area_name_en = "service_area_name_en" in params3188 isset_area_name_th = "service_area_name_th" in params3189 if isset_accept and isset_content_type and isset_token and isset_app_version and isset_area_name_en and isset_area_name_th:3190 #เช็ค token ว่า expire แล้วหรือยัง3191 token = request.headers['Authorization']3192 check_token = check_token_expire_backend(token)3193 if check_token:3194 admin_info = get_admin_info(token)3195 admin_id = admin_info['_id']['$oid']3196 check_area_name = db.service_area.find({"$or": [{"service_area_name_en": params['service_area_name_en'].strip()},{"service_area_name_th": params['service_area_name_th'].strip()}]}).count()3197 if check_area_name > 0:3198 result = {3199 "status" : False,3200 "msg" : "Service area has been used."3201 }3202 else:3203 data = { 3204 "service_area_name_en": params['service_area_name_en'].strip(),3205 "service_area_name_th": params['service_area_name_th'].strip(),3206 "service_area_status": "1",3207 "created_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S'),3208 "updated_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S')3209 }3210 if db.service_area.insert_one(data):3211 result = {3212 "status" : True,3213 "msg" : "Add service area success."3214 }3215 else:3216 result = {3217 "status" : False,3218 "msg" : "Data insert failed."3219 }3220 else:3221 result = { 3222 "status" : False,3223 "error_code" : 401,3224 "msg" : "Unauthorized."3225 }3226 else:3227 result = { 3228 "status" : False,3229 "msg" : "Please check your parameters."3230 }3231 #set log detail3232 user_type = "admin"3233 function_name = "add_service_area"3234 request_headers = request.headers3235 params_get = None3236 params_post = params3237 set_api_log(user_type , admin_id , function_name , request_headers , params_get , params_post , result)3238 return result3239def edit_service_area(request):3240 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false3241 isset_accept = "Accept" in request.headers3242 isset_content_type = "Content-Type" in request.headers3243 isset_token = "Authorization" in request.headers3244 admin_id = None3245 params = json.loads(request.data)3246 #เช็ค parameter ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false3247 isset_app_version = "app_version" in params3248 isset_area_id = "service_area_id" in params3249 isset_area_name_en = "service_area_name_en" in params3250 isset_area_name_th = "service_area_name_th" in params3251 if isset_accept and isset_content_type and isset_token and isset_app_version and isset_area_id and isset_area_name_en and isset_area_name_th:3252 #เช็ค token ว่า expire แล้วหรือยัง3253 token = request.headers['Authorization']3254 check_token = check_token_expire_backend(token)3255 if check_token:3256 admin_info = get_admin_info(token)3257 admin_id = admin_info['_id']['$oid']3258 check_area_name = db.service_area.find({3259 "$or": [3260 {"service_area_name_en": params['service_area_name_en'].strip()},3261 {"service_area_name_th": params['service_area_name_th'].strip()}3262 ],3263 "$and": [3264 {"_id": {"$ne": ObjectId(params['service_area_id'])}}3265 ]}).count()3266 if check_area_name > 0:3267 result = {3268 "status" : False,3269 "msg" : "Service area has been used."3270 }3271 else:3272 # update data3273 where_param = { "_id": ObjectId(params['service_area_id']) }3274 value_param = {3275 "$set":3276 {3277 "service_area_name_en": params['service_area_name_en'].strip(),3278 "service_area_name_th": params['service_area_name_th'].strip(),3279 "updated_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S')3280 }3281 }3282 if db.service_area.update(where_param , value_param):3283 result = {3284 "status" : True,3285 "msg" : "Edit service area success."3286 }3287 else:3288 result = {3289 "status" : False,3290 "msg" : "Data update failed."3291 }3292 else:3293 result = { 3294 "status" : False,3295 "error_code" : 401,3296 "msg" : "Unauthorized."3297 }3298 else:3299 result = { 3300 "status" : False,3301 "msg" : "Please check your parameters."3302 }3303 #set log detail3304 user_type = "admin"3305 function_name = "edit_service_area"3306 request_headers = request.headers3307 params_get = None3308 params_post = params3309 set_api_log(user_type , admin_id , function_name , request_headers , params_get , params_post , result)3310 return result3311def get_specification_policy_backend(request):3312 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false3313 isset_accept = "Accept" in request.headers3314 isset_content_type = "Content-Type" in request.headers3315 isset_token = "Authorization" in request.headers3316 admin_id = None3317 params = json.loads(request.data)3318 #เช็ค parameter ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false3319 isset_app_version = "app_version" in params3320 isset_user_type = "user_type" in params3321 if isset_accept and isset_content_type and isset_token and isset_app_version and isset_user_type:3322 #เช็ค token ว่า expire แล้วหรือยัง3323 token = request.headers['Authorization']3324 check_token = check_token_expire_backend(token)3325 if check_token:3326 admin_info = get_admin_info(token)3327 admin_id = admin_info['_id']['$oid']3328 specification = db.specification.find_one({"user_type": params['user_type']})3329 3330 if specification is None:3331 result = { 3332 "status" : False,3333 "msg" : "Data not found."3334 }3335 else:3336 #เอาค่าที่ได้จาก query มาแปลงจาก object เป็น json3337 specification_object = dumps(specification)3338 specification_json = json.loads(specification_object)3339 result = {3340 "status" : True,3341 "msg" : "Get specification and policy success.",3342 "user_type" : specification_json['user_type'],3343 "specification_en" : specification_json['specification_en'],3344 "specification_th" : specification_json['specification_th'],3345 "policy_en" : specification_json['policy_en'],3346 "policy_th" : specification_json['policy_th']3347 }3348 else:3349 result = { 3350 "status" : False,3351 "error_code" : 401,3352 "msg" : "Unauthorized."3353 }3354 else:3355 result = { 3356 "status" : False,3357 "msg" : "Please check your parameters."3358 }3359 #set log detail3360 user_type = "admin"3361 function_name = "get_specification_policy_backend"3362 request_headers = request.headers3363 params_get = None3364 params_post = params3365 set_api_log(user_type , admin_id , function_name , request_headers , params_get , params_post , result)3366 return result3367def edit_specification_policy(request):3368 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false3369 isset_accept = "Accept" in request.headers3370 isset_content_type = "Content-Type" in request.headers3371 isset_token = "Authorization" in request.headers3372 admin_id = None3373 params = json.loads(request.data)3374 #เช็ค parameter ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false3375 isset_app_version = "app_version" in params3376 isset_user_type = "user_type" in params3377 isset_specification_en = "specification_en" in params3378 isset_specification_th = "specification_th" in params3379 isset_policy_en = "policy_en" in params3380 isset_policy_th = "policy_th" in params3381 if isset_accept and isset_content_type and isset_token and isset_app_version and isset_user_type and isset_specification_en and isset_specification_th and isset_policy_en and isset_policy_th:3382 #เช็ค token ว่า expire แล้วหรือยัง3383 token = request.headers['Authorization']3384 check_token = check_token_expire_backend(token)3385 if check_token:3386 admin_info = get_admin_info(token)3387 admin_id = admin_info['_id']['$oid']3388 # update data3389 where_param = { "user_type": params['user_type'] }3390 value_param = {3391 "$set":3392 {3393 "specification_en": params['specification_en'].strip(),3394 "specification_th": params['specification_th'].strip(),3395 "policy_en": params['policy_en'].strip(),3396 "policy_th": params['policy_th'].strip(),3397 "updated_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S')3398 }3399 }3400 if db.specification.update(where_param , value_param):3401 result = {3402 "status" : True,3403 "msg" : "Edit specification and policy success."3404 }3405 else:3406 result = {3407 "status" : False,3408 "msg" : "Data update failed."3409 }3410 else:3411 result = { 3412 "status" : False,3413 "error_code" : 401,3414 "msg" : "Unauthorized."3415 }3416 else:3417 result = { 3418 "status" : False,3419 "msg" : "Please check your parameters."3420 }3421 #set log detail3422 user_type = "admin"3423 function_name = "edit_specification_policy"3424 request_headers = request.headers3425 params_get = None3426 params_post = params3427 set_api_log(user_type , admin_id , function_name , request_headers , params_get , params_post , result)3428 return result3429def car_engine_list(request):3430 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false3431 isset_accept = "Accept" in request.headers3432 isset_content_type = "Content-Type" in request.headers3433 admin_id = None3434 if isset_accept and isset_content_type:3435 car_engine = db.car_engine.find()3436 if car_engine is not None:3437 #เอาค่าที่ได้จาก query มาแปลงจาก object เป็น json3438 car_engine_object = dumps(car_engine)3439 car_engine_json = json.loads(car_engine_object)3440 car_engine_list = []3441 for i in range(len(car_engine_json)):3442 if car_engine_json[i]['car_engine_status'] == "1":3443 car_engine_status_text = "เปิดใช้งาน"3444 else:3445 car_engine_status_text = "ปิดใช้งาน"3446 car_engine_list.append({3447 "id" : car_engine_json[i]['_id']['$oid'],3448 "car_engine_en": car_engine_json[i]['car_engine_en'],3449 "car_engine_th": car_engine_json[i]['car_engine_th'],3450 "car_engine_status": car_engine_json[i]['car_engine_status'],3451 "car_engine_status_text": car_engine_status_text3452 })3453 result = {3454 "status" : True,3455 "msg" : "Get car engine success.",3456 "data" : car_engine_list3457 }3458 else:3459 result = { 3460 "status" : False,3461 "msg" : "Please check your parameters."3462 }3463 #set log detail3464 user_type = "admin"3465 function_name = "car_engine_list"3466 request_headers = request.headers3467 params_get = None3468 params_post = None3469 set_api_log(user_type , admin_id , function_name , request_headers , params_get , params_post , result)3470 return result3471def add_car_engine(request):3472 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false3473 isset_accept = "Accept" in request.headers3474 isset_content_type = "Content-Type" in request.headers3475 isset_token = "Authorization" in request.headers3476 admin_id = None3477 params = json.loads(request.data)3478 #เช็ค parameter ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false3479 isset_app_version = "app_version" in params3480 isset_car_engine_en = "car_engine_en" in params3481 isset_car_engine_th = "car_engine_th" in params3482 if isset_accept and isset_content_type and isset_token and isset_app_version and isset_car_engine_en and isset_car_engine_th:3483 #เช็ค token ว่า expire แล้วหรือยัง3484 token = request.headers['Authorization']3485 check_token = check_token_expire_backend(token)3486 if check_token:3487 admin_info = get_admin_info(token)3488 admin_id = admin_info['_id']['$oid']3489 data = { 3490 "car_engine_en": params['car_engine_en'].strip(),3491 "car_engine_th": params['car_engine_th'].strip(),3492 "car_engine_status": "1",3493 "created_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S'),3494 "updated_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S')3495 }3496 if db.car_engine.insert_one(data):3497 result = {3498 "status" : True,3499 "msg" : "Add car engine success."3500 }3501 else:3502 result = {3503 "status" : False,3504 "msg" : "Data insert failed."3505 }3506 else:3507 result = { 3508 "status" : False,3509 "error_code" : 401,3510 "msg" : "Unauthorized."3511 }3512 else:3513 result = { 3514 "status" : False,3515 "msg" : "Please check your parameters."3516 }3517 #set log detail3518 user_type = "admin"3519 function_name = "add_car_engine"3520 request_headers = request.headers3521 params_get = None3522 params_post = params3523 set_api_log(user_type , admin_id , function_name , request_headers , params_get , params_post , result)3524 return result3525def edit_car_engine(request):3526 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false3527 isset_accept = "Accept" in request.headers3528 isset_content_type = "Content-Type" in request.headers3529 isset_token = "Authorization" in request.headers3530 admin_id = None3531 params = json.loads(request.data)3532 #เช็ค parameter ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false3533 isset_app_version = "app_version" in params3534 isset_car_engine_id = "car_engine_id" in params3535 isset_car_engine_en = "car_engine_en" in params3536 isset_car_engine_th = "car_engine_th" in params3537 isset_car_engine_status = "car_engine_status" in params3538 if isset_accept and isset_content_type and isset_token and isset_app_version and isset_car_engine_id and isset_car_engine_en and isset_car_engine_th and isset_car_engine_status:3539 #เช็ค token ว่า expire แล้วหรือยัง3540 token = request.headers['Authorization']3541 check_token = check_token_expire_backend(token)3542 if check_token:3543 admin_info = get_admin_info(token)3544 admin_id = admin_info['_id']['$oid']3545 car_engine = db.car_engine.find_one({"_id": ObjectId(params['car_engine_id'])})3546 3547 if car_engine is None:3548 result = { 3549 "status" : False,3550 "msg" : "Data not found."3551 }3552 else:3553 #เอาค่าที่ได้จาก query มาแปลงจาก object เป็น json3554 car_engine_object = dumps(car_engine)3555 car_engine_json = json.loads(car_engine_object)3556 if params['car_engine_status'] is None:3557 car_engine_status = car_engine_json['car_engine_status']3558 elif params['car_engine_status'] == "0":3559 car_engine_status = "0"3560 else:3561 car_engine_status = "1"3562 # update data3563 where_param = { "_id": ObjectId(params['car_engine_id']) }3564 value_param = {3565 "$set":3566 {3567 "car_engine_en": params['car_engine_en'].strip(),3568 "car_engine_th": params['car_engine_th'].strip(),3569 "car_engine_status": car_engine_status,3570 "updated_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S')3571 }3572 }3573 if db.car_engine.update(where_param , value_param):3574 result = {3575 "status" : True,3576 "msg" : "Edit car engine success."3577 }3578 else:3579 result = {3580 "status" : False,3581 "msg" : "Data update failed."3582 }3583 else:3584 result = { 3585 "status" : False,3586 "error_code" : 401,3587 "msg" : "Unauthorized."3588 }3589 else:3590 result = { 3591 "status" : False,3592 "msg" : "Please check your parameters."3593 }3594 #set log detail3595 user_type = "admin"3596 function_name = "edit_car_engine"3597 request_headers = request.headers3598 params_get = None3599 params_post = params3600 set_api_log(user_type , admin_id , function_name , request_headers , params_get , params_post , result)3601 return result3602def get_vat_rate_backend(request):3603 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false3604 isset_accept = "Accept" in request.headers3605 isset_content_type = "Content-Type" in request.headers3606 isset_token = "Authorization" in request.headers3607 admin_id = None3608 if isset_accept and isset_content_type and isset_token:3609 #เช็ค token ว่า expire แล้วหรือยัง3610 token = request.headers['Authorization']3611 check_token = check_token_expire_backend(token)3612 if check_token:3613 admin_info = get_admin_info(token)3614 admin_id = admin_info['_id']['$oid']3615 vat = db.vat_rate.find_one()3616 3617 if vat is None:3618 result = { 3619 "status" : False,3620 "msg" : "Data not found."3621 }3622 else:3623 #เอาค่าที่ได้จาก query มาแปลงจาก object เป็น json3624 vat_object = dumps(vat)3625 vat_json = json.loads(vat_object)3626 result = {3627 "status" : True,3628 "msg" : "Get vat rate success.",3629 "vat_rate" : vat_json['vat_rate']3630 }3631 else:3632 result = { 3633 "status" : False,3634 "error_code" : 401,3635 "msg" : "Unauthorized."3636 }3637 else:3638 result = { 3639 "status" : False,3640 "msg" : "Please check your parameters."3641 }3642 #set log detail3643 user_type = "admin"3644 function_name = "get_vat_rate_backend"3645 request_headers = request.headers3646 params_get = None3647 params_post = None3648 set_api_log(user_type , admin_id , function_name , request_headers , params_get , params_post , result)3649 return result3650def edit_vat_rate(request):3651 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false3652 isset_accept = "Accept" in request.headers3653 isset_content_type = "Content-Type" in request.headers3654 isset_token = "Authorization" in request.headers3655 admin_id = None3656 params = json.loads(request.data)3657 #เช็ค parameter ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false3658 isset_app_version = "app_version" in params3659 isset_vat_rate = "vat_rate" in params3660 if isset_accept and isset_content_type and isset_token and isset_app_version and isset_vat_rate:3661 #เช็ค token ว่า expire แล้วหรือยัง3662 token = request.headers['Authorization']3663 check_token = check_token_expire_backend(token)3664 if check_token:3665 admin_info = get_admin_info(token)3666 admin_id = admin_info['_id']['$oid']3667 3668 try:3669 vat_rate = float(params['vat_rate'])3670 check_vat_rate = True3671 except ValueError:3672 check_vat_rate = False3673 if not check_vat_rate:3674 result = { 3675 "status" : False,3676 "msg" : "Vat rate is not a number."3677 }3678 else:3679 # update data3680 where_param = { "vat_rate": {"$gt" : 0} }3681 value_param = {3682 "$set":3683 {3684 "vat_rate": vat_rate,3685 "updated_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S')3686 }3687 }3688 if db.vat_rate.update(where_param , value_param):3689 result = {3690 "status" : True,3691 "msg" : "Edit vat rate success."3692 }3693 else:3694 result = {3695 "status" : False,3696 "msg" : "Data update failed."3697 }3698 else:3699 result = { 3700 "status" : False,3701 "error_code" : 401,3702 "msg" : "Unauthorized."3703 }3704 else:3705 result = { 3706 "status" : False,3707 "msg" : "Please check your parameters."3708 }3709 #set log detail3710 user_type = "admin"3711 function_name = "edit_vat_rate"3712 request_headers = request.headers3713 params_get = None3714 params_post = params3715 set_api_log(user_type , admin_id , function_name , request_headers , params_get , params_post , result)3716 return result3717def request_driver_remark_list(request):3718 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false3719 isset_accept = "Accept" in request.headers3720 isset_content_type = "Content-Type" in request.headers3721 admin_id = None3722 if isset_accept and isset_content_type:3723 remark = db.request_driver_remark.find()3724 if remark is not None:3725 #เอาค่าที่ได้จาก query มาแปลงจาก object เป็น json3726 remark_object = dumps(remark)3727 remark_json = json.loads(remark_object)3728 remark_list = []3729 for i in range(len(remark_json)):3730 if remark_json[i]['remark_status'] == "1":3731 remark_status_text = "เปิดใช้งาน"3732 else:3733 remark_status_text = "ปิดใช้งาน"3734 remark_list.append({3735 "id" : remark_json[i]['_id']['$oid'],3736 "remark_en": remark_json[i]['remark_en'],3737 "remark_th": remark_json[i]['remark_th'],3738 "remark_status": remark_json[i]['remark_status'],3739 "remark_status_text": remark_status_text3740 })3741 result = {3742 "status" : True,3743 "msg" : "Get request driver remark success.",3744 "data" : remark_list3745 }3746 else:3747 result = { 3748 "status" : False,3749 "msg" : "Please check your parameters."3750 }3751 #set log detail3752 user_type = "admin"3753 function_name = "request_driver_remark_list"3754 request_headers = request.headers3755 params_get = None3756 params_post = None3757 set_api_log(user_type , admin_id , function_name , request_headers , params_get , params_post , result)3758 return result3759def add_request_driver_remark(request):3760 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false3761 isset_accept = "Accept" in request.headers3762 isset_content_type = "Content-Type" in request.headers3763 isset_token = "Authorization" in request.headers3764 admin_id = None3765 params = json.loads(request.data)3766 #เช็ค parameter ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false3767 isset_app_version = "app_version" in params3768 isset_remark_en = "remark_en" in params3769 isset_remark_th = "remark_th" in params3770 if isset_accept and isset_content_type and isset_token and isset_app_version and isset_remark_en and isset_remark_th:3771 #เช็ค token ว่า expire แล้วหรือยัง3772 token = request.headers['Authorization']3773 check_token = check_token_expire_backend(token)3774 if check_token:3775 admin_info = get_admin_info(token)3776 admin_id = admin_info['_id']['$oid']3777 data = { 3778 "remark_en": params['remark_en'].strip(),3779 "remark_th": params['remark_th'].strip(),3780 "remark_status": "1",3781 "created_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S'),3782 "updated_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S')3783 }3784 if db.request_driver_remark.insert_one(data):3785 result = {3786 "status" : True,3787 "msg" : "Add request driver remark success."3788 }3789 else:3790 result = {3791 "status" : False,3792 "msg" : "Data insert failed."3793 }3794 else:3795 result = { 3796 "status" : False,3797 "error_code" : 401,3798 "msg" : "Unauthorized."3799 }3800 else:3801 result = { 3802 "status" : False,3803 "msg" : "Please check your parameters."3804 }3805 #set log detail3806 user_type = "admin"3807 function_name = "add_request_driver_remark"3808 request_headers = request.headers3809 params_get = None3810 params_post = params3811 set_api_log(user_type , admin_id , function_name , request_headers , params_get , params_post , result)3812 return result3813def edit_request_driver_remark(request):3814 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false3815 isset_accept = "Accept" in request.headers3816 isset_content_type = "Content-Type" in request.headers3817 isset_token = "Authorization" in request.headers3818 admin_id = None3819 params = json.loads(request.data)3820 #เช็ค parameter ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false3821 isset_app_version = "app_version" in params3822 isset_remark_id = "remark_id" in params3823 isset_remark_en = "remark_en" in params3824 isset_remark_th = "remark_th" in params3825 isset_remark_status = "remark_status" in params3826 if isset_accept and isset_content_type and isset_token and isset_app_version and isset_remark_id and isset_remark_en and isset_remark_th and isset_remark_status:3827 #เช็ค token ว่า expire แล้วหรือยัง3828 token = request.headers['Authorization']3829 check_token = check_token_expire_backend(token)3830 if check_token:3831 admin_info = get_admin_info(token)3832 admin_id = admin_info['_id']['$oid']3833 remark = db.request_driver_remark.find_one({"_id": ObjectId(params['remark_id'])})3834 3835 if remark is None:3836 result = { 3837 "status" : False,3838 "msg" : "Data not found."3839 }3840 else:3841 #เอาค่าที่ได้จาก query มาแปลงจาก object เป็น json3842 remark_object = dumps(remark)3843 remark_json = json.loads(remark_object)3844 if params['remark_status'] is None:3845 remark_status = remark_json['remark_status']3846 elif params['remark_status'] == "0":3847 remark_status = "0"3848 else:3849 remark_status = "1"3850 # update data3851 where_param = { "_id": ObjectId(params['remark_id']) }3852 value_param = {3853 "$set":3854 {3855 "remark_en": params['remark_en'].strip(),3856 "remark_th": params['remark_th'].strip(),3857 "remark_status": remark_status,3858 "updated_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S')3859 }3860 }3861 if db.request_driver_remark.update(where_param , value_param):3862 result = {3863 "status" : True,3864 "msg" : "Edit request driver remark success."3865 }3866 else:3867 result = {3868 "status" : False,3869 "msg" : "Data update failed."3870 }3871 else:3872 result = { 3873 "status" : False,3874 "error_code" : 401,3875 "msg" : "Unauthorized."3876 }3877 else:3878 result = { 3879 "status" : False,3880 "msg" : "Please check your parameters."3881 }3882 #set log detail3883 user_type = "admin"3884 function_name = "edit_request_driver_remark"3885 request_headers = request.headers3886 params_get = None3887 params_post = params3888 set_api_log(user_type , admin_id , function_name , request_headers , params_get , params_post , result)3889 return result3890#add -- add special skill3891def special_skill_list(request):3892 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false3893 isset_accept = "Accept" in request.headers3894 isset_content_type = "Content-Type" in request.headers3895 admin_id = None3896 if isset_accept and isset_content_type:3897 special_skill = db.special_skill.find()3898 if special_skill is not None:3899 #เอาค่าที่ได้จาก query มาแปลงจาก object เป็น json3900 special_skill_object = dumps(special_skill)3901 special_skill_json = json.loads(special_skill_object)3902 special_skill_list = []3903 for i in range(len(special_skill_json)):3904 if special_skill_json[i]['skill_status'] == "1":3905 skill_status_text = "เปิดใช้งาน"3906 else:3907 skill_status_text = "ปิดใช้งาน"3908 special_skill_list.append({3909 "id" : special_skill_json[i]['_id']['$oid'],3910 "skill_en": special_skill_json[i]['skill_en'],3911 "skill_th": special_skill_json[i]['skill_th'],3912 "skill_status": special_skill_json[i]['skill_status'],3913 "skill_status_text": skill_status_text3914 })3915 result = {3916 "status" : True,3917 "msg" : "Get special skill success.",3918 "data" : special_skill_list3919 }3920 else:3921 result = { 3922 "status" : False,3923 "msg" : "Please check your parameters."3924 }3925 #set log detail3926 user_type = "admin"3927 function_name = "special_skill_list"3928 request_headers = request.headers3929 params_get = None3930 params_post = None3931 set_api_log(user_type , admin_id , function_name , request_headers , params_get , params_post , result)3932 return result3933def add_special_skill(request):3934 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false3935 isset_accept = "Accept" in request.headers3936 isset_content_type = "Content-Type" in request.headers3937 isset_token = "Authorization" in request.headers3938 admin_id = None3939 params = json.loads(request.data)3940 #เช็ค parameter ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false3941 isset_app_version = "app_version" in params3942 isset_skill_en = "skill_en" in params3943 isset_skill_th = "skill_th" in params3944 if isset_accept and isset_content_type and isset_token and isset_app_version and isset_skill_en and isset_skill_th:3945 #เช็ค token ว่า expire แล้วหรือยัง3946 token = request.headers['Authorization']3947 check_token = check_token_expire_backend(token)3948 if check_token:3949 admin_info = get_admin_info(token)3950 admin_id = admin_info['_id']['$oid']3951 data = { 3952 "skill_en": params['skill_en'].strip(),3953 "skill_th": params['skill_th'].strip(),3954 "skill_status": "1",3955 "created_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S'),3956 "updated_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S')3957 }3958 if db.special_skill.insert_one(data):3959 result = {3960 "status" : True,3961 "msg" : "Add special skill success."3962 }3963 else:3964 result = {3965 "status" : False,3966 "msg" : "Data insert failed."3967 }3968 else:3969 result = { 3970 "status" : False,3971 "error_code" : 401,3972 "msg" : "Unauthorized."3973 }3974 else:3975 result = { 3976 "status" : False,3977 "msg" : "Please check your parameters."3978 }3979 #set log detail3980 user_type = "admin"3981 function_name = "add_special_skill"3982 request_headers = request.headers3983 params_get = None3984 params_post = params3985 set_api_log(user_type , admin_id , function_name , request_headers , params_get , params_post , result)3986 return result3987def edit_special_skill(request):3988 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false3989 isset_accept = "Accept" in request.headers3990 isset_content_type = "Content-Type" in request.headers3991 isset_token = "Authorization" in request.headers3992 admin_id = None3993 params = json.loads(request.data)3994 #เช็ค parameter ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false3995 isset_app_version = "app_version" in params3996 isset_skill_id = "skill_id" in params3997 isset_skill_en = "skill_en" in params3998 isset_skill_th = "skill_th" in params3999 isset_skill_status = "skill_status" in params4000 if isset_accept and isset_content_type and isset_token and isset_app_version and isset_skill_id and isset_skill_en and isset_skill_th and isset_skill_status:4001 #เช็ค token ว่า expire แล้วหรือยัง4002 token = request.headers['Authorization']4003 check_token = check_token_expire_backend(token)4004 if check_token:4005 admin_info = get_admin_info(token)4006 admin_id = admin_info['_id']['$oid']4007 special_skill = db.special_skill.find_one({"_id": ObjectId(params['skill_id'])})4008 4009 if special_skill is None:4010 result = { 4011 "status" : False,4012 "msg" : "Data not found."4013 }4014 else:4015 #เอาค่าที่ได้จาก query มาแปลงจาก object เป็น json4016 special_skill_object = dumps(special_skill)4017 special_skill_json = json.loads(special_skill_object)4018 if params['skill_status'] is None:4019 skill_status = special_skill_json['skill_status']4020 elif params['skill_status'] == "0":4021 skill_status = "0"4022 else:4023 skill_status = "1"4024 # update data4025 where_param = { "_id": ObjectId(params['skill_id']) }4026 value_param = {4027 "$set":4028 {4029 "skill_en": params['skill_en'].strip(),4030 "skill_th": params['skill_th'].strip(),4031 "skill_status": skill_status,4032 "updated_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S')4033 }4034 }4035 if db.special_skill.update(where_param , value_param):4036 result = {4037 "status" : True,4038 "msg" : "Edit special skill success."4039 }4040 else:4041 result = {4042 "status" : False,4043 "msg" : "Data update failed."4044 }4045 else:4046 result = { 4047 "status" : False,4048 "error_code" : 401,4049 "msg" : "Unauthorized."4050 }4051 else:4052 result = { 4053 "status" : False,4054 "msg" : "Please check your parameters."4055 }4056 #set log detail4057 user_type = "admin"4058 function_name = "edit_special_skill"4059 request_headers = request.headers4060 params_get = None4061 params_post = params4062 set_api_log(user_type , admin_id , function_name , request_headers , params_get , params_post , result)4063 return result4064def delete_special_skill(request):4065 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false4066 isset_accept = "Accept" in request.headers4067 isset_content_type = "Content-Type" in request.headers4068 isset_token = "Authorization" in request.headers4069 admin_id = None4070 params = json.loads(request.data)4071 #เช็ค parameter ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false4072 isset_app_version = "app_version" in params4073 isset_skill_id = "skill_id" in params4074 if isset_accept and isset_content_type and isset_token and isset_app_version and isset_skill_id:4075 #เช็ค token ว่า expire แล้วหรือยัง4076 token = request.headers['Authorization']4077 check_token = check_token_expire_backend(token)4078 if check_token:4079 admin_info = get_admin_info(token)4080 admin_id = admin_info['_id']['$oid']4081 # update data4082 where_param = { "_id": ObjectId(params['skill_id']) }4083 value_param = {4084 "$set":4085 {4086 "skill_status": "0",4087 "updated_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S')4088 }4089 }4090 if db.special_skill.update(where_param , value_param):4091 result = {4092 "status" : True,4093 "msg" : "Delete special skill success."4094 }4095 else:4096 result = {4097 "status" : False,4098 "msg" : "Data update failed."4099 }4100 else:4101 result = { 4102 "status" : False,4103 "error_code" : 401,4104 "msg" : "Unauthorized."4105 }4106 else:4107 result = { 4108 "status" : False,4109 "msg" : "Please check your parameters."4110 }4111 #set log detail4112 user_type = "admin"4113 function_name = "delete_special_skill"4114 request_headers = request.headers4115 params_get = None4116 params_post = params4117 set_api_log(user_type , admin_id , function_name , request_headers , params_get , params_post , result)...

Full Screen

Full Screen

login.py

Source:login.py Github

copy

Full Screen

1from connections.connect_mongo import db2from function.jsonencoder import json_encoder3from function.notification import send_push_message4from function.checktokenexpire import check_token_expire , check_token_expire_backend5from function.getmemberinfo import *6from function.api import *7from bson.objectid import ObjectId8from bson.json_util import loads , dumps9from datetime import datetime , date , timedelta10import sys11import json12import random13import string14import hashlib15import re16import os17from flask import render_template18from flask_mail import Mail, Message19from modules.upload_image import upload_profile_image20from modules.send_email import send_email21def testlogin():22 array = list(db.user.find())23 return json_encoder(array)24def login(request):25 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false26 isset_accept = "Accept" in request.headers27 isset_content_type = "Content-Type" in request.headers28 member_id = None29 member_type = None30 member_lang = None31 params = json.loads(request.data)32 #เช็ค parameter ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false33 isset_app_version = "app_version" in params34 isset_os_type = "os_type" in params35 isset_username = "member_username" in params36 isset_password = "member_password" in params37 isset_noti_key = "noti_key" in params38 isset_user_type = "user_type" in params39 if isset_accept and isset_content_type and isset_app_version and isset_os_type and isset_username and isset_password and isset_noti_key and isset_user_type:40 if params['user_type'] == "customer" or params['user_type'] == "web":41 check_username = db.member.find_one({42 "member_username": params['member_username'].strip().lower(),43 "member_type": "customer",44 "activated_at": {"$ne": None}45 })46 else:47 check_username = db.member.find_one({48 "member_username": params['member_username'].strip().lower(),49 "member_type": "driver"50 })51 if check_username is None:52 result = { 53 "status" : False,54 "username_invalid" : False,55 "password_invalid" : False,56 "msg" : get_api_message("login" , "username_not_found" , member_lang)57 }58 else:59 #เอาค่าที่ได้จาก query มาแปลงจาก object เป็น json60 member_object = dumps(check_username)61 member_json = json.loads(member_object)62 member_id = member_json['_id']['$oid']63 member_type = member_json['member_type']64 member_lang = member_json['member_lang']65 #เอา password ที่รับมาเข้ารหัส66 hash_input_pass = hashlib.md5(params['member_password'].encode())67 hash_pass = hash_input_pass.hexdigest()68 #ถ้า password ตรงกัน69 if member_json['member_password'] == hash_pass:70 # update member_token, noti_key71 where_param = { "_id": ObjectId(member_json['_id']['$oid']) }72 #ถ้า member_token ใน tb เป็น null73 if member_json['member_token'] is None:74 #generate token75 token = get_random_token(40)76 #ถ้าค่า noti_key ใน tb เป็น null77 if member_json['noti_key'] is None:78 #ถ้าค่า noti_key ที่ส่งเข้ามาเป็น null ให้อัพเดตเป็น null79 if params['noti_key'] is None:80 noti_key = None81 #ถ้าค่า noti_key ที่ส่งเข้ามาไม่ใช่ null ให้อัพเดตเป็นค่า noti_key ที่ส่งเข้ามา82 else:83 noti_key = params['noti_key']84 #ถ้าค่า noti_key ใน tb ไม่ใช่ null ให้อัพเดตเป็นค่า noti_key เป็นค่าเดิมใน tb85 else:86 #noti_key = params['noti_key']87 #ถ้าค่า noti_key ที่ส่งเข้ามาเป็น null ให้อัพเดตเป็น null88 if params['noti_key'] is None:89 noti_key = None90 elif member_json['noti_key'] == params['noti_key']:91 noti_key = member_json['noti_key']92 #ถ้าค่า noti_key ที่ส่งเข้ามาไม่ใช่ null ให้อัพเดตเป็นค่า noti_key ที่ส่งเข้ามา93 else:94 noti_key = params['noti_key']95 #ถ้า member_token ใน tb ไม่ใช่ null96 else:97 #ถ้าค่า noti_key ใน tb เป็น null98 if member_json['noti_key'] is None:99 #generate token100 token = get_random_token(40)101 #ถ้าค่า noti_key ที่ส่งเข้ามาเป็น null ให้อัพเดตเป็น null102 if params['noti_key'] is None:103 noti_key = None104 #ถ้าค่า noti_key ที่ส่งเข้ามาไม่ใช่ null ให้อัพเดตเป็นค่า noti_key ที่ส่งเข้ามา105 else:106 noti_key = params['noti_key']107 #ถ้าค่า noti_key ใน tb ไม่ใช่ null108 else:109 #ถ้า noti_key เป็นค่าเดิม ไม่ต้องอัพเดต member_token110 if member_json['noti_key'] == params['noti_key']:111 token = member_json['member_token']112 noti_key = member_json['noti_key']113 #ถ้า noti_key เป็นค่าใหม่ ให้อัพเดต member_token และส่ง noti ไปหา noti_key ค่าเก่า114 else:115 #generate token116 token = get_random_token(40)117 #ถ้าค่า noti_key ที่ส่งเข้ามาเป็น null ให้อัพเดตเป็นค่า null118 if params['noti_key'] is None:119 noti_key = None120 #ถ้าค่า noti_key ที่ส่งเข้ามาไม่ใช่ null ให้อัพเดตเป็นค่า noti_key ที่ส่งเข้ามา121 else:122 noti_key = params['noti_key']123 # ส่ง noti หา noti_key ค่าเก่า124 send_noti_key = member_json['noti_key']125 send_noti_title = "There are other users logged in."126 send_noti_message = "Please login again later."127 send_noti_data = { "action" : "logout" }128 send_noti_badge = 1129 try:130 send_push_message(send_noti_key , send_noti_title , send_noti_message , send_noti_data , send_noti_badge)131 send_status = True132 except:133 send_status = False 134 value_param = {135 "$set":136 {137 "member_token": token,138 "noti_key": noti_key,139 "os_type": params['os_type'],140 "last_active": datetime.now().strftime('%Y-%m-%d %H:%M:%S'),141 "updated_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S')142 }143 }144 if db.member.update(where_param , value_param):145 if params['noti_key'] is not None:146 #เช็คว่าถ้ามี user ที่ใช้ noti_key เดียวกันอยู่ ให้ logout user อื่นออกจากระบบ147 check_noti_key = db.member.find({148 "member_username": {"$ne": params['member_username'].strip().lower()},149 "noti_key": params['noti_key']150 })151 if check_noti_key is not None:152 #เอาค่าที่ได้จาก query มาแปลงจาก object เป็น json153 mem_object = dumps(check_noti_key)154 mem_json = json.loads(mem_object)155 for i in range(len(mem_json)):156 #update member_token เป็น null เพื่อเตะ user ที่ใช้งานอยู่ออกจากระบบ157 where_param_2 = { "_id": ObjectId(mem_json[i]['_id']['$oid']) }158 value_param_2 = {159 "$set":160 {161 "member_token": None,162 "noti_key": None,163 "updated_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S')164 }165 }166 db.member.update(where_param_2 , value_param_2)167 result = {168 "status" : True,169 "msg" : get_api_message("login" , "login_success" , member_lang),170 "token" : token171 }172 else:173 result = {174 "status" : False,175 "msg" : get_api_message("login" , "data_update_failed" , member_lang)176 }177 else:178 result = {179 "status" : False,180 "username_invalid" : True,181 "password_invalid" : False,182 "msg" : get_api_message("login" , "password_invalid" , member_lang)183 }184 else:185 result = { 186 "status" : False,187 "msg" : get_api_message("all" , "please_check_your_parameters")188 }189 #set log detail190 user_type = member_type191 function_name = "login"192 request_headers = request.headers193 params_get = None194 params_post = params195 set_api_log(user_type , member_id , function_name , request_headers , params_get , params_post , result)196 return result197def login_social(request):198 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false199 isset_accept = "Accept" in request.headers200 isset_content_type = "Content-Type" in request.headers201 member_id = None202 member_type = None203 member_lang = None204 params = json.loads(request.data)205 #เช็ค parameter ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false206 isset_app_version = "app_version" in params207 isset_os_type = "os_type" in params208 isset_social_type = "social_type" in params209 isset_social_id = "social_id" in params210 isset_noti_key = "noti_key" in params211 if isset_accept and isset_content_type and isset_app_version and isset_os_type and isset_social_type and isset_social_id and isset_noti_key:212 if params['social_type'] == "line":213 check_social_id = db.member.find_one({214 "member_type": "customer",215 "social_type": "line",216 "social_id": params['social_id']217 })218 if check_social_id is None:219 result = { 220 "status" : False,221 "social_type_invalid" : True,222 "social_id_invalid" : False,223 "msg" : get_api_message("login_social" , "social_id_not_found" , member_lang)224 }225 else:226 #เอาค่าที่ได้จาก query มาแปลงจาก object เป็น json227 member_object = dumps(check_social_id)228 member_json = json.loads(member_object)229 member_id = member_json['_id']['$oid']230 member_type = member_json['member_type']231 member_lang = member_json['member_lang']232 233 # update member_token, noti_key234 where_param = { "_id": ObjectId(member_json['_id']['$oid']) }235 #ถ้า member_token ใน tb เป็น null236 if member_json['member_token'] is None:237 #generate token238 token = get_random_token(40)239 #ถ้าค่า noti_key ใน tb เป็น null240 if member_json['noti_key'] is None:241 #ถ้าค่า noti_key ที่ส่งเข้ามาเป็น null ให้อัพเดตเป็น null242 if params['noti_key'] is None:243 noti_key = None244 #ถ้าค่า noti_key ที่ส่งเข้ามาไม่ใช่ null ให้อัพเดตเป็นค่า noti_key ที่ส่งเข้ามา245 else:246 noti_key = params['noti_key']247 #ถ้าค่า noti_key ใน tb ไม่ใช่ null ให้อัพเดตเป็นค่า noti_key เป็นค่าเดิมใน tb248 else:249 #noti_key = params['noti_key']250 #ถ้าค่า noti_key ที่ส่งเข้ามาเป็น null ให้อัพเดตเป็น null251 if params['noti_key'] is None:252 noti_key = None253 elif member_json['noti_key'] == params['noti_key']:254 noti_key = member_json['noti_key']255 #ถ้าค่า noti_key ที่ส่งเข้ามาไม่ใช่ null ให้อัพเดตเป็นค่า noti_key ที่ส่งเข้ามา256 else:257 noti_key = params['noti_key']258 #ถ้า member_token ใน tb ไม่ใช่ null259 else:260 #ถ้าค่า noti_key ใน tb เป็น null261 if member_json['noti_key'] is None:262 #generate token263 token = get_random_token(40)264 #ถ้าค่า noti_key ที่ส่งเข้ามาเป็น null ให้อัพเดตเป็น null265 if params['noti_key'] is None:266 noti_key = None267 #ถ้าค่า noti_key ที่ส่งเข้ามาไม่ใช่ null ให้อัพเดตเป็นค่า noti_key ที่ส่งเข้ามา268 else:269 noti_key = params['noti_key']270 #ถ้าค่า noti_key ใน tb ไม่ใช่ null271 else:272 #ถ้า noti_key เป็นค่าเดิม ไม่ต้องอัพเดต member_token273 if member_json['noti_key'] == params['noti_key']:274 token = member_json['member_token']275 noti_key = member_json['noti_key']276 #ถ้า noti_key เป็นค่าใหม่ ให้อัพเดต member_token และส่ง noti ไปหา noti_key ค่าเก่า277 else:278 #generate token279 token = get_random_token(40)280 #ถ้าค่า noti_key ที่ส่งเข้ามาเป็น null ให้อัพเดตเป็นค่า null281 if params['noti_key'] is None:282 noti_key = None283 #ถ้าค่า noti_key ที่ส่งเข้ามาไม่ใช่ null ให้อัพเดตเป็นค่า noti_key ที่ส่งเข้ามา284 else:285 noti_key = params['noti_key']286 # ส่ง noti หา noti_key ค่าเก่า287 send_noti_key = member_json['noti_key']288 send_noti_title = "There are other users logged in."289 send_noti_message = "Please login again later."290 send_noti_data = { "action" : "logout" }291 send_noti_badge = 1292 try:293 send_push_message(send_noti_key , send_noti_title , send_noti_message , send_noti_data , send_noti_badge)294 send_status = True295 except:296 send_status = False 297 value_param = {298 "$set":299 {300 "member_token": token,301 "noti_key": noti_key,302 "os_type": params['os_type'],303 "last_active": datetime.now().strftime('%Y-%m-%d %H:%M:%S'),304 "updated_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S')305 }306 }307 if db.member.update(where_param , value_param):308 result = {309 "status" : True,310 "msg" : get_api_message("login_social" , "login_success" , member_lang),311 "token" : token312 }313 else:314 result = {315 "status" : False,316 "msg" : get_api_message("login_social" , "data_update_failed" , member_lang)317 } 318 else:319 result = {320 "status" : False,321 "social_type_invalid" : False,322 "social_id_invalid" : False,323 "msg" : get_api_message("login_social" , "social_type_is_invalid" , member_lang)324 }325 else:326 result = { 327 "status" : False,328 "msg" : get_api_message("all" , "please_check_your_parameters")329 }330 #set log detail331 user_type = member_type332 function_name = "login_social"333 request_headers = request.headers334 params_get = None335 params_post = params336 set_api_log(user_type , member_id , function_name , request_headers , params_get , params_post , result)337 return result338def logout(request):339 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false340 isset_accept = "Accept" in request.headers341 isset_content_type = "Content-Type" in request.headers342 isset_token = "Authorization" in request.headers343 member_id = None344 member_type = None345 if isset_accept and isset_content_type and isset_token:346 #เช็ค token ว่า expire แล้วหรือยัง347 token = request.headers['Authorization']348 check_token = check_token_expire(token)349 if check_token:350 member = db.member.find_one({"member_token": token})351 352 if member is None:353 result = {"status" : False}354 else:355 #เอาค่าที่ได้จาก query มาแปลงจาก object เป็น json356 member_object = dumps(member)357 member_json = json.loads(member_object)358 member_id = member_json['_id']['$oid']359 member_type = member_json['member_type']360 member_lang = member_json['member_lang']361 # update member_token, noti_key362 where_param = { "_id": ObjectId(member_json['_id']['$oid']) }363 value_param = {364 "$set":365 {366 "member_token": None,367 "noti_key": None,368 "last_active": datetime.now().strftime('%Y-%m-%d %H:%M:%S'),369 "updated_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S')370 }371 }372 373 if db.member.update(where_param , value_param):374 result = {375 "status" : True,376 "msg" : get_api_message("logout" , "logout_success" , member_lang)377 }378 else:379 result = {380 "status" : False,381 "msg" : get_api_message("logout" , "data_update_failed" , member_lang)382 }383 else:384 result = { 385 "status" : False,386 "error_code" : 401,387 "msg" : get_api_message("all" , "unauthorized")388 }389 else:390 result = { 391 "status" : False,392 "msg" : get_api_message("all" , "please_check_your_parameters")393 }394 #set log detail395 user_type = member_type396 function_name = "logout"397 request_headers = request.headers398 params_get = None399 params_post = None400 set_api_log(user_type , member_id , function_name , request_headers , params_get , params_post , result)401 return result402def check_token(request):403 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false404 isset_accept = "Accept" in request.headers405 isset_content_type = "Content-Type" in request.headers406 isset_token = "Authorization" in request.headers407 member_id = None408 member_type = None409 if isset_accept and isset_content_type and isset_token:410 #เช็ค token ว่า expire แล้วหรือยัง411 token = request.headers['Authorization']412 check_token = check_token_expire(token)413 if check_token:414 member_info = get_member_info(token)415 member_id = member_info['_id']['$oid']416 member_type = member_info['member_type']417 member = db.member.find_one({"member_token": token})418 if member is None:419 result = {420 "status" : False,421 "msg" : "False"422 }423 else:424 result = {425 "status" : True,426 "msg" : "True"427 }428 else:429 result = { 430 "status" : False,431 "error_code" : 401,432 "msg" : get_api_message("all" , "unauthorized")433 }434 else:435 result = { 436 "status" : False,437 "msg" : get_api_message("all" , "please_check_your_parameters")438 }439 #set log detail440 user_type = member_type441 function_name = "check_token"442 request_headers = request.headers443 params_get = None444 params_post = None445 set_api_log(user_type , member_id , function_name , request_headers , params_get , params_post , result)446 return result447def change_password(request):448 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false449 isset_accept = "Accept" in request.headers450 isset_content_type = "Content-Type" in request.headers451 isset_token = "Authorization" in request.headers452 member_id = None453 member_type = None454 params = json.loads(request.data)455 #เช็ค parameter ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false456 isset_app_version = "app_version" in params457 isset_current_password = "current_password" in params458 isset_new_password = "new_password" in params459 isset_confirm_password = "confirm_password" in params460 if isset_accept and isset_content_type and isset_token and isset_app_version and isset_current_password and isset_new_password and isset_confirm_password:461 #เช็ค token ว่า expire แล้วหรือยัง462 token = request.headers['Authorization']463 check_token = check_token_expire(token)464 if check_token:465 member_info = get_member_info(token)466 member_id = member_info['_id']['$oid']467 member_type = member_info['member_type']468 member_lang = member_info['member_lang']469 470 check_member = db.member.find_one({"member_token": token})471 if check_member is None:472 result = { 473 "status" : False,474 "msg" : get_api_message("change_password" , "data_not_found" , member_lang)475 }476 else:477 #เอาค่าที่ได้จาก query มาแปลงจาก object เป็น json478 member_object = dumps(check_member)479 member_json = json.loads(member_object)480 #เอา current password ที่รับมาเข้ารหัส481 hash_input_pass = hashlib.md5(params['current_password'].encode())482 current_password = hash_input_pass.hexdigest()483 #เช็คว่ารหัสผ่านตรงกันหรือไม่484 if current_password != member_json['member_password']:485 result = { 486 "status" : False,487 "msg" : get_api_message("change_password" , "current_password_is_incorrect" , member_lang)488 }489 else:490 #check new password & confirm password491 if params['new_password']!=params['confirm_password']:492 result = { 493 "status" : False,494 "msg" : get_api_message("change_password" , "new_password_do_not_match" , member_lang)495 }496 else:497 count_password = len(params['new_password'])498 if count_password < 6:499 result = {500 "status" : False,501 "msg" : get_api_message("change_password" , "new_password_less_than_6_character" , member_lang)502 }503 else:504 if params['new_password'] == params['current_password']:505 result = {506 "status" : False,507 "msg" : get_api_message("change_password" , "new_password_can_not_be_the_same_as_your_current_password" , member_lang)508 }509 else:510 #เอา new_password ที่รับมาเข้ารหัส511 hash_input_pass = hashlib.md5(params['new_password'].encode())512 hash_pass = hash_input_pass.hexdigest()513 # update password514 where_param = { "_id": ObjectId(member_json['_id']['$oid']) }515 value_param = {516 "$set":517 {518 "member_password": hash_pass,519 "last_active": datetime.now().strftime('%Y-%m-%d %H:%M:%S'),520 "updated_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S')521 }522 }523 if db.member.update(where_param , value_param):524 result = {525 "status" : True,526 "msg" : get_api_message("change_password" , "change_password_success" , member_lang)527 }528 else:529 result = {530 "status" : False,531 "msg" : get_api_message("change_password" , "data_update_failed" , member_lang)532 }533 else:534 result = { 535 "status" : False,536 "error_code" : 401,537 "msg" : get_api_message("all" , "unauthorized")538 } 539 else:540 result = { 541 "status" : False,542 "msg" : get_api_message("all" , "please_check_your_parameters")543 }544 #set log detail545 user_type = member_type546 function_name = "change_password"547 request_headers = request.headers548 params_get = None549 params_post = params550 set_api_log(user_type , member_id , function_name , request_headers , params_get , params_post , result)551 return result552def forgot_password(request):553 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false554 isset_accept = "Accept" in request.headers555 isset_content_type = "Content-Type" in request.headers556 member_id = None557 member_type = None558 member_lang = None559 params = json.loads(request.data)560 #เช็ค parameter ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false561 isset_app_version = "app_version" in params562 isset_email = "member_email" in params563 isset_user_type = "user_type" in params564 if isset_accept and isset_content_type and isset_app_version and isset_email and isset_user_type:565 check_email = db.member.find_one({566 "member_type": params['user_type'],567 "member_email": params['member_email'].strip().lower()568 })569 if check_email is None:570 result = { 571 "status" : False,572 "msg" : get_api_message("forgot_password" , "data_not_found" , member_lang)573 }574 else:575 #เอาค่าที่ได้จาก query มาแปลงจาก object เป็น json576 member_object = dumps(check_email)577 member_json = json.loads(member_object)578 member_id = member_json['_id']['$oid']579 member_type = member_json['member_type']580 member_lang = member_json['member_lang']581 #generate password582 generate_password = get_random_token(8)583 #เอา generate password ที่รับมาเข้ารหัส584 hash_input_pass = hashlib.md5(generate_password.encode())585 hash_pass = hash_input_pass.hexdigest()586 # update password587 where_param = { "_id": ObjectId(member_json['_id']['$oid']) }588 value_param = {589 "$set":590 {591 "member_password": hash_pass,592 "last_active": datetime.now().strftime('%Y-%m-%d %H:%M:%S'),593 "updated_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S')594 }595 }596 if db.member.update(where_param , value_param):597 #send email598 email_type = "forgot_password"599 subject = "VR Driver : Forgot password"600 to_email = params['member_email'].lower()601 template_html = "forgot_password.html"602 data = { "password" : generate_password }603 check_send_email = send_email(email_type , subject , to_email , template_html , data)604 if check_send_email:605 result = {606 "status" : True,607 "msg" : get_api_message("forgot_password" , "forgot_password_success" , member_lang)608 }609 else:610 result = {611 "status" : False,612 "msg" : get_api_message("forgot_password" , "can_not_send_email" , member_lang)613 }614 else:615 result = {616 "status" : False,617 "msg" : get_api_message("forgot_password" , "data_update_failed" , member_lang)618 }619 else:620 result = { 621 "status" : False,622 "msg" : get_api_message("all" , "please_check_your_parameters")623 }624 #set log detail625 user_type = member_type626 function_name = "forgot_password"627 request_headers = request.headers628 params_get = None629 params_post = params630 set_api_log(user_type , member_id , function_name , request_headers , params_get , params_post , result)631 return result632def change_language(request):633 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false634 isset_accept = "Accept" in request.headers635 isset_content_type = "Content-Type" in request.headers636 isset_token = "Authorization" in request.headers637 member_id = None638 member_type = None639 params = json.loads(request.data)640 #เช็ค parameter ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false641 isset_app_version = "app_version" in params642 isset_member_lang = "member_lang" in params643 if isset_accept and isset_content_type and isset_token and isset_app_version and isset_member_lang:644 #เช็ค token ว่า expire แล้วหรือยัง645 token = request.headers['Authorization']646 check_token = check_token_expire(token)647 if check_token:648 member_info = get_member_info(token)649 member_id = member_info['_id']['$oid']650 member_type = member_info['member_type']651 member_lang = member_info['member_lang']652 if params['member_lang']=="en":653 member_lang = "en"654 else:655 member_lang = "th"656 # update member lang657 where_param = { "member_token": token }658 value_param = {659 "$set":660 {661 "member_lang": member_lang,662 "last_active": datetime.now().strftime('%Y-%m-%d %H:%M:%S'),663 "updated_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S')664 }665 }666 if db.member.update(where_param , value_param):667 result = {668 "status" : True,669 "msg" : get_api_message("change_language" , "change_language_success" , member_lang)670 }671 else:672 result = {673 "status" : False,674 "msg" : get_api_message("change_language" , "data_update_failed" , member_lang)675 }676 else:677 result = { 678 "status" : False,679 "error_code" : 401,680 "msg" : get_api_message("all" , "unauthorized")681 }682 else:683 result = { 684 "status" : False,685 "msg" : get_api_message("all" , "please_check_your_parameters")686 }687 #set log detail688 user_type = member_type689 function_name = "change_language"690 request_headers = request.headers691 params_get = None692 params_post = params693 set_api_log(user_type , member_id , function_name , request_headers , params_get , params_post , result)694 return result695 696def get_specification_policy(request):697 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false698 isset_accept = "Accept" in request.headers699 isset_content_type = "Content-Type" in request.headers700 member_id = None701 member_type = None702 member_lang = "en"703 params = json.loads(request.data)704 #เช็ค parameter ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false705 isset_app_version = "app_version" in params706 isset_user_type = "user_type" in params707 if isset_accept and isset_content_type and isset_app_version and isset_user_type:708 member_type = params['user_type']709 specification = db.specification.find_one({"user_type": params['user_type']})710 711 if specification is None:712 result = { 713 "status" : False,714 "msg" : get_api_message("get_specification_policy" , "data_not_found" , member_lang)715 }716 else:717 #เอาค่าที่ได้จาก query มาแปลงจาก object เป็น json718 specification_object = dumps(specification)719 specification_json = json.loads(specification_object)720 result = {721 "status" : True,722 "msg" : get_api_message("get_specification_policy" , "get_specification_and_policy_success" , member_lang),723 "user_type" : specification_json['user_type'],724 "specification_en" : specification_json['specification_en'],725 "specification_th" : specification_json['specification_th'],726 "policy_en" : specification_json['policy_en'],727 "policy_th" : specification_json['policy_th']728 }729 else:730 result = { 731 "status" : False,732 "msg" : get_api_message("all" , "please_check_your_parameters")733 }734 #set log detail735 user_type = member_type736 function_name = "get_specification_policy"737 request_headers = request.headers738 params_get = None739 params_post = params740 set_api_log(user_type , member_id , function_name , request_headers , params_get , params_post , result)741 return result742def backend_login(request):743 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false744 isset_accept = "Accept" in request.headers745 isset_content_type = "Content-Type" in request.headers746 admin_id = None747 params = json.loads(request.data)748 #เช็ค parameter ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false749 isset_app_version = "app_version" in params750 isset_username = "admin_username" in params751 isset_password = "admin_password" in params752 if isset_accept and isset_content_type and isset_app_version and isset_username and isset_password:753 check_username = db.admin.find_one({754 "admin_username": params['admin_username'].strip().lower(),755 "admin_status": "1"756 })757 if check_username is None:758 result = { 759 "status" : False,760 "username_invalid" : False,761 "password_invalid" : False,762 "msg" : "Username not found."763 }764 else:765 #เอาค่าที่ได้จาก query มาแปลงจาก object เป็น json766 admin_object = dumps(check_username)767 admin_json = json.loads(admin_object)768 admin_id = admin_json['_id']['$oid']769 #เอา password ที่รับมาเข้ารหัส770 hash_input_pass = hashlib.md5(params['admin_password'].encode())771 hash_pass = hash_input_pass.hexdigest()772 #ถ้า password ตรงกัน773 if admin_json['admin_password'] == hash_pass:774 #generate token775 token = get_random_token(40)776 # update admin_token777 where_param = { "_id": ObjectId(admin_json['_id']['$oid']) }778 value_param = {779 "$set":780 {781 "admin_token": token,782 "last_active": datetime.now().strftime('%Y-%m-%d %H:%M:%S'),783 "updated_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S')784 }785 }786 if db.admin.update(where_param , value_param):787 result = {788 "status" : True,789 "msg" : "Login success.",790 "token" : token,791 "fullname" : admin_json['admin_firstname']+" "+admin_json['admin_lastname'],792 "system" : "backend"793 }794 else:795 result = {796 "status" : False,797 "msg" : "Data update failed."798 }799 else:800 result = {801 "status" : False,802 "username_invalid" : True,803 "password_invalid" : False,804 "msg" : "Password invalid."805 }806 else:807 result = { 808 "status" : False,809 "msg" : get_api_message("all" , "please_check_your_parameters")810 }811 #set log detail812 user_type = "admin"813 function_name = "backend_login"814 request_headers = request.headers815 params_get = None816 params_post = params817 set_api_log(user_type , admin_id , function_name , request_headers , params_get , params_post , result)818 return result819def backend_logout(request):820 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false821 isset_accept = "Accept" in request.headers822 isset_content_type = "Content-Type" in request.headers823 isset_token = "Authorization" in request.headers824 admin_id = None825 if isset_accept and isset_content_type and isset_token:826 #เช็ค token ว่า expire แล้วหรือยัง827 token = request.headers['Authorization']828 check_token = check_token_expire_backend(token)829 if check_token:830 admin = db.admin.find_one({831 "admin_token": token,832 "admin_status": "1"833 })834 835 if admin is None:836 result = {"status" : False}837 else:838 #เอาค่าที่ได้จาก query มาแปลงจาก object เป็น json839 admin_object = dumps(admin)840 admin_json = json.loads(admin_object)841 admin_id = admin_json['_id']['$oid']842 # update admin_token, noti_key843 where_param = { "_id": ObjectId(admin_json['_id']['$oid']) }844 value_param = {845 "$set":846 {847 "admin_token": None,848 "last_active": datetime.now().strftime('%Y-%m-%d %H:%M:%S'),849 "updated_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S')850 }851 }852 853 if db.admin.update(where_param , value_param):854 result = {855 "status" : True,856 "msg" : "Logout success."857 }858 else:859 result = {860 "status" : False,861 "msg" : "Data update failed."862 }863 else:864 result = { 865 "status" : False,866 "error_code" : 401,867 "msg" : get_api_message("all" , "unauthorized")868 }869 else:870 result = { 871 "status" : False,872 "msg" : get_api_message("all" , "please_check_your_parameters")873 }874 #set log detail875 user_type = "admin"876 function_name = "backend_logout"877 request_headers = request.headers878 params_get = None879 params_post = None880 set_api_log(user_type , admin_id , function_name , request_headers , params_get , params_post , result)881 return result882def backend_change_password(request):883 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false884 isset_accept = "Accept" in request.headers885 isset_content_type = "Content-Type" in request.headers886 isset_token = "Authorization" in request.headers887 admin_id = None888 params = json.loads(request.data)889 #เช็ค parameter ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false890 isset_app_version = "app_version" in params891 isset_current_password = "current_password" in params892 isset_new_password = "new_password" in params893 isset_confirm_password = "confirm_password" in params894 if isset_accept and isset_content_type and isset_token and isset_app_version and isset_current_password and isset_new_password and isset_confirm_password:895 #เช็ค token ว่า expire แล้วหรือยัง896 token = request.headers['Authorization']897 check_token = check_token_expire_backend(token)898 if check_token:899 check_admin = db.admin.find_one({900 "admin_token": token,901 "admin_status": "1"902 })903 if check_admin is None:904 result = { 905 "status" : False,906 "msg" : "Admin not found."907 }908 else:909 #เอาค่าที่ได้จาก query มาแปลงจาก object เป็น json910 admin_object = dumps(check_admin)911 admin_json = json.loads(admin_object)912 admin_id = admin_json['_id']['$oid']913 #เอา current password ที่รับมาเข้ารหัส914 hash_input_pass = hashlib.md5(params['current_password'].encode())915 current_password = hash_input_pass.hexdigest()916 #เช็คว่ารหัสผ่านตรงกันหรือไม่917 if current_password != admin_json['admin_password']:918 result = { 919 "status" : False,920 "msg" : "Current password is incorrect."921 }922 else:923 #check new password & confirm password924 if params['new_password']!=params['confirm_password']:925 result = { 926 "status" : False,927 "msg" : "New password do not match."928 }929 else:930 count_password = len(params['new_password'])931 if count_password < 6:932 result = {933 "status" : False,934 "msg" : "New password less than 6 character."935 }936 else:937 if params['new_password'] == params['current_password']:938 result = {939 "status" : False,940 "msg" : "New password can't be the same as your current password."941 }942 else:943 #เอา new_password ที่รับมาเข้ารหัส944 hash_input_pass = hashlib.md5(params['new_password'].encode())945 hash_pass = hash_input_pass.hexdigest()946 # update password947 where_param = { "_id": ObjectId(admin_id) }948 value_param = {949 "$set":950 {951 "admin_password": hash_pass,952 "last_active": datetime.now().strftime('%Y-%m-%d %H:%M:%S'),953 "updated_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S')954 }955 }956 if db.admin.update(where_param , value_param):957 result = {958 "status" : True,959 "msg" : "Change password success."960 }961 else:962 result = {963 "status" : False,964 "msg" : "Data update failed."965 }966 else:967 result = { 968 "status" : False,969 "error_code" : 401,970 "msg" : get_api_message("all" , "unauthorized")971 } 972 else:973 result = { 974 "status" : False,975 "msg" : get_api_message("all" , "please_check_your_parameters")976 }977 #set log detail978 user_type = "admin"979 function_name = "backend_change_password"980 request_headers = request.headers981 params_get = None982 params_post = params983 set_api_log(user_type , admin_id , function_name , request_headers , params_get , params_post , result)984 return result985def backend_forgot_password(request):986 #เช็ค parameter ใน header ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false987 isset_accept = "Accept" in request.headers988 isset_content_type = "Content-Type" in request.headers989 admin_id = None990 params = json.loads(request.data)991 #เช็ค parameter ว่าส่งมาไหม ถ้าส่งมาจะมีค่าเป็น true ไม่ส่งมาจะมีค่าเป็น false992 isset_app_version = "app_version" in params993 isset_email = "admin_email" in params994 if isset_accept and isset_content_type and isset_app_version and isset_email:995 check_email = db.admin.find_one({996 "admin_email": params['admin_email'].strip().lower(),997 "admin_status": "1"998 })999 if check_email is None:1000 result = { 1001 "status" : False,1002 "msg" : "E-mail not found."1003 }1004 else:1005 #เอาค่าที่ได้จาก query มาแปลงจาก object เป็น json1006 admin_object = dumps(check_email)1007 admin_json = json.loads(admin_object)1008 admin_id = admin_json['_id']['$oid']1009 #generate password1010 generate_password = get_random_token(8)1011 #เอา generate password ที่รับมาเข้ารหัส1012 hash_input_pass = hashlib.md5(generate_password.encode())1013 hash_pass = hash_input_pass.hexdigest()1014 # update password1015 where_param = { "_id": ObjectId(admin_json['_id']['$oid']) }1016 value_param = {1017 "$set":1018 {1019 "admin_password": hash_pass,1020 "last_active": datetime.now().strftime('%Y-%m-%d %H:%M:%S'),1021 "updated_at": datetime.now().strftime('%Y-%m-%d %H:%M:%S')1022 }1023 }1024 if db.admin.update(where_param , value_param):1025 #send email1026 email_type = "forgot_password_backend"1027 subject = "VR Driver : Forgot password"1028 to_email = params['admin_email'].lower()1029 template_html = "forgot_password_backend.html"1030 data = { "password" : generate_password }1031 check_send_email = send_email(email_type , subject , to_email , template_html , data)1032 if check_send_email:1033 result = {1034 "status" : True,1035 "msg" : "Forgot password success."1036 }1037 else:1038 result = {1039 "status" : False,1040 "msg" : "Can't send email."1041 }1042 else:1043 result = {1044 "status" : False,1045 "msg" : "Data update failed."1046 }1047 else:1048 result = { 1049 "status" : False,1050 "msg" : get_api_message("all" , "please_check_your_parameters")1051 }1052 #set log detail1053 user_type = "admin"1054 function_name = "backend_forgot_password"1055 request_headers = request.headers1056 params_get = None1057 params_post = params1058 set_api_log(user_type , admin_id , function_name , request_headers , params_get , params_post , result)1059 return result1060def get_random_token(string_length=40):1061 #ใช้ตัวอักษร A-Z,a-z,0-9 ในการ generate token1062 all_character = string.ascii_letters + string.digits...

Full Screen

Full Screen

threads.py

Source:threads.py Github

copy

Full Screen

1#Licensed to the Apache Software Foundation (ASF) under one2#or more contributor license agreements. See the NOTICE file3#distributed with this work for additional information4#regarding copyright ownership. The ASF licenses this file5#to you under the Apache License, Version 2.0 (the6#"License"); you may not use this file except in compliance7#with the License. You may obtain a copy of the License at8# http://www.apache.org/licenses/LICENSE-2.09#Unless required by applicable law or agreed to in writing, software10#distributed under the License is distributed on an "AS IS" BASIS,11#WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12#See the License for the specific language governing permissions and13#limitations under the License.14import threading, time, os, sys, pprint15from popen2 import Popen4, Popen3, MAXFD16from signal import SIGTERM, SIGKILL17class baseThread(threading.Thread):18 """Base CAM threading class. The run method should be overridden."""19 def __init__(self, name):20 threading.Thread.__init__(self, name=name)21 self.stopFlag = threading.Event()22 self.stopFlag.clear()23 self.running = threading.Event()24 self.running.set()25 self.isFinished = threading.Event()26 self.isFinished.clear()27 def join(self, timeout=None):28 self.stopFlag.set()29 threading.Thread.join(self, timeout)30 def pause(self):31 """Pause thread."""32 self.running.clear()33 def cont(self):34 """Resume thread operation."""35 self.running.set()36class simpleCommand(baseThread):37 """Command execution object. Command output and exit status are captured.38 Public class attributes:39 cmdString - command to be executed40 outputBuffer - command output, stdout + stderr41 status - exit status, as returned by wait42 43 stdin - standard input for command44 stdout - standard output of command when buffer == False45 stderr - standard error of command when mode == 3 and buffer == False46 47 """48 def __init__(self, name, cmdString, env=os.environ, mode=4, buffer=True, 49 wait=True, chdir=None):50 """Class initialization.51 name - thread name to use when running the command52 cmdString - command string to execute53 inputString - string to print to command's stdin54 env - shell environment dictionary55 mode - 3 for popen3 and 4 for popen456 buffer - out put to be retrieved with output() method57 wait - return immediately after start() is called and output 58 command results as they come to stdout"""59 baseThread.__init__(self, name=name)60 self.cmdString = cmdString61 self.__mode = mode62 self.__buffer = buffer63 self.__wait = wait64 self.__chdir = chdir65 self.__outputBuffer = []66 self.__status = None67 self.__pid = None68 self.__isFinished = threading.Event()69 self.__isFinished.clear()70 71 self.stdin = None72 self.stdout = None73 self.stderr = None74 self.__env = env75 76 def run(self):77 """ Overridden run method. Most of the work happens here. start()78 should be called in place of this method."""79 80 oldDir = None81 if self.__chdir:82 if os.path.exists(self.__chdir):83 oldDir = os.getcwd() 84 os.chdir(self.__chdir)85 else:86 raise Exception(87 "simpleCommand: invalid chdir specified: %s" % 88 self.__chdir)89 90 cmd = None91 if self.__mode == 3:92 cmd = _Popen3Env(self.cmdString, env=self.__env)93 else:94 cmd = _Popen4Env(self.cmdString, env=self.__env)95 self.__pid = cmd.pid96 self.stdin = cmd.tochild97 98 if self.__mode == 3:99 self.stderr = cmd.childerr100 while cmd.fromchild == None:101 time.sleep(1)102 103 if self.__buffer == True:104 output = cmd.fromchild.readline()105 while output != '':106 while not self.running.isSet():107 if self.stopFlag.isSet():108 break109 time.sleep(1)110 self.__outputBuffer.append(output)111 output = cmd.fromchild.readline()112 elif self.__wait == False:113 output = cmd.fromchild.readline()114 while output != '':115 while not self.running.isSet():116 if self.stopFlag.isSet():117 break118 time.sleep(1)119 print output,120 if self.stopFlag.isSet():121 break122 output = cmd.fromchild.readline()123 else:124 self.stdout = cmd.fromchild125 self.__status = cmd.poll()126 while self.__status == -1:127 while not self.running.isSet():128 if self.stopFlag.isSet():129 break130 time.sleep(1)131 self.__status = cmd.poll()132 time.sleep(1)133 if oldDir:134 os.chdir(oldDir)135 self.__isFinished.set()136 137 sys.exit(0)138 def getPid(self):139 """return pid of the launches process"""140 return self.__pid141 def output(self):142 return self.__outputBuffer[:]143 def wait(self):144 """Wait blocking until command execution completes."""145 self.__isFinished.wait()146 return os.WEXITSTATUS(self.__status)147 def is_running(self):148 """Returns boolean, are we running?"""149 150 status = True151 if self.__isFinished.isSet():152 status = False153 154 return status 155 def exit_code(self):156 """ Returns process exit code."""157 158 if self.__status != None:159 return os.WEXITSTATUS(self.__status)160 else:161 return None162 163 def exit_status_string(self):164 """Return a string representation of the command's exit status."""165 statusString = None166 if self.__status:167 exitStatus = os.WEXITSTATUS(self.__status)168 exitSignal = os.WIFSIGNALED(self.__status)169 coreDump = os.WCOREDUMP(self.__status)170 statusString = "exit code: %s | signal: %s | core %s" % \171 (exitStatus, exitSignal, coreDump)172 return(statusString)173 def stop(self):174 """Stop the running command and join it's execution thread."""175 self.join()176 def kill(self):177 count = 0178 while self.is_running():179 try:180 if count > 20:181 os.kill(self.__pid, SIGKILL)182 break183 else: 184 os.kill(self.__pid, SIGTERM)185 except:186 break187 188 time.sleep(.1)189 count = count + 1190 191 self.stop()192 193class _Popen3Env(Popen3):194 def __init__(self, cmd, capturestderr=False, bufsize=-1, env=os.environ):195 self._env = env196 Popen3.__init__(self, cmd, capturestderr, bufsize)197 198 def _run_child(self, cmd):199 if isinstance(cmd, basestring):200 cmd = ['/bin/sh', '-c', cmd]201 for i in xrange(3, MAXFD):202 try:203 os.close(i)204 except OSError:205 pass206 try:207 os.execvpe(cmd[0], cmd, self._env)208 finally:209 os._exit(1)210 211class _Popen4Env(_Popen3Env, Popen4):212 childerr = None213 def __init__(self, cmd, bufsize=-1, env=os.environ):214 self._env = env215 Popen4.__init__(self, cmd, bufsize)216 217class loop(baseThread):218 """ A simple extension of the threading.Thread class which continuously219 executes a block of code until join().220 """221 def __init__(self, name, functionRef, functionArgs=None, sleep=1, wait=0,222 offset=False):223 """Initialize a loop object.224 name - thread name225 functionRef - a function reference226 functionArgs - function arguments in the form of a tuple,227 sleep - time to wait between function execs228 wait - time to wait before executing the first time229 offset - set true to sleep as an offset of the start of the230 last func exec instead of the end of the last func231 exec232 """233 self.__functionRef = functionRef234 self.__functionArgs = functionArgs235 self.__sleep = sleep236 self.__wait = wait237 self.__offset = offset238 baseThread.__init__(self, name=name)239 def run(self):240 """Do not call this directly. Call self.start()."""241 startTime = None242 while not self.stopFlag.isSet():243 sleep = self.__sleep244 if self.__wait > 0:245 startWaitCount = 0246 while not self.stopFlag.isSet():247 while not self.running.isSet():248 if self.stopFlag.isSet():249 break250 time.sleep(1)251 time.sleep(0.5)252 startWaitCount = startWaitCount + .5253 if startWaitCount >= self.__wait:254 self.__wait = 0255 break256 startTime = time.time()257 if not self.stopFlag.isSet():258 if self.running.isSet():259 if self.__functionArgs:260 self.__functionRef(self.__functionArgs)261 else:262 self.__functionRef()263 endTime = time.time()264 while not self.running.isSet():265 time.sleep(1)266 while not self.stopFlag.isSet():267 while not self.running.isSet():268 if self.stopFlag.isSet():269 break270 time.sleep(1)271 currentTime = time.time()272 if self.__offset:273 elapsed = time.time() - startTime274 else:275 elapsed = time.time() - endTime276 if elapsed >= self.__sleep:277 break278 time.sleep(0.5)279 280 self.isFinished.set()281 def set_sleep(self, sleep, wait=None, offset=None):282 """Modify loop frequency paramaters.283 sleep - time to wait between function execs284 wait - time to wait before executing the first time285 offset - set true to sleep as an offset of the start of the286 last func exec instead of the end of the last func287 exec288 """289 self.__sleep = sleep290 if wait != None:291 self.__wait = wait292 if offset != None:293 self.__offset = offset294 def get_sleep(self):295 """Get loop frequency paramaters.296 Returns a dictionary with sleep, wait, offset.297 """298 return {299 'sleep' : self.__sleep,300 'wait' : self.__wait,301 'offset' : self.__offset,302 }303 304class func(baseThread):305 """ A simple extension of the threading.Thread class which executes 306 a function in a separate thread.307 """308 def __init__(self, name, functionRef, functionArgs=None):309 """Initialize a func object.310 name - thread name311 functionRef - a function reference312 functionArgs - function arguments in the form of a tuple,313 """314 self.__functionRef = functionRef315 self.__functionArgs = functionArgs316 baseThread.__init__(self, name=name)317 def run(self):318 """Do not call this directly. Call self.start()."""319 if not self.stopFlag.isSet():320 if self.running.isSet():321 if self.__functionArgs:322 self.__functionRef(self.__functionArgs)323 else:324 self.__functionRef()...

Full Screen

Full Screen

MyAlgorithm.py

Source:MyAlgorithm.py Github

copy

Full Screen

1import threading2import numpy3# from interfaces.robot_wrapper import RobotWrapper4from pick_and_place import Pick_Place5from std_msgs.msg import Bool6import os, rospkg, yaml7import rospy8class Algorithm:9 def __init__(self):10 self.is_on = False11 self.stopevent = threading.Event()12 self.pauseevent = threading.Event()13 self.startalgorithm_sub = rospy.Subscriber("/start_algorithm", Bool, self.start_callback)14 self.stopalgorithm_sub = rospy.Subscriber("/stop_algorithm", Bool, self.stop_callback)15 self.pausealgorithm_sub = rospy.Subscriber("/pause_algorithm", Bool, self.pause_callback)16 self.stopalgorithm_pub = rospy.Publisher("/stop_algorithm", Bool, queue_size=0)17 def start_callback(self, msg):18 if msg.data == True:19 self.stopevent.set()20 self.pauseevent.set()21 self.myalgorithm()22 msg = Bool()23 msg.data = True24 self.stopalgorithm_pub.publish(msg) 25 def stop_callback(self, msg):26 if msg.data == True:27 self.pauseevent.clear()28 self.stopevent.clear()29 def pause_callback(self, msg):30 if msg.data == True:31 self.pauseevent.clear()32 else:33 self.pauseevent.set()34 def set_pick_and_place(self, pick_place):35 self.pick_place = pick_place36 def myalgorithm(self):37 self.pick_place.back_to_home()38 # insert following two lines where you want to stop the algorithm 39 # with the stop button in GUI40 while (not self.pauseevent.isSet()) or (not self.stopevent.isSet()):41 if not self.stopevent.isSet():42 return43 # pick blue ball44 object_name = "blue_ball"45 pose = self.pick_place.get_object_pose(object_name)46 print(pose.position)47 grasp = self.pick_place.generate_grasp(object_name, "vertical", pose.position, 0.27, length=0.145)48 self.pick_place.pickup(object_name, [grasp])49 while (not self.pauseevent.isSet()) or (not self.stopevent.isSet()):50 if not self.stopevent.isSet():51 return52 goal_position = self.pick_place.get_target_position("blue_target")53 x = goal_position.x54 y = goal_position.y55 z = goal_position.z+0.1556 place_pose = self.pick_place.pose2msg(0,0,0, x, y, z)57 print(place_pose.position)58 self.pick_place.place("vertical", place_pose.position)59 while (not self.pauseevent.isSet()) or (not self.stopevent.isSet()):60 if not self.stopevent.isSet():61 return62 self.pick_place.back_to_home()63 while (not self.pauseevent.isSet()) or (not self.stopevent.isSet()):64 if not self.stopevent.isSet():65 return66 # pick yellow box67 object_name = "yellow_box"68 pose = self.pick_place.get_object_pose(object_name)69 print(pose.position)70 grasp = self.pick_place.generate_grasp(object_name, "vertical", pose.position, 0.55, yaw = 90, length=0.16)71 self.pick_place.pickup(object_name, [grasp])72 while (not self.pauseevent.isSet()) or (not self.stopevent.isSet()):73 if not self.stopevent.isSet():74 return75 goal_position = self.pick_place.get_target_position("yellow_target")76 x = goal_position.x77 y = goal_position.y78 z = goal_position.z+0.1579 place_pose = self.pick_place.pose2msg(0,0,0, x, y, z)80 print(place_pose.position)81 self.pick_place.place("vertical", place_pose.position)82 while (not self.pauseevent.isSet()) or (not self.stopevent.isSet()):83 if not self.stopevent.isSet():84 return85 self.pick_place.back_to_home()86 while (not self.pauseevent.isSet()) or (not self.stopevent.isSet()):87 if not self.stopevent.isSet():88 return89 # pick red box90 object_name = "red_box"91 pose = self.pick_place.get_object_pose(object_name)92 print(pose.position)93 grasp = self.pick_place.generate_grasp(object_name, "vertical", pose.position, length=0.16)94 self.pick_place.pickup(object_name, [grasp])95 while (not self.pauseevent.isSet()) or (not self.stopevent.isSet()):96 if not self.stopevent.isSet():97 return98 goal_position = self.pick_place.get_target_position("red_target")99 x = goal_position.x100 y = goal_position.y101 z = goal_position.z+0.15102 place_pose = self.pick_place.pose2msg(0,0,0, x, y, z)103 print(place_pose.position)104 self.pick_place.place("vertical", place_pose.position)105 while (not self.pauseevent.isSet()) or (not self.stopevent.isSet()):106 if not self.stopevent.isSet():107 return108 self.pick_place.back_to_home()109 while (not self.pauseevent.isSet()) or (not self.stopevent.isSet()):110 if not self.stopevent.isSet():111 return112 # pick yellow ball113 object_name = "yellow_ball"114 pose = self.pick_place.get_object_pose(object_name)115 print(pose.position)116 grasp = self.pick_place.generate_grasp(object_name, "vertical", pose.position, 0.55, length = 0.155)117 self.pick_place.pickup(object_name, [grasp])118 while (not self.pauseevent.isSet()) or (not self.stopevent.isSet()):119 if not self.stopevent.isSet():120 return121 goal_position = self.pick_place.get_target_position("yellow_target")122 x = goal_position.x123 y = goal_position.y124 z = goal_position.z+0.15125 place_pose = self.pick_place.pose2msg(0,0,0, x, y, z)126 print(place_pose.position)127 self.pick_place.place("vertical", place_pose.position)128 while (not self.pauseevent.isSet()) or (not self.stopevent.isSet()):129 if not self.stopevent.isSet():130 return131 self.pick_place.back_to_home()132 while (not self.pauseevent.isSet()) or (not self.stopevent.isSet()):133 if not self.stopevent.isSet():134 return135 # pick green cylinder136 object_name = "green_cylinder"137 pose = self.pick_place.get_object_pose(object_name)138 print(pose.position)139 pose.position.z += 0.02140 grasp = self.pick_place.generate_grasp(object_name, "horizontal", pose.position, 0.3, length = 0.13)141 self.pick_place.pickup(object_name, [grasp])142 while (not self.pauseevent.isSet()) or (not self.stopevent.isSet()):143 if not self.stopevent.isSet():144 return145 goal_position = self.pick_place.get_target_position("green_target")146 x = goal_position.x147 y = goal_position.y148 z = goal_position.z+0.15149 place_pose = self.pick_place.pose2msg(0,0,0, x, y, z)150 print(place_pose.position)151 self.pick_place.place("vertical", place_pose.position)152 while (not self.pauseevent.isSet()) or (not self.stopevent.isSet()):153 if not self.stopevent.isSet():154 return155 self.pick_place.back_to_home()156 while (not self.pauseevent.isSet()) or (not self.stopevent.isSet()):157 if not self.stopevent.isSet():158 return159 # pick red cylinder160 object_name = "red_cylinder"161 pose = self.pick_place.get_object_pose(object_name)162 print(pose.position)163 pose.position.z += 0.01164 grasp = self.pick_place.generate_grasp(object_name, "horizontal", pose.position, 0.45, length=0.14)165 self.pick_place.pickup(object_name, [grasp])166 while (not self.pauseevent.isSet()) or (not self.stopevent.isSet()):167 if not self.stopevent.isSet():168 return169 goal_position = self.pick_place.get_target_position("red_target")170 x = goal_position.x171 y = goal_position.y172 z = goal_position.z+0.15173 place_pose = self.pick_place.pose2msg(0,0,0, x, y, z)174 print(place_pose.position)175 self.pick_place.place("vertical", place_pose.position)176 while (not self.pauseevent.isSet()) or (not self.stopevent.isSet()):177 if not self.stopevent.isSet():178 return179 self.pick_place.back_to_home()180 while (not self.pauseevent.isSet()) or (not self.stopevent.isSet()):181 if not self.stopevent.isSet():182 return183 # pick blue box184 object_name = "blue_box"185 pose = self.pick_place.get_object_pose(object_name)186 print(pose.position)187 pose.position.x -= 0.02188 grasp = self.pick_place.generate_grasp(object_name, "horizontal", pose.position, 0.4, pitch = 60, length = 0.16)189 self.pick_place.pickup(object_name, [grasp])190 while (not self.pauseevent.isSet()) or (not self.stopevent.isSet()):191 if not self.stopevent.isSet():192 return193 goal_position = self.pick_place.get_target_position("blue_target")194 x = goal_position.x195 y = goal_position.y196 z = goal_position.z+0.15197 place_pose = self.pick_place.pose2msg(0,0,0, x, y, z)198 print(place_pose.position)199 self.pick_place.place("vertical", place_pose.position)200 while (not self.pauseevent.isSet()) or (not self.stopevent.isSet()):201 if not self.stopevent.isSet():202 return203 self.pick_place.back_to_home()204 # pick green ball205 object_name = "green_ball"206 pose = self.pick_place.get_object_pose(object_name)207 print(pose.position)208 grasp = self.pick_place.generate_grasp(object_name, "horizontal", pose.position, 0.37, pitch = 80, length=0.145)209 self.pick_place.pickup(object_name, [grasp])210 while (not self.pauseevent.isSet()) or (not self.stopevent.isSet()):211 if not self.stopevent.isSet():212 return213 goal_position = self.pick_place.get_target_position("green_target")214 x = goal_position.x215 y = goal_position.y216 z = goal_position.z+0.15217 place_pose = self.pick_place.pose2msg(0,0,0, x, y, z)218 print(place_pose.position)219 self.pick_place.place("vertical", place_pose.position)220 while (not self.pauseevent.isSet()) or (not self.stopevent.isSet()):221 if not self.stopevent.isSet():222 return223 self.pick_place.back_to_home()224 self.pick_place.send_message("Algorithm finished")225if __name__=="__main__":226 rospy.init_node("pick_place_basic")227 algo = Algorithm()228 algo.set_pick_and_place(Pick_Place())229 print("You can start your algorithm with GUI")...

Full Screen

Full Screen

Pytest Tutorial

Looking for an in-depth tutorial around pytest? LambdaTest covers the detailed pytest tutorial that has everything related to the pytest, from setting up the pytest framework to automation testing. Delve deeper into pytest testing by exploring advanced use cases like parallel testing, pytest fixtures, parameterization, executing multiple test cases from a single file, and more.

Chapters

  1. What is pytest
  2. Pytest installation: Want to start pytest from scratch? See how to install and configure pytest for Python automation testing.
  3. Run first test with pytest framework: Follow this step-by-step tutorial to write and run your first pytest script.
  4. Parallel testing with pytest: A hands-on guide to parallel testing with pytest to improve the scalability of your test automation.
  5. Generate pytest reports: Reports make it easier to understand the results of pytest-based test runs. Learn how to generate pytest reports.
  6. Pytest Parameterized tests: Create and run your pytest scripts while avoiding code duplication and increasing test coverage with parameterization.
  7. Pytest Fixtures: Check out how to implement pytest fixtures for your end-to-end testing needs.
  8. Execute Multiple Test Cases: Explore different scenarios for running multiple test cases in pytest from a single file.
  9. Stop Test Suite after N Test Failures: See how to stop your test suite after n test failures in pytest using the @pytest.mark.incremental decorator and maxfail command-line option.

YouTube

Skim our below pytest tutorial playlist to get started with automation testing using the pytest framework.

https://www.youtube.com/playlist?list=PLZMWkkQEwOPlcGgDmHl8KkXKeLF83XlrP

Run Pytest automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful