def _run(self): """Start the main loop of the thread, creating Dota bots to process available jobs.""" while True: with self.app.app_context(): admins, casters = divide_vip_list_per_type( GameVIP.get_all_vips()) bot_pause = DynamicConfiguration.get('bot_pause', 'False') for game in db.session().query(Game)\ .filter(Game.status==GameStatus.WAITING_FOR_BOT)\ .order_by(Game.id).all(): if len(self.credentials) == 0 or bot_pause == 'True': continue # Start a Dota bot to process the game self.mutex.acquire() credential = self.credentials.pop( random.randint(0, len(self.credentials) - 1)) g = DotaBot(self, credential, admins, casters, game.id, game.name, game.password, game.team1, game.team2, game.team1_ids, game.team2_ids, game.team_choosing_first) self.working_bots[credential.login] = g game.status = GameStatus.CREATION_IN_PROGRESS game.bot = credential.login db.session().commit() g.start() self.mutex.release() sleep(60)
def add_word(form): DetectorFactory.seed = 0 target_lang = TARGET_LANGUAGE word = form.get("word").strip() if (len(word) < 1): raise CustomException(404, "Word can't be less that 1 character") if (form.get("target_lang") != None): target_lang = form["target_lang"] langs = get_langs(word) translations = get_translations(langs, word, target_lang) w = WordTranslations(word, target_lang, langs[0], translations[langs[0]], langs[1], translations[langs[1]], langs[2], translations[langs[2]]) for attr, value in w.__dict__.items(): if value is None: w.__dict__[attr] = "-" try: db.session.add(w) db.session.commit() return w except exc.IntegrityError as e: print("add_word exc.IntegrityError: " + str(e)) db.session().rollback() raise exc.IntegrityError
def add_api_key(key, description): """Add a new API Key to the system. Args: key: key value string to add. description: key description as a reminder. """ if key is None: print('No API key specified') return if description is None: print('No description specified') return salt = app.config['API_KEY_SALT'] hash_object = hashlib.sha1((key + salt).encode('utf-8')) hash_key = hash_object.hexdigest() api_key = db.session().query(APIKey).filter(APIKey.key_hash == hash_key).one_or_none() if api_key is not None: print('Key already in the system') else: key = APIKey(hash_key, description) db.session().add(key) db.session().commit() print('Key added')
def get(self): """ 获取用户资料 """ db.session().set_to_read() user = User.query.options( load_only(User.id, User.name, User.mobile, User.profile_photo, User.introduction, User.email)).filter_by(id=g.user_id).first() return { 'id': user.id, 'name': user.name, 'intro': user.introduction, 'photo': current_app.config['QINIU_DOMAIN'] + (user.profile_photo if user.profile_photo else cache_constants.DEFAULT_USER_PROFILE_PHOTO), 'email': user.email, 'mobile': user.mobile }
def remove_game_vip(): """ @api {post} /api/game/vip/remove GameVIPRemove @apiVersion 1.0.0 @apiName GameVIPRemove @apiGroup DotaBots @apiDescription Remove a game VIP. @apiHeader {String} API_KEY Restricted API_KEY necessary to call the endpoint. @apiError (Errors){String} ApiKeyMissing Missing API_KEY header. @apiError (Errors){String} ApiKeyInvalid Invalid API_KEY header. @apiParam {Integer} id SteamId of the vip to remove. @apiError (Errors){String} MissingId id is not specified. @apiError (Errors){String} InvalidId id is invalid. @apiError (Errors){String} VIPDoesNotExist VIP with id does not exist in the database. """ # Header checks header_key = request.headers.get('API_KEY', None) if header_key is None: return jsonify({'success': 'no', 'error': 'ApiKeyMissing', 'payload': {} }), 200 if header_key != app.config['API_KEY']: return jsonify({'success': 'no', 'error': 'ApiKeyInvalid', 'payload': {} }), 200 data = request.get_json(force=True) # id checks id = data.get('id', None) if id is None: return jsonify({'success': 'no', 'error': 'MissingId', 'payload': {} }), 200 if not isinstance(id, int): return jsonify({'success': 'no', 'error': 'InvalidId', 'payload': {} }), 200 game_vip = db.session().query(GameVIP).filter(GameVIP.id==id).one_or_none() if game_vip is None: return jsonify({'success': 'no', 'error': 'VIPDoesNotExist', 'payload': {} }), 200 # Remove VIP db.session().delete(game_vip) db.session().commit() return jsonify({'success': 'yes', 'payload': {} }), 200
def post_api_key_remove(auth_token): """ @api {post} /api/auth/key/remove APIKeyRemove @apiVersion 1.1.0 @apiName APIKeyRemove @apiGroup Authentication @apiDescription Remove an APIKey from the system. @apiHeader {String} Authorization 'Bearer <Auth_Token>' @apiError (Errors){String} AuthorizationHeaderInvalid Authorization Header is Invalid. @apiError (Errors){String} AuthTokenExpired Token has expired, must be refreshed by client. @apiError (Errors){String} AuthTokenInvalid Token is invalid, decode is impossible. @apiError (Errors){String} ClientAccessImpossible This type of client can't access target endpoint. @apiError (Errors){String} ClientAccessRefused Client has no scope access to target endpoint. @apiParam {String} key APIKey to add to the system. @apiError (Errors){String} KeyParameterMissing Key is not present in the parameters. @apiError (Errors){String} KeyParameterInvalid Key is not valid String. @apiError (Errors){String} KeyDoesntExists There is no such key in the system. """ data = request.get_json(force=True) # key checks key = data.get('key', None) if key is None: return jsonify({ 'success': 'no', 'error': 'KeyParameterMissing', 'payload': {} }), 200 if not isinstance(key, str) or len(key) == 0: return jsonify({ 'success': 'no', 'error': 'KeyParameterInvalid', 'payload': {} }), 200 # Hash salt = app.config['API_KEY_SALT'] hash_object = hashlib.sha1((key + salt).encode('utf-8')) hash_key = hash_object.hexdigest() db_key = APIKey.get(hash_key) if db_key is None: return jsonify({ 'success': 'no', 'error': 'KeyDoesntExists', 'payload': {} }), 200 db.session().delete(db_key) db.session().commit() return jsonify({'success': 'yes', 'error': '', 'payload': {}}), 200
def patch(self): """ 编辑用户的信息 """ db.session().set_to_write() json_parser = RequestParser() json_parser.add_argument('name', type=inputs.regex(r'^.{1,7}$'), required=False, location='json') json_parser.add_argument('intro', type=inputs.regex(r'^.{0,60}$'), required=False, location='json') json_parser.add_argument('email', type=parser.email, required=False, location='json') args = json_parser.parse_args() user_id = g.user_id new_cache_values = {} new_user_values = {} return_values = {'id': user_id} if args.name: new_cache_values['name'] = args.name new_user_values['name'] = args.name return_values['name'] = args.name if args.intro: new_cache_values['intro'] = args.intro new_user_values['introduction'] = args.intro return_values['intro'] = args.intro if args.email: # TODO email 缓存 new_user_values['email'] = args.email return_values['email'] = args.email try: if new_user_values: User.query.filter_by(id=user_id).update(new_user_values) except IntegrityError: db.session.rollback() return {'message': 'User name has existed.'}, 409 db.session.commit() if new_cache_values: cache_user.UserProfileCache(user_id).clear() return return_values, 201
def initialize_lobby(self): """Setup the game lobby with the good options, and change status in database.""" self.print_info('Game hosted, setup.') self.dota.channels.join_lobby_channel() self.dota.join_practice_lobby_team() self.dota.config_practice_lobby(options=self.lobby_options) with self.app.app_context(): game = db.session().query(Game).filter( Game.id == self.id).one_or_none() if game is not None: game.status = GameStatus.WAITING_FOR_PLAYERS db.session().commit() self.machine_state = DotaBotState.WAITING_FOR_PLAYERS
def ModifyRoleRequest(self, role_id, params): ''' 修改权限信息 ''' s = db.session() try: role = s.query(Role).filter(Role.role_id == role_id).first() if not role: return str('数据不存在') is_exists = self.isSaveExists(s, params, role) if is_exists != True: return str(is_exists['error'].encode('utf8')) role.name = params['name'] role.mark = params['mark'] role.is_disabled = params['is_disabled'] role.role_list = json.dumps({ 'I': params['role_list'], 'M': params['menu'] }) s.commit() return True except Exception as e: print e s.rollback() return str(e.message)
def ImportSql(self, file): s = db.session() try: filename = 'TABLE%s.sql' % int(time.time() * 1000) config = Config() if not os.path.exists(sql_dir): os.mkdir(sql_dir) file_path = os.path.join(sql_dir, filename) file.save(file_path) sqlfromat = "%s -h%s -u%s -p%s -P%s %s <%s" sql = (sqlfromat % ('mysql ', config.host, config.admin, config.password, config.port, config.db, file_path)) db.drop_all() os.system(sql) return True except Exception as e: s.rollback() print e return str(e.message)
def create_user(self): """ 회원가입한 유저 정보 DB에 저장 :return: Boolean """ name = self._body.get('name') nickname = self._body.get('nick_name') password = self._body.get('password') phone = self._body.get('phone') email = self._body.get('email') gender = self._body.get('gender') password = self.encrypt_password(password=password) session = db.session() try: user = Users(name=name, nickname=nickname, password=password, phone=phone, email=email, gender=gender) session.add(user) except Exception as e: print(f'err : {e}') session.rollback() return False else: session.commit() session.close() return True
def CreateRoleRequest(self, params): ''' 新建权限 ''' s = db.session() is_exists = self.isCreateExists(s, params) if is_exists != True: return str(is_exists['error'].encode('utf8')) try: item = Role(name=params['name'], mark=params['mark'], role_id=uuid.uuid4(), is_disabled=params['is_disabled'], role_list=json.dumps({ 'I': params['role_list'], 'M': params['menu'] })) s.add(item) s.commit() return True except Exception as e: s.rollback() print e return str(e.message)
def GetSalaryRequest(self, openid, page=1, page_size=20): ''' 获取个人工资列表 ''' s = db.session() try: res = SalaryUser.query.filter_by(**{ 'openid': openid }).first() if not res: return {'data': [], 'total': 0} data = { 'id_card': res.id_card, 'phone': res.phone } result = Salary.query.filter_by(**data).order_by('id').paginate(page, page_size, error_out=False) return {'data': [value.to_json() for value in result.items], 'total': result.total} except Exception as e: print e logging.info('-------获取个人工资失败%s' % e) return str('获取个人工资失败')
def AddSalaryRequest(self, params): ''' 注册或者登录个人工资查询 ''' s = db.session() try: res = SalaryUser.query.filter_by(**{ 'id_card': params['id_card'], 'phone': int(params['phone']) }).first() if res: return { 'openid': res.openid } openid = str(uuid.uuid4()) s.add(SalaryUser( salary_user_id=uuid.uuid4(), id_card=params['id_card'], phone=int(params['phone']), openid=openid )) s.commit() return { 'openid': openid } except Exception as e: print e logging.info('-------注册个人工资查询失败%s' % e) return str('注册个人工资查询失败')
def GetUserLoginIp(self): ''' 获取用户登录IP分布情况 ''' s = db.session() try: ip_list = s.query(Log.ip).filter( Log.type == 1, Log.status == 0).group_by('ip').all() reader = geoip2.database.Reader(GeoLite2_dir) ip = {} city = {} for i in ip_list: try: response = reader.city(i[0]) if not ip.has_key(response.city.names["zh-CN"]): ip[response.city.names["zh-CN"]] = { 'count': 1, 'ip': [i[0]] } else: ip[response.city.names["zh-CN"]]['count'] += 1 ip[response.city.names["zh-CN"]]['ip'].append(i[0]) city[response.city.names["zh-CN"]] = [ response.location.longitude, response.location.latitude ] except: continue return {'ip': ip, 'city': city} except Exception as e: print e return str(e.message)
def ModifyRouteRequest(self, route_id, params): ''' 修改路由信息 ''' s = db.session() try: route = s.query(Route).filter(Route.route_id == route_id).first() if not route: return str('路由不存在') AllowableFields = [ 'pid', 'name', 'path', 'title', 'component', 'componentPath', 'cache' ] data = {} for i in params: if i in AllowableFields and params.has_key(i): data[i] = params[i] s.query(Route).filter(Route.route_id == route_id).update(data) s.commit() return True except Exception as e: print e s.rollback() return str(e.message)
def CreateDropRequest(self, isInit, params=None): db.drop_all() db.create_all() s = db.session() try: s.add(InitSql(isInit=False)) s.commit() role_id = uuid.uuid4() role = Role( role_id=role_id, name=self.role_name, mark=default['role_mark'] ) s.add(role) s.commit() password = self.__get_code() if not isInit: admin = Admin( admin_id=uuid.uuid4(), username=self.user_name, password=Config().get_md5(password), avatarUrl='', role_id=role_id ) else: admin = Admin( admin_id=params['admin_id'], username=self.user_name, password=params['password'], avatarUrl='', role_id=role_id ) s.add(admin) s.commit() self.__init_menus(s, init_menu) folder = Folder( folder_id=uuid.uuid4(), admin_id=None, name=u'系统文件', is_sys=True ) s.add(folder) s.commit() sql = s.query(InitSql).one() sql.isInit = True s.commit() return { 'username': '******', 'password': password } except Exception as e: s.rollback() print e return str(e.message)
def ModifyRoleRequest(self, role_id, params): ''' 修改鉴权信息 ''' s = db.session() try: role = s.query(Role).filter(Role.role_id == role_id).first() if not role: return str('数据不存在') is_exists = self.isSaveExists(s, params, role) if is_exists != True: return str(is_exists['error']) role.name = params['name'] role.mark = params['mark'] role.disable = params['disable'] role.menus = s.query(Menu).filter(Menu.menu_id.in_(params.getlist('menu[]'))).all() role.interfaces = s.query(Interface).filter(Interface.interface_id.in_(params.getlist('interface[]'))).all() s.commit() return True except Exception as e: print(e) s.rollback() return str(e)
def CreateRoleRequest(self, params): ''' 新建鉴权 ''' s = db.session() is_exists = self.isCreateExists(s, params) if is_exists != True: return str(is_exists['error']) try: item = Role( name=params['name'], mark=params['mark'], role_id=str(uuid.uuid4()), disable=params['disable'], menus=s.query(Menu).filter(Menu.menu_id.in_(params.getlist('menu[]'))).all(), interfaces=s.query(Interface).filter(Interface.interface_id.in_(params.getlist('interface[]'))).all() ) s.add(item) s.commit() return True except Exception as e: s.rollback() print(e) return str(e)
def QueryAdminByParamRequest(self, params, page=1, page_size=20, order_by='id'): ''' 管理员列表 ''' s = db.session() try: data = {} for i in ['role_id', 'is_disabled']: if params.has_key(i): data[i] = params[i] result = Admin.query.filter_by(**data).order_by(order_by).paginate( page, page_size, error_out=False) return { 'data': [value.to_json() for value in result.items], 'total': result.total } except Exception as e: print e return str(e.message)
def QueryInterfaceByParamRequest(self, params, page=1, page_size=20, order_by='id'): ''' 接口列表 ''' s = db.session() try: Int = ['menu_id', 'is_disabled', 'method'] data = {} for i in Int: if params.has_key(i): data[i] = params[i] result = Interface.query.filter_by(**data).filter( Interface.name.like("%" + params['name'] + "%") if params. has_key('name') else text('')).order_by(order_by).paginate( page, page_size, error_out=False) return { 'data': [value.to_json() for value in result.items], 'total': result.total } except Exception as e: print e return str(e.message)
def ModifyRoleRequest(self, role_id, params): ''' 修改权限信息 ''' s = db.session() try: role = s.query(Role).filter(Role.role_id == role_id).first() if not role: return str('数据不存在') interface = s.query(Interface).filter( Interface.interface_id.in_(params['interface_id'])).all() menu = s.query(Menu).filter(Menu.menu_id.in_( params['menu_id'])).all() role.name = params['name'] role.mark = params['mark'] role.interfaces = interface role.menus = menu s.commit() return True except Exception as e: print e s.rollback() return str(e.message)
def CreateInterfaceRequest(self, params): ''' 新建接口 ''' s = db.session() is_exists = self.isCreateExists(s, params) if is_exists != True: return str(is_exists['error'].encode('utf8')) try: menus = s.query(Menu).filter(Menu.menu_id.in_( params['menus'])).all() item = Interface(interface_id=uuid.uuid4(), name=params['name'], path=params['path'], method=params['method'], description=params['description'], mark=params['mark'], forbidden=params['forbidden'], is_disabled=params['is_disabled'], menus=menus) s.add(item) data = copy.deepcopy(item.to_json()) s.commit() return data except Exception as e: s.rollback() print e return str(e.message)
def QueryDocumentByParamRequest(self, params, page=1, page_size=20, order_by='create_time'): ''' 文档列表 ''' s = db.session() try: deleted = Document.deleted == (True if params['deleted'] == 'true' else False) folder = Document.folder_id == params['folder_id'] if params['folder_id'] == '0': folder = or_(Document.folder_id == params['folder_id'], Document.folder_id == None) status = text('') if params.has_key('status'): status = Document.status == int(params['status']) result = Document.query.filter(folder, deleted, status).order_by(order_by).paginate( page, page_size, error_out=False) return { 'data': [value.to_json() for value in result.items], 'total': result.total } except Exception as e: print e return str(e.message)
def is_in_scope(admin_id, path): ''' 路由鉴权判断 ''' s = db.session() try: admin = s.query(Admin).filter(Admin.admin_id == admin_id).first() if not admin: return str('管理员不存在') if admin.disable: return str('管理员被禁用') role = s.query(Role).filter(Role.role_id == admin.role_id, Role.disable == False).one() if role: interface = role.interfaces.filter(Interface.disable == False, Interface.path == path) if interface: return True menu = role.menus.filter(Menu.disable == False, Menu.path == path) if menu: return True return False except Exception as e: print(e) return False
def GetAllUserLoginCount(self): ''' 获取所有用户登录次数 ''' s = db.session() try: user_count = s.query( Log.username, func.count(Log.username) ).filter( Log.type == 1 ).group_by('username').all() user_list = [u'用户', u'登录次数'] data = [] for i in user_count: user_list.append(i[0]) data.append({ u'用户': i[0], u'登录次数': i[1] }) return { 'data': data, 'user': user_list } except Exception as e: print e return str(e.message)
def load_data(): url1 = "https://api.stlouisfed.org/fred/series/observations?series_id=" key = "19dede202896425a8700c0682a1b3b16" series = ["GDPC1", "UMCSENT", "UNRATE"] collected_data = collect_data(series, key, url1) session = db.session() for row in collected_data["GDPC1"]: date = row[0] value = float(row[1]) if row[1] != '.' else None d = Gdpc1(observation_date=date, gdp_value=value) session.merge(d) for row in collected_data["UMCSENT"]: date = row[0] value = float(row[1]) if row[1] != '.' else None d = UMConsumerSentimentIndex(observation_date=date, sentiment_index=value) session.merge(d) for row in collected_data["UNRATE"]: date = row[0] value = float(row[1]) if row[1] != '.' else None d = UnemploymentRate(observation_date=date, unemployment_rate=value) session.merge(d) session.commit()
def checkDb(): s = db.session() try: res = s.query(InitSql).first() return res.is_init except Exception as e: return str('数据库未连接或者其他错误请查看错误信息:%s' % e)
def is_in_scope(admin_id, path): ''' 路由权限判断 ''' s = db.session() try: admin = s.query(Admin).filter(Admin.admin_id == admin_id).first() if not admin: return str('管理员不存在') if admin.is_disabled: return str('管理员被禁用') role = s.query(Role).filter(Role.role_id == admin.role_id, Role.is_disabled == False).first() if role: i = role.interfaces.filter(Interface.is_disabled == False, Interface.path == path) if i: return True m = role.menus.filter(Menu.is_disabled == False, Menu.path == path) if m: return True r = s.query(Route).filter(Route.path == path, Route.is_disabled == False).first() if r: return True return False except Exception, e: print e return False
def get_pause_bot(): """ DEPRECATED api {get} /api/game/bot/pause/get BotPauseGet apiVersion 1.0.3 apiName BotPauseGet apiGroup DotaBots apiDescription Get the bot pause status apiHeader {String} API_KEY Restricted API_KEY necessary to call the endpoint. apiError (Errors){String} ApiKeyMissing Missing API_KEY header. apiError (Errors){String} ApiKeyInvalid Invalid API_KEY header. apiError (Errors){String} BotPauseMissing Bot pause was never set, default value is 'False'. apiSuccess {String=True,False} bot_pause Pause status of the bot. """ bot_pause = db.session().query(DynamicConfiguration).filter( DynamicConfiguration.key == 'bot_pause').one_or_none() if bot_pause is None: return jsonify({ 'success': 'no', 'error': 'BotPauseMissing', 'payload': {} }), 200 return jsonify({ 'success': 'yes', 'payload': { 'bot_pause': bot_pause.value } }), 200
def run(self): bytes = "" while not self.thread_cancelled: try: bytes += self.stream.raw.read(1024) a = bytes.find("\xff\xd8") b = bytes.find("\xff\xd9") if a != -1 and b != -1: jpg = bytes[a : b + 2] bytes = bytes[b + 2 :] img = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8), cv2.IMREAD_COLOR) framenumber = "%08d" % (self.count) screencolor = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = self.facecascade.detectMultiScale( screencolor, scaleFactor=1.3, minNeighbors=3, minSize=(30, 30), flags=cv2.CASCADE_SCALE_IMAGE ) if len(faces) == 0: pass elif len(faces) > 0: print ("Face Detected") for (x, y, w, h) in faces: cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 1) self.strpath = "C:\\Users\\nirav\Envs\\svsapp\\app\\FD\\FaceCaps\\" self.strpath += framenumber + "_" + str(self.usid) + "_" + str(self.caid) self.strpath += ".jpg" print self.strpath cv2.imwrite( "C:\\Users\\nirav\Envs\\svsapp\\app\\FD\\FaceCaps\\" + framenumber + "_" + str(self.usid) + "_" + str(self.caid) + ".jpg", img, ) self.imgret = Image.fromarray(img) if self.imgret is None: print "its none" else: readbin = open(self.strpath, "rb").read() with app.app_context(): CamImgAdd = SVSFaceTab(u_id=self.usid, cam_id=self.caid, Face_image=readbin) local_session = db.session() local_session.add(CamImgAdd) local_session.commit() print ("data is DB ") self.count += 1 except ThreadError: self.thread_cancelled = True
def populate_db(files): with app.app_context(): session = db.session() db.metadata.create_all(db.engine) main_added_counter = 0 main_updated_counter = 0 for f in files: if f.endswith('.json'): openf = 'scripts/db_files/'+ f with open(openf, 'Ur') as ifile: print ifile products = json.load(ifile, encoding="cp1252") added_counter = 0 updated_counter = 0 for product in products: item = products[product] # Set variables part_number = item['part_number'] manufacturer = item['manufacturer'] fprice = get_price(item) h, l, w = get_dimensions(item) weight = get_value('weight', item) upc = get_value('upc', item) title = get_value('title', item) # Check if item exist in database. dbproduct = get_product(part_number, manufacturer) if dbproduct is not None: update_product(dbproduct, item, session) updated_counter += 1 else: product_for_db = Product( part_number=part_number, upc = upc, manufacturer = manufacturer, title = title, primary_cost = fprice, available = True, weight = weight, height = h, width = w, length = l ) add_product(product_for_db, session) added_counter += 1 print('{0} products from {1} added to database.'.format(added_counter, manufacturer)) print('{0} products from {1} updated in the database.'.format(updated_counter, manufacturer)) main_added_counter += added_counter main_updated_counter += updated_counter print('{0} total products added to database.'.format(main_added_counter)) print('{0} total products updated in the database.'.format(main_updated_counter))
def run(self): bytes ='' while not self.thread_cancelled: try: bytes+=self.stream.raw.read(1024) a = bytes.find('\xff\xd8') b = bytes.find('\xff\xd9') if a!=-1 and b!=-1: jpg = bytes[a:b+2] bytes= bytes[b+2:] img = cv2.imdecode(np.fromstring(jpg,dtype=np.uint8),cv2.IMREAD_COLOR) framenumber ='%08d' % (self.count) screencolor = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) faces = self.facecascade.detectMultiScale(screencolor,scaleFactor = 1.3,minNeighbors=3,minSize = (30,30),flags = cv2.CASCADE_SCALE_IMAGE) if len(faces) == 0: pass elif len(faces) > 0: print("Face Detected") for (x,y,w,h) in faces: cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),1) self.strpath = "C:\\Users\\IBM_ADMIN\\Desktop\\svsapp\\svsapp\\app\\FD\\FaceCaps\\" self.strpath+=framenumber+'_'+str(self.usid)+'_'+str(self.caid) self.strpath+='.jpg' print self.strpath cv2.imwrite("C:\\Users\\IBM_ADMIN\\Desktop\\svsapp\\svsapp\\app\\FD\\FaceCaps\\" + framenumber+'_'+str(self.usid)+'_'+str(self.caid) + '.jpg',img) self.imgret = Image.fromarray(img) if self.imgret is None: print 'its none' else: #newimg = cv2.imread(self.strpath) readbin = open(self.strpath,'rb').read() #emid = SVSuserReg.query.filter_by(emid=current_user.emid).first() #camid = SVSIpCamReg.query.filter_by(u_id = current_user.id).first() with app.app_context(): CamImgAdd = SVSFaceTab(u_id = self.usid,cam_id= self.caid,Face_image = readbin) local_session = db.session() local_session.add(CamImgAdd) local_session.commit() print("data is DB ") self.count +=1 except ThreadError: self.thread_cancelled = True
def populate_db(): with app.app_context(): session = db.session() db.metadata.create_all(db.engine) products = Product.query.all() for product in products: part_number = product.part_number manufacturer = product.manufacturer sku = make_sku(part_number, manufacturer) cost = product.primary_cost res_price = make_res_price(cost) com_price = make_com_price(cost) shipping = get_shipping(product.weight) leadtime = get_leadtime(manufacturer) quantity = get_quantity() fba = get_fba() instock = get_instock() if get_item(sku) is not None: continue try: item = Catalog( sku = sku, part_number = product.part_number, cost = cost, res_price = res_price, com_price = com_price, shipping = shipping, leadtime = leadtime, quantity = quantity, manufacturer = product.manufacturer, #asin = asin, upc = product.upc, fba = fba, instock = instock, #listing_asin = asin, product_id = product.id ) db.session.add(item) db.session.commit() except: print('Unable to add to db') print(sku, res_price, cost, shipping)
def get_companies(): companies = db.session().query(Company).all() return companies
def search_by_sku(sku): product = db.session().query(Catalog).filter(Catalog.sku).first() return product
def __init__(self): self.session = db.session()