def wrap(*args, **kwargs): if 'logged_in' in session: logging.info('true') return test(*args, **kwargs) else: error = 'Unauthorised, please login' return render_template('login.html', error=error)
def api_user_put_cameras(user_id: int): logging.info('set all cameras, user: %d', user_id) cameras = request.get_json() logging.debug('request headers: %s', str(request.headers)) logging.debug('request payload: %s', str(cameras)) if cameras is None: return error_response(400, "failed") if isinstance(cameras,dict): cameras = [cameras] for c in cameras: if c.get('enabled'): del c['enabled'] #print("set cameras: ", cameras) if not bvc_db.update_cameras(user_id, cameras): return error_response(400, "failed") app.dispatcher.on_cameras_update() return flask.jsonify({}), 204
def setup_class(cls): cls.krakens_pool = {} logging.info("Initing the tests {}, let's pop the krakens".format( cls.__name__)) cls.launch_all_krakens() instances_config_files = cls.create_dummy_json() i_manager.configuration_files = instances_config_files i_manager.initialisation() #we block the stat manager not to send anything to rabbit mq def mock_publish(self, stat): pass #we don't want to initialize rabbit for test. def mock_init(): pass StatManager.publish_request = mock_publish StatManager._init_rabbitmq = mock_init #we don't want to have anything to do with the jormun database either class bob: @classmethod def mock_get_token(cls, token, valid_until): #note, since get_from_token is a class method, we need to wrap it. #change that with a real mock framework pass User.get_from_token = bob.mock_get_token @property def mock_journey_order(self): return 'arrival_time' Instance.journey_order = mock_journey_order
def api_camera_enabled(camera_id: int): if request.method == 'GET': camera, err = bvc_db.get_camera(camera_id) if camera is None: logging.error(err) return error_response(404, err) return flask.jsonify({'enabled' : camera.get('enabled', True) }) if request.method == 'PUT': enabled = request.get_json()['enabled'] if not isinstance(enabled,bool): return error_response(400, "invalid argument") res, err = bvc_db.set_camera_enabled(camera_id, enabled) if res is None: logging.error(err) return error_response(404, err) logging.info("camera [%d] enabled = %s", camera_id, enabled) app.dispatcher.on_cameras_update() return flask.jsonify(res)
def wrap(*args, **kwargs): if 'logged_in' not in session: logging.info('true') return test(*args, **kwargs) else: error = 'user currently login, Pleae Logout' return render_template('dashboard.html', error=error)
def setup_class(cls): cls.krakens_pool = {} logging.info("Initing the tests {}, let's pop the krakens".format( cls.__name__)) cls.launch_all_krakens() instances_config_files = cls.create_dummy_json() i_manager.configuration_files = instances_config_files i_manager.initialisation() cls.mocks = [] for name in cls.krakens_pool: priority = cls.data_sets[name].get('priority', 0) logging.info('instance %s has priority %s', name, priority) is_free = cls.data_sets[name].get('is_free', False) cls.mocks.append( mock.patch.object(i_manager.instances[name], 'get_models', return_value=FakeModel(priority, is_free))) for m in cls.mocks: m.start() # we check that all instances are up for name in cls.krakens_pool: instance = i_manager.instances[name] try: retrying.Retrying( stop_max_delay=5000, wait_fixed=10, retry_on_result=lambda x: not instance.is_up).call( instance.init) except RetryError: logging.exception('impossible to start kraken {}'.format(name)) assert False, 'impossible to start a kraken' #we block the stat manager not to send anything to rabbit mq def mock_publish(self, stat): pass #we don't want to initialize rabbit for test. def mock_init(): pass StatManager.publish_request = mock_publish StatManager._init_rabbitmq = mock_init #we don't want to have anything to do with the jormun database either class bob: @classmethod def mock_get_token(cls, token, valid_until): #note, since get_from_token is a class method, we need to wrap it. #change that with a real mock framework pass User.get_from_token = bob.mock_get_token @property def mock_journey_order(self): return 'arrival_time' Instance.journey_order = mock_journey_order
def teardown_class(cls): logging.info( "Tearing down the tests {}, time to hunt the krakens down".format( cls.__name__)) cls.kill_all_krakens() for m in cls.mocks: m.stop()
def api_cameras_get_all(user_id:int): logging.info('get all cameras, user: %d', user_id) cameras = bvc_db.get_cameras(user_id) return flask.jsonify({'cameras': cameras})
def wxgzh(): if request.method == 'GET': if len(request.args) == 0: return 'nothing!' return gzhsvr.when_geted(request.args) # when post user's text: # POST /wxgzh?signature=fee500230e38f00143e18c2cffd9c92e366315fd×tamp=1510654293&nonce=1176144732&openid=okUwT0h8M94dukXWhRrg1c80uboM print request.form fromoid = request.args.get('openid') usr_holder = dict(msger=None) rmode,msger = gzhsvr.when_posted(request.data, fromoid) if msger is None: return gzhsvr.rt_text(fromoid, 'unkown message!') if rmode == 'event' and if hasattr(msger, 'showmsg'): # by default, event returns by showmsg func; # if reg event func, which will be deal with reged func rp = msger.showmsg() elif rmode == 'text' and wx_replier: # text message is seperated, may work with some replier app cont = msger['Content'] rp = wx_replier(cont, fromoid) else: # by default, msssage returns by reply func and u'收到' as default return rp = msger.reply() logging.info('reply to user with: %s', rp) if rp.startswith('<xml>'): return rp else: return gzhsvr.rt_text(fromoid, rp)
def formatKafka(deviceId="", body=None): res = dict() redisDict = dict() # redisDict["deviceId"] = '{}{}'.format(code, siteCode) redisDict["deviceId"] = deviceId redisDict["deviceType"] = "4010304030602#车站点" redisDict["apiKey"] = "A4026FD47174E543EA41C538A8B430C6" redisDict["productKey"] = "jVcnIMCb3Xf" redisDict["dateTime"] = str(int(round(time.time() * 1000))) redisDict["curMapType"] = "" redisDict["longitude"] = "" redisDict["latitude"] = "" redisDict["direction"] = "" redisDict["mnc"] = "" redisDict["lac"] = "" redisDict["cellid"] = "" redisDict["messageId"] = "" redisDict["dataType"] = "1002900" redisDict["onLine"] = "1" redisDict["alarm"] = "" redisDict["simNum"] = "" redisDict["version"] = "" bytesStr = str(body).replace("\'", "\"").encode(encoding='utf-8') string = str(bytesStr, 'utf-8') partten = re.sub('None', '\"None\"', string) part = re.sub('False', '\"False\"', partten) partt = re.sub('True', '\"True\"', part) b = bytes(partt, encoding='utf-8') b64str = base64.b64encode(b) redisDict["body"] = b64str.decode() ret = bytes('{}'.format(str(redisDict).replace("\'", "\"")), 'utf-8') logging.info("数据发送kafka 参数信息 {} ".format(ret)) return ret
def api_user_new_camera(user_id: int): logging.info('set all cameras, user: %d', user_id) camera = request.get_json() logging.debug('request headers: %s', str(request.headers)) logging.debug('request payload: %s', str(camera)) if camera is None: return error_response(400, "failed") if not isinstance(camera,dict): return error_response(400, "failed") cameras = [camera] camera_id = camera.get('camera_id') for c in cameras: if c.get('enabled'): del c['enabled'] #print("set cameras: ", cameras) if not bvc_db.append_cameras(user_id, cameras): return error_response(400, "failed") app.dispatcher.on_cameras_update() return flask.jsonify({}), 201, {'location': '/api/cameras/{}'.format(camera_id)}
def sendmsg(bmsg, bkey): result = producer.send("router2shadow_jVcnIMCb3Xf", value=bmsg, key=bkey) try: _ = result.get(timeout=10) except KafkaError as kerr: print(kerr) logging.info("数据发送kafka成功 参数信息 {} ".format(result))
def api_cameras_delete(camera_id): logging.info('detete camera: %d', camera_id) if not bvc_db.delete_camera(camera_id): return error_response(404, "not found") app.dispatcher.on_cameras_update() return flask.jsonify({}), 204
def run(): # app.run() # app.debug = True try: WSGIServer(app, bindAddress='./hello-world.sock', umask=0000).run() except (KeyboardInterrupt, SystemExit, SystemError): logging.info("Shutdown requested...exiting") except Exception: traceback.print_exc(file=sys.stdout) db.close()
def api_cameras_get_enabled(): logging.info('get active cameras, %s', current_identity.id) if current_identity.id[:5] != 'reco-': return error_response(403, "") reco_id = current_identity.id[5:] cameras = app.dispatcher.on_reco_get_cameras(reco_id) return flask.jsonify({'cameras': cameras})
def query_no_assert(self, url, display=False): """ query url without checking the status code used to test invalid url return tuple with response as dict and status """ response = self.tester.get(url) json_response = json.loads(response.data) if display: logging.info("loaded response : " + json.dumps(json_response, indent=2)) return json_response, response.status_code
def select(sql, args, size=None): log(sql, args) global __pool with (yield from __pool) as conn: cur = yield from conn.cursor(aiomysql.DictCursor) yield from cur.execute(sql.replace('?', '%s'), args or ()) if size: rs = yield from cur.fetchmany(size) else: rs = yield from cur.fetchall() yield from cur.close() logging.info('rows returned: %s' % len(rs)) return rs
def on_reco_instance_request(self, reco_id): i = reco_id.rfind(':') if i >= 0: instance_id = reco_id[:i] process_id = reco_id[i+1:] else: instance_id = reco_id process_id = '0' logging.info('on_reco_instance_request, \'%s\', \'%s\'', instance_id, process_id) pass
def insertSql(deviceId): url = 'http://192.168.2.13:80/code/product.do?add' body = { "devName": "车辆状态信息", "devType": "C01C01C01", "devNewId": deviceId, "devOldId": "", "orgid": "1001" } headers = {'content-type': "application/json"} response = requests.post(url, data=json.dumps(body), headers=headers) retdata = response.text logging.info("deviceId 添加数据库成功 ".format(retdata))
def login(): error = None if request.method == 'POST': username = request.form["username"] password_insert = request.form["password"] remember = request.form.getlist('Remember_me') db = mysql.connector.connect(**config) mycursor = db.cursor() mycursor.execute("USE abraham") mycursor.execute("SELECT * FROM log_details WHERE username = %s", [username]) data = mycursor.fetchone() if data != 0: #logic to determine if the username is in the database password = data[2] if sha256_crypt.verify(password_insert, password): #method to verify is the inputed password match with the password in the database with the specified username logging.info('password matched') db.close() gc.collect() session['logged_in'] = True #creating a session for the user after logging_in session['username'] = request.form['username'] flash('You were successfully logged in') return redirect(url_for('Dashboard', username=username)) else: logging.info('wrong credentials') error = 'wrong credentials' return render_template('login.html', error=error) else: error = 'No user' logging.info('no user') return render_template('login.html', error=error) else: error = 'wrong method' logging.info('wrong method') return render_template('login.html', error=error)
def register(): if request.method == "POST": #check which method was used username = request.form["username"] email = request.form["email"] password = sha256_crypt.hash((str(request.form["password"]))) #hashing and salting the password comfirm = request.form["comfirm password"] if sha256_crypt.verify(comfirm, password): db = mysql.connector.connect(**config) #connecting to mysql database mycursor = db.cursor() #creating cursor object mycursor.execute("USE abraham") mycursor.execute("SELECT * FROM log_details WHERE username = %s", [username]) #selecting "username" from the table "log_details" data = mycursor.fetchone() #fecting the first row of the output result in case of multi-rows if data != None: logging.info('invalid credentials') error = 'invalid credentials' return render_template('register.html', error=error) #logic to determine if the username exist in the database before so as to eliminate the case of having two similar username in the database else: mycursor.execute("INSERT INTO log_details (username, email, password) VALUES (%s, %s, %s)",(username, email, password)) db.commit() db.close() flash('registration successful') logging.info('registration successful') #log the details of the state of the application return render_template('login.html') else: logging.info('password does not match') error = 'Password does not match' return render_template('register.html', error=error) else: error = 'wrong method' logging.info('wrong method') return render_template('register.html', error=error)
def create_pool(loop, **kw): logging.info('create database connection pool...') global __pool __pool = yield from aiomysql.create_pool(host=kw.get('host', 'localhost'), port=kw.get('port', 3306), user=kw['user'], password=kw['password'], db=kw['db'], charset=kw.get('charset', 'utf8'), autocommit=kw.get( 'autocommit', True), maxsize=kw.get('maxsize', 10), minsize=kw.get('minsize', 1), loop=loop)
def saveNewCompany(): """ Parameters:{business_name,name,address,phone} Description: Saves in DB new company """ logging.info("entra a save company") response={} try: if request.method == 'POST': flag,dict=toDict(request.form,'post') if flag: logging.info("success: %s"%dict) for k,v in dict.iteritems(): if len(v.strip())==0: response['success']=False response['msg_response']='Existen campos vacíos, no es posible realizar el registro de la empresa.' break if 'success' not in response: new_folder=replaceString(dict['business_name'])[0:10] company=db.insert('system.company',dict) folder="%s_%s"%(new_folder,company['company_id']) db.query(""" update system.company set task_folder='%s' where company_id=%s """%(folder,company['company_id'])) logging.info(company) # if not os.path.exists('/usr/local/arctic/tmp/%s'%folder): # os.makedirs('/usr/local/arctic/tmp/%s'%folder) # uid = pwd.getpwnam("pgarcia").pw_uid # gid = grp.getgrnam("pgarcia").gr_gid # path = '/usr/local/arctic/tmp/%s'%folder if not os.path.exists('%s%s'%(cfg.task_path,folder)): os.makedirs('%s%s'%(cfg.task_path,folder)) uid = pwd.getpwnam(cfg.admin_uid).pw_uid gid = grp.getgrnam(cfg.admin_gid).gr_gid path = '%s%s'%(cfg.task_path,folder) os.chown(path, uid, gid) response['success']=True response['msg_response']='La empresa <b>%s</b> ha sido registrada.'%dict['name'] else: response['success']=False response['msg_response']='Ocurrió un error al intentar obtener los datos del formulario, favor de intentarlo nuevamente.' else: logging.info("GET") response['success']=True response['msg_response']='La empresa ha sido registrada exitosamente.' except: response['success']=False response['msg_response']='Ocurrió un error al intentar registrar la empresa.' exc_info = sys.exc_info() app.logger.info(traceback.format_exc(exc_info)) return json.dumps(response)
def api_alerts(): data = request.get_json() camera_id = data.get('camera_id', None) if camera_id is None: return error_response(400, "invalid arguments") alert_type = data.get('alert_type_id') if alert_type is None: return error_response(400, "invalid arguments") logging.info("new alert: camera [%d], type: %s", camera_id, alert_type) return flask.jsonify({}), 201
def query(self, url, display=False, **kwargs): """ Query the requested url, test url status code to 200 and if valid format response as dict display param dumps the json (used only for debug) """ response = check_url(self.tester, url, **kwargs) assert response.data json_response = json.loads(response.data) if display: logging.info("loaded response : " + json.dumps(json_response, indent=2)) assert json_response return json_response
def api_rs(): if current_identity.id[:5] != 'reco-': return error_response(403, "") data = request.get_json() reco_id = current_identity.id[5:] logging.info("ps: %s %s", reco_id, str(data)) if reco_id is None: return error_response(400, "invalid arguments") cameras_count = data.get('cameras_count', 0) fps = data.get('fps', 0.0) app.dispatcher.on_reco_state(reco_id, cameras_count, fps) return flask.jsonify({}), 204
def dashboard(): colors = ['Daily', 'Monthly', 'Yearly'] cur = connection.cursor() cur1 = connection.cursor() cur2 = connection.cursor() cur3 = connection.cursor() email = session['email'] cur2.execute('select user_id from user where email = %s', email) result2 = cur2.fetchone() result2d = result2['user_id'] #print(result2d) dude = [] result = cur.execute('select video_id from video') res = [] if result > 0: data = cur.fetchall() for i in data: print('i', i) cur1.execute( 'select video_id from vd_subscription where user_id = %s', result2d) result1 = cur1.fetchall() print('result1', result1) if i not in result1: res.append(i) print('res', res) for k in res: cur3.execute('select * from video where video_id = %s', k['video_id']) result3 = cur3.fetchall() dude.append(result3[0]) print('dude', dude) cur.close() cur1.close() cur2.close() else: logging.info("Error in video fetch") return render_template('dashboard.html', dude=dude, colors=colors)
def find_nearest(latitude, longitude, distance): # Create SQL cursor. cur = mysql.connect.cursor() # Euclidean distance b/w two points. # p = (p1, p2) ; q = (q1, q2) # d = sqrt((q1-p1)^2 + (q2-p2)^2) # d_sqrd = distance * distance last_month = datetime.datetime.now( ) - dateutil.relativedelta.relativedelta(months=3) last_month_first_date = last_month.replace(day=1) date = last_month_first_date.strftime("%Y-%m-%d") date_format = "%%Y-%%m-%%d" print(date) query = "SELECT id, title, mag, timestamp, latitude, longitude, depth \ FROM earthquakes WHERE \ POW(longitude-%s, 2) + POW(latitude-%s, 2) <= 1 \ AND timestamp >= STR_TO_DATE(%s, '%%Y-%%m-%%d')" print(query) cur.execute(query, (longitude, latitude, date)) results = cur.fetchall() logging.info(results) cur.close() # Create an array of all the earthquake occurrences. print("here!") occurences = [] for occ in results: # [TODO] added a temp ID. print(occ[6]) occurences.append( Earthquake(occ[0], occ[1], occ[2], occ[3], occ[4], occ[5], occ[6])) cur.close() # Returns an array of Earthquakes. return occurences
def dogrid(): logging.info("entra a funcion dogrid") form = RegisterNewCompany(request.form) if request.method == 'POST' and form.validate(): logging.info("entra if") logging.info(request.form) return redirect(url_for(index)) return render_template('home.html', form=form)
def send_fcm_message(check_time, account_id, node_type, chat_type, contents, param): logging.info("send_fcm_message") user_datetime_object = time.strptime(check_time, '%H:%M') user_time = datetime.time(user_datetime_object[3], user_datetime_object[4]).strftime("%H:%M") now_time = datetime.datetime.now().strftime("%H:%M") logging.info("now_time > user_time", now_time, user_time) if now_time > user_time: if chat_type == 4: for content in contents: chat = Chat(account_id=account_id, content=content, node_type=node_type, chat_type=chat_type, time=str(int(time.time() * 1000)), isBot=1) db.session.add(chat) elif chat_type == 5: for content in contents: chat = Chat(account_id=account_id, content=content, node_type=node_type, chat_type=chat_type, time=str(int(time.time() * 1000)), isBot=1, carousel_list=str( param['data']['result']['events'])) db.session.add(chat) db.session.commit() tokens = FcmToken.query.filter(FcmToken.account_id == account_id).all() for token in tokens: # send the fcm notification print("메세지 전송 얍!") logging.info("메세지 전송 : ", token) push_service.notify_single_device(registration_id=token.token, data_message=param, content_available=True) return True return False