def read_from_file(): db.database() with open("captalesduMonde/cap.txt") as file: for line in file: line = line.rstrip('\n') country, city = line.split(',') wolrd[country] = city
def run(self): sendSkt = lightblue.socket() sendSkt.bind(("", 0)) sendSkt.listen(1) lightblue.advertise("SMS Gateway (Response Thread)", sendSkt, lightblue.RFCOMM) db = database() conn2, addr2 = sendSkt.accept() print "Connected to Response Server", addr2 while 1: time.sleep(1) db = database() rows = db.popOutboxMsg() for row in rows: print "Sending Msg -> %s" % (row[0]) sms = SMS(str(row[0]), row[1], row[2], row[3], str(row[4])) toSend = sms.toXML() print toSend conn2.send(toSend.replace("\n", "\\n")) res = conn2.recv(1024) print res while (res != "1" and res != "2"): res = conn2.recv(1024) print res db.setOutboxProcessed(str(row[0]), res)
def publish(bot, update, user_data): """publish item""" item = user_data['item'] database().item.save(item) update.message.reply_text('Item saved!', reply_markup=ReplyKeyboardRemove()) return ConversationHandler.END
def add_flag(user,flags): j=IsRegister(user) if j[0] == True: for i in flags: if i in ["f","j","k","o","p","q","r","s","t","v","F","S"] and not i in arrays.DB_user[j[1]][2]: arrays.DB_user[j[1]][2].insert(0,i) db.database("API/DB/DB_user",arrays.DB_user).W_db() a=info(4,user) a="".join(a) return "Flags(%s): %s" % (user,a)
def addHotel(data): hotels = database("hotels") util = database("util") data['id'] = str(util.get("name", "num_hotels")[0]['value']) if hotels.insert(data): util.change("name", "num_hotels", "value", util.get("name", "num_hotels")[0]['value'] + 1) return True else: return False
def delete_item(bot, update, groups): # todo: спросить, уверен ли id = groups[0] item = database().item.get(id=id, userID=update.message.from_user.id, all=False) if item is None: update.message.reply_text('Product with ID "%s" not found' % id) return item.is_active = False update.message.reply_text('Item "%s" has been deleted' % item.decorator().get_title()) database().item.save(item)
def del_flag(user,flags): j=IsRegister(user) if j[0] == True: for i in flags: if i in arrays.DB_user[j[1]][2]: a=arrays.DB_user[j[1]][2].index(i) del arrays.DB_user[j[1]][2][a] db.database("API/DB/DB_user",arrays.DB_user).W_db() a=info(4,user) a="".join(a) return "Flags(%s): %s" % (user,a)
def deactivate(bot, update): chatID = update.message.chat_id subscription = database().subscription.get(chatID=chatID, all=False) if not subscription: update.message.reply_text("Sorry, you are not signed yet") database().subscription.unsubscribe(chatID) update.message.reply_text( 'Subscription cancelled. Hope you found it interesting!' '\n\nPlease, comment your suggestions, will be taken into account :)')
def delete_item(bot, update, groups): # todo: спросить, уверен ли id = groups[0] item = database().item.get(id=id, userID=update.message.from_user.id, all=False) if item is None: update.message.reply_text('Товар с идентификатором "%s" не найден' % id) return item.is_active = False update.message.reply_text('Товар "%s" был удалён' % item.decorator().get_title()) database().item.save(item)
def query1(): result = [] # creo obj db OMS de la forma 2 oms = db.database('oms') query = """ SELECT ORDERS.TC_ORDER_ID AS FOLIO, OMSEOMCLPR.PURCHASE_ORDERS_STATUS.DESCRIPTION AS ESTADO FROM PURCHASE_ORDERS_LINE_ITEM INNER JOIN ORDER_LINE_ITEM ON ORDER_LINE_ITEM.MO_LINE_ITEM_ID = PURCHASE_ORDERS_LINE_ITEM.PURCHASE_ORDERS_LINE_ITEM_ID INNER JOIN ORDERS ON ORDER_LINE_ITEM.ORDER_ID = ORDERS.ORDER_ID INNER JOIN PURCHASE_ORDERS ON ORDERS.PURCHASE_ORDER_ID = PURCHASE_ORDERS.PURCHASE_ORDERS_ID INNER JOIN OMSEOMCLPR.PURCHASE_ORDERS_STATUS ON PURCHASE_ORDERS_LINE_ITEM.PURCHASE_ORDERS_LINE_STATUS = OMSEOMCLPR.PURCHASE_ORDERS_STATUS.PURCHASE_ORDERS_STATUS WHERE ORDERS.TC_ORDER_ID LIKE '12758999%'; """ oms.cursor.execute(query) oms_result = oms.cursor.fetchall() oms.cursor.close() # creo obj db SAB de la forma 1 sab = db.database('sab') for folio,estado in oms_result: query2 = """ SELECT b.CNPEDIDO AS ID, b.CFUNCION AS FUNCION, b.FCREAREG AS REGISTRO FROM f132hist b, (SELECT Max(h.FCREAREG) fecha, h.CNPEDIDO FROM f132hist h WHERE h.CNPEDIDO in('%s') GROUP BY h.CNPEDIDO) query1 WHERE b.FCREAREG = query1.fecha AND b.CNPEDIDO = query1.CNPEDIDO AND (b.CNPEDIDO in('%s')) """ %(folio,folio) sab.cursor.execute(query2) row = sab.cursor.fetchone() if not row: pass else: row = { 'FOLIO' :folio, 'ESTADO' :estado, 'ID' :row.ID, 'FUNCION' :row.FUNCION, 'REGISTRO':row.REGISTRO } result.append(row) sab.cursor.close() return (result)
def main(): scanner = Scan(config.get('scan','dest')) config.set('db','netname',scanner.netname) try: db = database(config.get('db','path')) except OperationalError, e: # init dabase os.makedirs('/'.join(config.get('db','path').split('/')[:-1])) db = database(config.get('db','path')) schame = config.get('db','schema') tablename = config.get('db','netname') db.initTable(schame,tablename,scanner.iplist)
def deactivate(bot, update): chatID = update.message.chat_id subscription = database().subscription.get(chatID=chatID, all=False) if not subscription: update.message.reply_text('Это странно, но ты и так не подписан.') database().subscription.unsubscribe(chatID) update.message.reply_text( 'Подписка деактивировна. Надеюсь, ты нашел всё, чего тебе не хватало!' '\n\nЕсли соскучишься за новыми штуками - скажи /subscribe, я снова буду тебе спамить :)' )
def register(user, host, password): a=IsRegister(user) if a[0] == False: j=[[user, host],password,[],0,["status","connected"]] arrays.DB_user.append(j) i=IsRegister(user)[0] if i == True: db.database("API/DB/DB_user",arrays.DB_user).W_db() return "Se completo el registro." elif i == False: return "No se pudo completar el registro." else: return "Ya se encuentra registrado."
def addAdmin(data): admins = database("admins") util = database("util") if not data.has_key("username") or len( admins.get("username", data["username"])) > 0: return False data['id'] = str(util.get("name", "num_admins")[0]['value']) if admins.insert(data): util.change("name", "num_admins", "value", util.get("name", "num_admins")[0]['value'] + 1) return True else: return False
def test_database(self): db.setup(config, adapter='pymysql') self.assertEqual(db.database(), db.database('default', slave=True)) conns = getattr(db, '__db', []) self.assertEqual(len(conns['default.slave']), 1) db.setup(config, slave=True) self.assertNotEqual(db.database(), db.database('default', slave=True)) conns = getattr(db, '__db', []) self.assertEqual(len(conns['default.slave']), 1) db.setup(config, slave=True) conns = getattr(db, '__db', []) self.assertEqual(len(conns['default.slave']), 2)
def test_database(self): db.setup(config,adapter='pymysql') self.assertEqual(db.database(), db.database('default', slave=True)) conns = getattr(db, '__db', []) self.assertEqual(len(conns['default.slave']), 1) db.setup(config, slave=True) self.assertNotEqual(db.database(), db.database('default', slave=True)) conns = getattr(db, '__db', []) self.assertEqual(len(conns['default.slave']), 1) db.setup(config, slave=True) conns = getattr(db, '__db', []) self.assertEqual(len(conns['default.slave']), 2)
def activate(bot, update): chatID = update.message.chat_id if database().subscription.get(chatID=chatID, all=False): update.message.reply_text( 'Подписка уже активна. Скажи /unsubscribe, чтобы отписаться') return subscription = Subscription(chatID) database().subscription.save(subscription) update.message.reply_text( 'Подписка активирована. При добавлении нового объявления другим учатником, ты получишь ' 'уведомление в этом чате и сможешь забрать крутую штукень первым!' '\n\nЕсли уведомления тебе станут неинтересными - скажи /unsubscribe, чтобы отписаться.' )
def activate(bot, update): chatID = update.message.chat_id if database().subscription.get(chatID=chatID, all=False): update.message.reply_text( 'The subscription is already active. Say /unsubscribe to unsubscribe' ) return subscription = Subscription(chatID) database().subscription.save(subscription) update.message.reply_text( 'Subscription enabled, you will receive notes with offers from other members' 'in this chat and you can pick up the cool thing first!' '\n\ntype /unsuscribe if you want to stop further notifications.')
def addReservation(data): if possibleReservation(data['what'], data['from'], data['to']) <= 0: return False if possibleReservation(data['what'], data['from'], data['to']) - int( data['quantity']) < 0: return False reservations = database("reservations") util = database("util") data['id'] = str(util.get("name", "num_reservations")[0]['value']) if reservations.insert(data): util.change("name", "num_reservations", "value", util.get("name", "num_reservations")[0]['value'] + 1) return True else: return False
def server_recv(self,clntsock): # instruction receive #try: print('waiting to recv message from client') data_recv=clntsock.recv(2048) print(data_recv) data=pickle.loads(data_recv) print(data) if data[0] == 'close_thread': db = pymysql.connect(host='localhost', user='******', password='******', db='project_db', charset='utf8') curs = db.cursor() curs.execute("update profile set online=0 where id=%s",(data[1],)) db.commit() db.close() return False elif data[0] == 'exit_login': return False elif data[0] == 'img_send': ftp_sock = ftp_server.ftp(data) ftp_sock.img_recv() elif data[0] == 'img_recv': ftp_sock = ftp_server.ftp(data) ftp_sock.img_send() #else: server_db = database() server_db.get_data(data,clntsock) if data[0]=='count_users': data.append(len(self.c_list)) self.server_send(data,clntsock) return True
def all(bot, update): items = database().item.get() if len(items) == 0: update.message.reply_text('Нет ни одного товара') return send_items(update, items)
def my_items(bot, update): items = database().item.get(userID=update.message.from_user.id) if len(items) == 0: update.message.reply_text('У тебя нет ни одного товара. Пиши /add, чтобы добавить') return send_items(update, items)
def all(bot, update): items = database().item.get() if len(items) == 0: update.message.reply_text('There are no products.') return send_items(update, items)
def get_db(): if Utils.reconnect > 5: return None try: if not Utils.mysql_db: Utils.mysql_db = db.database(dbn="mysql",host=Utils.settings['MYSQL_SERVER'], db=Utils.settings['MYSQL_DB'], user=Utils.settings['MYSQL_USER'], pw=Utils.settings['MYSQL_PWD']) Utils.mysql_db.select(Utils.settings['MYSQL_LOG_TABLE'], what="1", limit=1) return Utils.mysql_db except: Utils.reconnect += 1 print "db connect error and reconnect:%s" % Utils.reconnect time.sleep(10) Utils.mysql_db = db.database(dbn="mysql",host=Utils.settings['MYSQL_SERVER'], db=Utils.settings['MYSQL_DB'], user=Utils.settings['MYSQL_USER'], pw=Utils.settings['MYSQL_PWD']) return Utils.mysql_db
def get_raw_rsp(flow): headers = str(flow.response.headers) body = flow.response.body db = database() cur = db.connectdb('./db.sqlite3') negative_type = db.query( cur, '''select value from minions_settings where setting='negative_type' ''' )[0][0].split('|') """ if flow.response.headers['content-type'] != []: content_type = flow.response.headers['content-type'].split(';')[0] #如content-type存在,过滤content-type类型为css等 else: m = magic.Magic(magic_file=r'C:\python27\magicfile\magic',mime=True) content_type = m.from_buffer(body) if content_type in negative_type: body = base64.b64encode(body) else: if chardet.detect(body)['encoding']: encode_type = chardet.detect(body)['encoding'] body = body.decode(encode_type,'replace') """ body = autodecode(body) rsp = headers + '\n' + body rsp = rsp.replace("'", "''") return rsp
def testH(self): db.addVideo(tests.user_id, tests.title, tests.description, tests.image, tests.video, tests.category_id, tests.origin) dbc = db.database() try: with dbc.cursor(pymysql.cursors.DictCursor) as cursor: sql = "SELECT video_id FROM videos WHERE title = '{}'".format(tests.title) cursor.execute(sql) result = cursor.fetchone() # Setting the video id of test video video_id = result['video_id'] setVideoId(video_id) except Exception as e: print(e) finally: dbc.close() self.assertEqual(video_id, getVideoId())
def __init__(self): self.database = database() self.config = config() self.port = self.config.getLocalMonitorPort() self.xmlHandler = xmlHandler() self.startServer()
def addIncentive(self, cursor): try: name = input("Enter name of employee. !") args = ['%' + name + '%'] cursor.execute('SELECT * FROM dbo.Employee where employee_name like ?', args) dash = '-' * 180 data = cursor.fetchall() if len(data) != 0: print(dash) print('{:<5s}{:>30s}{:>30s}{:>30s}{:>30s}{:>30s}'.format("Id", "Name", "Designation", "DOB", "PPS", "Salary")) print(dash) for row in data: print( '{:<5s}{:>30s}{:>30s}{:>30s}{:>30s}{:>30s}'.format(str(row[0]), row[1], row[2], row[4], row[5], str(row[6]))) empid = input("Enter employee id from above.!") db = database() incentive_date = input("Enter incentive date") db.insertIncentive(empid,incentive_date) else: print("No employee found with that name.!") except: print ("Something went wrong.!! Contact the administrator.!")
def run(self): print "Vulscan thread is running!" db = database() cur = db.connectdb('./db.sqlite3') settings = dict( db.query(cur, '''select setting,value from webmanager_settings''')) sqlmap_srv = settings['server'] if settings['upstream_enabled'] == 'true': upstream_proxy = settings['upstream_proxy'] else: upstream_proxy = None db.closedb(cur) if settings['sqlmap_enabled'] == 'true': sqliscan = AutoSqli(server=sqlmap_srv, scan_flow=self.flow, level=settings['level'], risk=settings['risk'], proxy=upstream_proxy) #sqliscan = AutoSqli(server= sqlmap_srv,scan_flow = self.flow) thread.start_new_thread(sqliscan.run, ()) #考虑到调用不同扫描模块,这里再次利用线程调用sqlmap if settings['xss_enabled'] == 'true': xsserscan = XsserScan(scan_flow=self.flow) thread.start_new_thread(xsserscan.run, ()) #调用xsser
def authUser(usern, passw): users = database("users") if len(users.get("username", usern)) == 1 and users.get( "username", usern)[0]['password'] == passw: return True else: return False
def console(): db = database() while True: try: args = sys.stdin.readline()[:-1].split() if len(args) == 0: continue elif args[0] == "END" and len(args) ==1: break elif args[0] == "BEGIN" and len(args) == 1: db.begin() elif args[0] == "COMMIT" and len(args) == 1: db.commit() elif args[0] == "ROLLBACK" and len(args) == 1: db.rollback() elif args[0] == "SET" and len(args) == 3: db.Set(args[1],args[2]) elif args[0] == "GET" and len(args) == 2: db.get(args[1]) elif args[0] == "UNSET" and len(args) == 2: db.unset(args[1]) elif args[0] == "NUMEQUALTO" and len(args) == 2: db.numEqualTo(args[1]) else: print "Invalid command or parameters." except KeyboardInterrupt: break
def list_items(bot, update): items = database().item.get(userID=update.message.from_user.id) if len(items) == 0: update.message.reply_text('You have no active items. Do you want to create one? Type /add') return send_items(update, items)
def authAdmin(usern, passw): admins = database("admins") if len(admins.get("username", usern)) == 1 and admins.get( "username", usern)[0]['password'] == passw: return True else: return False
def addManufacturer(self, cursor): try: db = database() self.manufacturerName = input("Enter name of manufacturer.") mname = self.manufacturerName while not validator.nameValidate(mname): mname = input("Enter name of manufacturer.") self.manufacturerName = mname self.manufacturerAddr = input("Enter manufacturer's address.") addr = self.manufacturerAddr while not validator.addrValidate(addr): addr = input("Enter manufacturer's address.") self.manufacturerAddr = addr self.manufacturerEmail = input("Enter manufacturer's email.") addr = self.manufacturerEmail while not validator.emailValidate(addr): addr = input("Enter manufacturer's email.") self.manufacturerEmail = addr self.manufacturerPhno = input( "Enter manufacturer's contact number.") addr = self.manufacturerPhno while not validator.numberValidate(addr): addr = input("Enter manufacturer's contact number.") self.manufacturerPhno = addr db.insertMf(self.manufacturerName, self.manufacturerAddr, self.manufacturerEmail, self.manufacturerPhno) print("Record inserted successfully in Manufacturer table.!") except: print("Something went wrong.!! Contact the administrator.!")
def edit(bot, update, groups, user_data): reply_keyboard = [[ '/skip', ]] id = groups[0] item = database().item.get(id=id, userID=update.message.from_user.id, all=False) if item is None: update.message.reply_text('Товар с идентификатором "%s" не найден' % id) return user_data['item'] = item update.message.reply_text( 'В сообщении ниже находится текущее имя товара. ' 'Напишите новое, или нажмите /skip, чтобы оставить его без изменений\n' ) update.message.reply_text(item.itemName, reply_markup=ReplyKeyboardMarkup( reply_keyboard, one_time_keyboard=True, resize_keyboard=True)) return NAME
def list_items(bot, update): items = database().item.get(userID=update.message.from_user.id) if len(items) == 0: update.message.reply_text('У тебя нет активных товаров. Хочешь создать? Пиши /add') return send_items(update, items)
def __init__(self, lcd_pin_rs=4, lcd_pin_e=24, lcd_pins_db=[23, 17, 21, 22], GPIO = None): # TODO: Set modes of both arn't set properly - check NFC before test self.db = database() if(self.isDeviceActive('lcd')): self.lcd = lcd() if(self.isDeviceActive('nfc')): self.nfc = nfc()
def all_items(bot, update): items = database().item.get() if len(items) == 0: update.message.reply_text('Нет ни одного товара') return for item in items: respond_item(update, item)
def item(bot, update, groups): id = groups[0] item = database().item.get(id=id, all=False) if item is None: update.message.reply_text('Товар с идентификатором "%s" не найден' % id) return respond_item(update, item)
def db_execute(self, sql, args=()): db = database(**self.dbinfo) ret = db.execute(sql, args) if ret > 0: db.commit() else: db.rollback() return ret, db._code, db._msg
def performBackup( dataID ): log("trying to perform backup for dataID " + str( dataID) ) c = config() MAINVOLUME = c.getMainVolume() debug = c.getDebug() data = database() container = data.getDataContainer( dataID )[0] if( container.type == "rsync" ): if container.options == "" or container.options == None: checkDirs( container ) rsync_cmd = "rsync -avz " + container.remotePath + " " + MAINVOLUME + "/" + container.localPath + "/cur/" returnValue = 0 id = 0 #get directory size before backup start_size = getDirectorySize( MAINVOLUME + "/" + container.localPath + "/cur/" ) log( rsync_cmd ) id = data.startJob( "rsync" , int(dataID)) returnValue, errorMessage, output = executeCommand( rsync_cmd ) #if len(errorMessage) == 0: # errorMessage = output log( "backup command returned: " + str(returnValue )) #get directory size after backup final_size = getDirectorySize( MAINVOLUME + "/" + container.localPath + "/cur/" ) transferredSize = final_size - start_size log( "transferred " + str(transferredSize) + "kb") if int(returnValue) == 0: data.finishJob(int(dataID), int(id), "finished", errorMessage, output, transferredSize) #start to archive the backup, if necessary archive , method , compress,ttl = data.getArchiveInfo( int(dataID) ) if archive != "disabled": id = data.startJob( "archive" , int(dataID)) archiveFolder( container , method , compress ) data.finishJob( int(dataID),int(id), "finished","","", 0) mailBody = "Backup finished on host '" + str(c.getHostname()) + "'\n" mailBody += "Job for dataID " + str(dataID) + " was succesful: " + str(output) notifyByMail( mailBody ) else: #Oh, the backup was not successful. Maybe we should try again later? data.finishJob( int(dataID), int(id), "aborted", errorMessage, output, transferredSize ) mailBody = "Backup aborted on host '" + str(c.getHostname()) + "'\n" mailBody +="Job for dataID " + str(dataID) + " was not succesful: " + str(errorMessage) notifyByMail(mailBody) else: log("Unsupported container type: %s" % container.type) syncMonitorData()
def checkSyncDirs(): c = config() d = database() container = d.getDataContainer("") dir = c.getSyncDir() if dir != "" and dir[-1] == "/": dir = dir[:-1] if dir != "" and os.path.isdir( dir ): for con in container: if os.path.isdir( dir + "/" + con.name ) and con.name != "" and con.name !="." and os.listdir(dir + "/" + con.name) != [] : dest_path = MAINVOLUME + "/" + con.name + "/cur/" os.system("mv " + dir + "/" + con.name + "/* " + dest_path )
def setup_test(): from db import database db = database( 'mysql', host='database', db='test', user='******', passwd='password' ) delete_storage(db) create_storage(db) return db
def characterIsSimpTrad(c, simpTrad): from db import database from cjklib import characterlookup thislocale, otherlocale = simpTrad == 0 and ("C", "T") or ("T", "C") clookup = characterlookup.CharacterLookup(thislocale, dbConnectInst=database()) # NB: not sure that thisLocale actualy makes any difference.. # Find all the variants of this character for the relevant locales othervariants = clookup.getCharacterVariants(c, otherlocale) thisvariants = clookup.getCharacterVariants(c, thislocale) # If there are any variants at all, guess that we must have a character in the original locale. # To deal nicely with situations where we lack data, guess that things are in the requested locale # if we *also* don't have any versions of them in the original locale. return len(othervariants) != 0 or len(thisvariants) == 0
def setup_test(): def create_test_tables(db): db( """ create table if not exists entities ( id int not null auto_increment, kind varchar(100), PRIMARY KEY (id) ) """ ) db( """ create table if not exists attributes ( id int not null auto_increment, kind varchar(100), row_id int not null, attribute varchar(100), datatype varchar(30), value text, PRIMARY KEY (id), KEY `row_id_key` (`row_id`), KEY `kind_key` (`kind`), KEY `kv` (`kind`, `attribute`, `value`(100)) ) """ ) def delete_test_tables(db): db('drop table if exists attributes') db('drop table if exists entities') from db import database db = database( 'mysql', host='database', db='test', user='******', passwd='password' ) delete_test_tables(db) create_test_tables(db) return db
def run(self): print "Vulscan thread is running!" db = database() cur = db.connectdb('./db.sqlite3') settings = dict(db.query(cur,'''select setting,value from webmanager_settings''')) sqlmap_srv = settings['server'] if settings['upstream_enabled'] == 'true': upstream_proxy = settings['upstream_proxy'] else: upstream_proxy = None db.closedb(cur) if settings['sqlmap_enabled'] == 'true': sqliscan = AutoSqli(server= sqlmap_srv,scan_flow = self.flow,level=settings['level'],risk=settings['risk'],proxy=upstream_proxy) #sqliscan = AutoSqli(server= sqlmap_srv,scan_flow = self.flow) thread.start_new_thread(sqliscan.run,()) #考虑到调用不同扫描模块,这里再次利用线程调用sqlmap if settings['xss_enabled'] == 'true': xsserscan = XsserScan(scan_flow = self.flow) thread.start_new_thread(xsserscan.run,()) #调用xsser
def __init__(self, server='', scan_flow ='',level=1,risk=1,proxy=None): super(AutoSqli, self).__init__() self.server = server if self.server[-1] != '/': self.server = self.server + '/' self.scan_flow = scan_flow self.target = scan_flow.request.url self.taskid = '' self.engineid = '' self.status = '' self.headers = dict(scan_flow.request.headers) self.data = scan_flow.request.body #self.referer = scan_flow.request.headers['referer'] if 'cookie' in scan_flow.request.headers: self.cookie = scan_flow.request.headers['cookie'] else: self.cookie = '' self.start_time = time.time() self.db = database() self.cur = self.db.connectdb('./db.sqlite3') self.level = level self.risk = risk self.proxy = proxy
def setup(self, instance_path): def existing(path, subdir=None): """Returns existing directories only""" pathname = path and subdir and os.path.join(os.path.abspath(path), subdir) or path and os.path.abspath(path) if pathname and os.path.exists(pathname): return pathname self.start_time = timeit.default_timer() self.lib_path = os.path.split(os.path.abspath(__file__))[0] self.instance_path = os.path.abspath(instance_path) if '.' not in sys.path: sys.path.insert(0, '.') self.config = config = cfg.Config(instance_path,request.server) self.request = request self.server_name = request.server #env.get('SERVER_NAME','localhost') # get current site directory self.root = os.path.split(os.path.abspath(os.getcwd()))[0] self.uri = config.get('site','uri','/') if self.uri[-1]=='/': self.uri = self.uri[:-1] # get site info self.site = Site( name = '', theme = '', home = os.path.join(config.sites_path, self.server_name), data_path = os.path.join(config.sites_path,self.server_name,config.get('data','path','data')), url = self.uri, tracking_id = config.get('site', 'tracking_id', ''), ) # authentication self.authentication = config.get('site','authentication','basic') if self.authentication == 'windows': self.nt_username = env.get('REMOTE_USER', None) # csrf validation self.csrf_validation = config.get('site', 'csrf_validation', True) not in ['0','False','off','no',True] # secure cookies self.secure_cookies = config.get('sessions', 'secure_cookies', False) not in ['0','False','off','no',False] # users and groups self.guest = config.get('users', 'default', 'guest') self.administrator_group = system.config.get('users', 'administrator_group', 'administrators') self.manager_group = config.get('users', 'manager_group', 'managers') self.managers = config.get('users', 'managers', 'managers') self.developers = config.get('users', 'developer', 'developers') self.administrators = config.get('users', 'administrators', 'administrators') # apps self.index = config.get('apps', 'index', 'index') self.home = config.get('apps', 'home', 'home') # connect to the database and stores db_engine = config.get('database','engine','mysql') db_host = config.get('database','dbhost','database') db_name = config.get('database','dbname','zoomdev') db_user = config.get('database','dbuser','testuser') db_pass = config.get('database','dbpass','password') # legacy database module self.database = database.database( db_engine, db_host, db_name, db_user, db_pass, ) # new (experimental) database module db_params = dict( engine = db_engine, host = db_host, db = db_name, user = db_user, ) if db_pass: db_params['passwd'] = db_pass self.db = db.database(**db_params) # users (experimental) self.users = UserStore(self.db) # email settings self.from_addr = system.config.get('mail','from_addr') # load theme self.themes_path = existing(config.get('theme', 'path', os.path.join(self.root,'themes'))) self.theme = self.themes_path and config.get('theme','name','default') self.theme_path = existing(self.themes_path, self.theme) self.default_theme_path = existing(self.themes_path, 'default') self.default_template = config.get('theme', 'template', 'default') # templates self.template_path = existing(self.theme_path, 'templates') self.default_template_path = existing(self.default_theme_path, 'templates') self.templates_paths = filter(bool, [ self.template_path, self.default_template_path, self.theme_path, self.default_theme_path, ]) self.templates = {} self.app = NoApp() self.site_name = '' self.warnings = [] self.errors = [] self.messages = [] self.js = set() self.css = set() self.head = set() self.tail = set() self.show_errors = config.get('error','users','0') == '1' self.profile = config.get('system','profile','0') == '1' self.webhook = config.get('webhook','url','') self.logging = config.get('log', 'logging', True) not in ['0','False','off','no',False]
def getConnect(db_cfg): connect = db.database(port=5432, host=db_cfg['ip'], dbn='postgres', db=db_cfg['db'], user=db_cfg['user'], pw=db_cfg['password']) return connect
sys.path.append("/usr/lib/datenfresser/modules") from webcore import datenfresser_web import cgi import cgitb from db import database cgitb.enable() a = datenfresser_web() a.print_header() form = cgi.FieldStorage() print "<br /><br />" if form.has_key("id"): id = form["id"].value data = database() containerList = data.getDataContainer( id ) print "<table>" for container in containerList: print "<h3>Showing container '" + container.name + "':</h3>" for var in container.__dict__.keys(): print "<tr><td>" + var + "</td><td>" + str(container.__dict__[var]) + "</td>"; print "</table>" else: print "Error: no valid id" sys.exit(0)
user = get_session(db) vote_comment(db, comment_id, user, 0, 1) total_votes = get_comment_votes(db, comment_id) return str(total_votes) @error(404) def error404(error): user = get_session(db) return template('404', user=user) @route('/static/<filename>') def server_static(filename): """ For CSS """ return static_file(filename, root='static/') @route('/static/img/<filename>') def server_image(filename): return static_file(filename, root='static/img/') if __name__ == '__main__': db = database() create_tables(db) # Testing purposes insert_sample_data(db) run(debug=True, host='localhost', port=8080)
def auth(key): import db stat = db.database("status") print stat.rows
import db ''' This script creates dummy data in the server ''' devices = db.database("devices") rooms = db.database("rooms") # Create some rooms rooms.addColumn("roomID") # unique ID of the room rooms.addColumn("name") # name of the room rooms.addColumn("floor") # floor in which the room is present rooms.addColumn("type") # type of room ex: bedroom, bathroom etc rooms.insert({ 'roomID' : '1', 'name' : 'Entry room', 'floor' : 'G', 'type' : 'entry' }) rooms.insert({ 'roomID' : '2', 'name' : 'Hall', 'floor' : 'G', 'type' : 'living' }) rooms.insert({ 'roomID' : '3',
except: pass sys.stdout.write('pid %s killed.. ' % (p, )) except: pass fp = file(config.PIDFILE, 'w') fp.write(pid) fp.close() from freq import freqbot import lang import options from options import optstringlist bot = freqbot(globals()) wtf_db = db.database('wtf') q = wtf_db.query('select count(*) from SQLITE_MASTER where type="table" and tbl_name="wtf"') if q.fetchone()[0] == 0: wtf_db.query('create table wtf (room text, key text, val text)') wtf_db.commit() try: bot.plug.load_all() reactor.run() except: bot.log.err(escape('FATAL ERROR: %s' % (traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback), ))) def log(m, e=False): bot.log.log(m) if e: bot.log.err(m)
def main( cliArguments ): # Set the signal handler and a 5-second alarm signal.signal(signal.SIGUSR1, handler) log("Starting datenfresser server") if cliArguments.daemon == True: createDaemon() c = config() webserver = c.getWebserverEnabled() webserver_port = c.getWebserverPort() monitor = c.getMonitorServerEnabled() if cliArguments.monitor: monitor = "True" auto_shutdown = c.getAutomaticShutdown() start_delay = c.getStartDelay() debug = c.getDebug() #udev = UdevListener() #udev.run() # if automatic shutdown is enabled, we ask the user to hit the "enter" key to # disable automatic shutdown at startup if int(auto_shutdown) > 0: print "Press 'enter' to disable automatic shutdown" rfds, wfds, efds = select.select( [sys.stdin], [], [], 5) if rfds != []: auto_shutdown = 0 if webserver == "True": log("Starting builtin webserver on port " + str(webserver_port)) #start our own webserver to serve the webinterface web = datenfresser_webserver( webserver_port ) web.startServer() d = database() d.cleanupZombieJobs() #current time cur_time = time() if int(start_delay) > 0: sleep( float ( start_delay ) ) syncMonitorData() print os.getpid() if monitor == "True" or monitor == "true": #start our own monitor log("Trying to start monitor service..") monitorServer = datenfresserMonitorServer () monitorServer.startServer() else: log("Not starting monitor") pidFileName = "/var/lib/datenfresser/datenfresser.pid" if os.path.isfile( pidFileName ): pidFile = open( pidFileName ) tmp = pidFile.readline() if len(tmp) == 0: pid = int( pidFile.readline() ) try: os.getpgid( pid ) log("Another instance of datenfresser is already running. Quitting now..") sys.exit( 0 ) except OSError, e: pass pidFile = open( pidFileName , "w" ) pidFile.write( str( os.getpid() ) ) pidFile.close() #the user forced an backup of all containers if cliArguments.forceAll: for id in d.getAllIDs(): performBackup( id ) while 1: #print getNextUdevNotification() #checkSyncDirs() for id in d.tickAction(): performBackup( id ) #print "before sleep" #wait till we look for new ready-to-run jobs #sleep( float( c.getPollInterval() ) ) sleep( 5 ) #print "after sleep" if int(auto_shutdown) > 0 and (int(cur_time) + int (auto_shutdown)) - time() < 0: print "shutdown" shutdown()
def sync(self): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) c = config() s.connect(( c.getRemoteMonitorServer() , int(c.getRemoteMonitorPort()))) d = database() self.xml = xmlHandler() #return try: #authenticate the client s.send("auth " + c.getRemoteMonitorUser() + " " + c.getRemoteMonitorPassword() ) print s.recv(1024) #announce our hostname s.send("host " + c.getHostname() ) print s.recv(1024) #check if all dataContainer are enlisted at the server containerList = d.getDataContainer("") for container in containerList: #ask server if container is already known to the server container.updateChecksum() request = "checkDataID " + str(container.dataID) + " " + container.checksum s.send(request) reply = str( s.recv(1024) ) print reply if reply == "dataID unknown": data = self.xml.dataContainerToXml( c.getHostname(), container ) print "trying to send data: " + data print "Send data, #bytes: " + str( s.sendall("data " + str(len(data)) + " " + data )) print "Answer to data:" + s.recv(1024) s.send("commit") print "Answer to commit: " + s.recv(1024) s.send("getLastID " + c.getHostname()) lastId = int( s.recv(1024) ) print "received lastId" + str(lastId) logs = d.getLogs( lastId) for i in range(0, len(logs)): data = self.xml.logEntryToXml( c.getHostname(), logs[i] ) origSize = len(data) dataPad = len(data) % 1024 dataPad = 1024 - dataPad data = data.ljust( origSize + dataPad, " ") print "Size of data: " + str(len(data)) print "Send data, #bytes: " + str( s.sendall("data " + str(len(data)) + " " + data )) print "Answer to data:" + s.recv(1024) s.send("commit") print "Answer to commit: " + s.recv(1024) s.send("exit") print s.recv(1024) finally: s.close()
def db_query(self, sql, args=()): db = database(**self.dbinfo) ret = db.query(sql, args) return ret, db._code, db._msg