Example #1
0
    def __init__(self) -> None:
        super().__init__()

        self._db_manager = DbManager()
        # Create database if it does not exists yet (Currently working just with SQLite3 database)
        self._conn = self._db_manager.create()

        # Creating DAO objects
        self._dao_environment = DaoEnvironment(self._conn)
        self._dao_registry = DaoRegistry(self._conn)
def search_videos():
    query = request.args.get('query', '')

    if not query:
        return Response(status=400, response='Empty search query provided')

    db_manager = DbManager()
    list_videos = db_manager.search(query)
    data = {}
    data["no_of_videos"] = len(list_videos)
    data["videos"] = list_videos
    return Response(status=200, response=json.dumps(data))
Example #3
0
 def _init_db(self):
     self._db = DbManager()
     self._dao_env = DaoEnvironment(conn=self._db.get_connection())
Example #4
0
class MainWindow(QTabWidget):

    def __init__(self):
        super(MainWindow, self).__init__()

        self.top: int = 400
        self.left: int = 400
        self.width: int = 600
        self.height: int = 500

        self._tabs = []

        # Db Stuff
        self._db: DbManager = None
        self._dao_env: DaoEnvironment = None

        # Menu Bars
        self._environment_menu: QMenuBar = None
        self._image_menu: QMenuBar = None
        self._repository_menu: QMenuBar = None
        self._help_menu: QMenuBar = None

        self._init_db()
        self._init_ui()

    def _init_ui(self):
        self.setWindowTitle(Strings.APP_NAME)
        self.setWindowIcon(QIcon('assets/docker.svg'))
        menu_button = QPushButton(QIcon('assets/menu.svg'), "")
        menu_button.clicked.connect(self.open_env_connect_dialog)
        self.setCornerWidget(menu_button, Qt.TopLeftCorner)
        self.setGeometry(self.top, self.left, self.width, self.height)
        self.setTabsClosable(True)
        self.tabCloseRequested.connect(self.close_tab)
        self.addTab(QWidget(), "Home")

    def _init_db(self):
        self._db = DbManager()
        self._dao_env = DaoEnvironment(conn=self._db.get_connection())

    def open_env_connect_dialog(self):
        env_connect_dialog = EnvConnectDialog(parent=self, dao=self._dao_env)
        env_connect_dialog.signals().accept_connect_signal.connect(self.connect_success)
        env_connect_dialog.open()

    @pyqtSlot(DEnvEnvironment, name=GeneralSignals.GENERAL_ACCEPT_CONNECT_SIGNAL)
    def connect_success(self, env: DEnvEnvironment = None):
        tab_window = DockerWindow(self, db=self._db, env=env)
        self._tabs.append(tab_window)
        index = self.addTab(tab_window, env.name)
        self.setTabEnabled(index + 1, True)

    def close_tab(self, index):
        tab = self.widget(index)
        if tab is not None:
            tab.deleteLater()
            tab.close()
        self.removeTab(index)
        self._tabs.remove(tab)

    def closeEvent(self, *args, **kwargs):
        """
        This function is called when this window is about to be closed
        :param args:
        :param kwargs:
        :return:
        """
        for tab in self._tabs:
            tab.closeEvent()

        self._tabs.clear()
 def __init__(self, option, userInfo=None):  # 初始化
     super().__init__()
     self.option = option
     self.userInfo = userInfo
     self.dbManager = DbManager()
class DataProcess(QThread):
    sinOut = pyqtSignal(tuple)  # 信号槽

    def __init__(self, option, userInfo=None):  # 初始化
        super().__init__()
        self.option = option
        self.userInfo = userInfo
        self.dbManager = DbManager()

    def run(self):
        if self.option == 1:  # 添加信息
            flag = self.insertInfo()
            if flag > 0:
                print('添加成功')
        elif self.option == 2:
            values = self.findAllUserInfo()
            print(values)
        elif self.option == 3:
            values = self.deleteUserInfo()
            print(values)
        elif self.option == 4:
            values = self.updateUserInfo()
            print(values)
        elif self.option == 5:
            self.outData()
            # print(values)

    def insertInfo(self):  # 添加账号密码

        if len(self.userInfo) >= 3:
            sql = 'INSERT INTO pwdinfo(webName,userName,pwd) VALUES(%(webName)s,%(userName)s,%(pwd)s)'
            params = self.userInfo
            flag = self.dbManager.edit(sql=sql, params=params)
            values = (flag, )
            self.sinOut.emit(values)
            return flag

    def findAllUserInfo(self):
        sql = 'SELECT * FROM pwdinfo'
        values = self.dbManager.fetchall(sql=sql)
        self.sinOut.emit(values)

    def deleteUserInfo(self):

        sql = 'DELETE FROM pwdinfo WHERE id=%(id)s'
        params = self.userInfo
        flag = self.dbManager.edit(sql=sql, params=params)
        values = (flag, )
        self.sinOut.emit(values)
        return flag

    def updateUserInfo(self):

        sql = 'UPDATE pwdinfo SET webName=%(webName)s,userName=%(userName)s,pwd=%(pwd)s WHERE id=%(id)s'
        params = self.userInfo
        flag = self.dbManager.edit(sql=sql, params=params)
        values = (flag, )
        self.sinOut.emit(values)
        return flag

    def outData(self):
        # dirPath = QFileDialog.getExistingDirectory(self, '保存位置', './')
        # dir_choose = QFileDialog.getExistingDirectory("选取文件夹", '.')  # 起始路径

        sql = 'SELECT * FROM pwdinfo'
        values = self.dbManager.fetchall(sql=sql)

        myWorkbook = xlwt.Workbook()
        mySheet = myWorkbook.add_sheet('网站账号信息')

        for i in range(1, len(values)):
            for j in range(1, len(values[i])):
                print(i, j, values[i][j])
                mySheet.write(i, j - 1, str(values[i][j]))

        mySheet.write(0, 0, '网站')
        mySheet.write(0, 1, '账号')
        mySheet.write(0, 2, '密码')
        # filePath = os.path.join(dirPath, 'password.xls')
        myWorkbook.save('password.xls')
        self.sinOut.emit((1, ))
 def __init__(self):
     auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
     auth.set_access_token(access_token, access_token_secret)
     self.api = tweepy.API(auth)
     self.db = DbManager(DB_NAME)
     random.seed(time.time())
class Bot():
    def __init__(self):
        auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
        auth.set_access_token(access_token, access_token_secret)
        self.api = tweepy.API(auth)
        self.db = DbManager(DB_NAME)
        random.seed(time.time())

    # make search based on our favorite hash tags
    def queryTags(self, hash_tags=HASH_TAGS):
        print("Querying twitter at {0}".format(getTime()))
        for tag in hash_tags:
            for tweet in tweepy.Cursor(self.api.search, q=tag).items(5):
                self.saveTweet(tweet)

    # save tweets
    def saveTweet(self, tweet):
        print("Checking {0}".format(tweet.id_str))
        tweet_checked = tweet

        # check if tweet is a RT. If it is we need to get it, because the tweet ids
        # from the RT and the tweet  are different and we only care about the original one
        if (hasattr(tweet, 'retweeted_status')):
            print("Tweet is an RT. OG: {0} ".format(
                tweet.retweeted_status.id_str))
            tweet_checked = tweet.retweeted_status

        # check if tweet is not in our DB
        if self.db.getTweet(tweet_checked.id):
            print("Tweet already stored in DB")
            return

        print("Storing {0}".format(tweet.id_str))
        self.db.saveTweet("tweets", tweet_checked)

    # create analysis of latests tweets
    def createAnalysis(self):
        pass

    def getGoodTweets(self):
        # for now we are just getting the  latest three tweets we stored
        return self.db.find(
            "tweets", {
                "$or": [{
                    "retweet_count": {
                        "$gte": MIN_RETWEETS
                    }
                }, {
                    "favorite_count": {
                        "$gte": MIN_FAVS
                    }
                }]
            }).sort("created_at", DSC).limit(10)

    # retweet based on analysis
    def retweet(self):
        print("Retweeting at {0}".format(getTime()))
        for tweet in self.getGoodTweets():
            # first we checked if we already retweeted it
            if self.db.getMyTweet(tweet["status_id"]):
                continue
            print("Retweeting {0}".format(tweet["status_id"]))
            self.db.saveTweet("my_tweets", tweet, False)
            # sleep for random time before tweeting
            time.sleep(random.randrange(0, 60))
            self.api.retweet(tweet["status_id"])
            print("Retweeted {0}".format(tweet["status_id"]))
Example #9
0
class Upgrade:
    def __init__(self) -> None:
        super().__init__()

        self._db_manager = DbManager()
        # Create database if it does not exists yet (Currently working just with SQLite3 database)
        self._conn = self._db_manager.create()

        # Creating DAO objects
        self._dao_environment = DaoEnvironment(self._conn)
        self._dao_registry = DaoRegistry(self._conn)

    def upgrade(self):
        """
        Upgrade script for now
        :return:
        """
        try:
            Log.i("Upgrade Started")
            self._dao_environment.drop()

            self._dao_environment.init()
            self.handle_sql_error(self._conn.lastError())

            # Insert Local VM environment
            env = self._dao_environment.create_env(
                DEnvEnvironment(name='Local VM'))
            if env is not None:
                self._dao_environment.create_env_setting(
                    env, ('DOCKER_HOST', 'tcp://10.0.0.17:2375'))
                self._dao_environment.create_env_setting(
                    env, ('DOCKER_TLS_VERIFY', ''))
                self._dao_environment.create_env_setting(
                    env, ('DOCKER_CERT_PATH', ''))

            # Insert Linux environment
            env = self._dao_environment.create_env(
                DEnvEnvironment(name='Linux'))
            if env is not None:
                self._dao_environment.create_env_setting(
                    env, ('DOCKER_HOST', 'unix:///var/run/docker.sock'))
                self._dao_environment.create_env_setting(
                    env, ('DOCKER_TLS_VERIFY', ''))
                self._dao_environment.create_env_setting(
                    env, ('DOCKER_CERT_PATH', ''))

            self._dao_registry.drop()
            self._dao_registry.init()

            # Insert Local Docker Registry entry
            registry_id = self._dao_registry.insert_registry(
                'Local VM', 'localhost:5000')

            # Commit all changes to database

            self.handle_sql_error(self._conn.lastError())
        except QSqlError as e:
            self.handle_sql_error(e)
        # Close database connection
        self._conn.close()

    def handle_sql_error(self, error: QSqlError = None):
        """
        Types:
        ConnectionError = 1
        NoError = 0
        StatementError = 2
        TransactionError = 3
        UnknownError = 4
        :param error:
        :return:
        """
        if error is not None:
            if error.type() == QSqlError.NoError:
                pass
            elif error.type() == QSqlError.ConnectionError:
                Log.e("SQL Error [Connection Error] - %s" % error.text())
            elif error.type() == QSqlError.StatementError:
                Log.e("SQL Error [Statement Error] - %s" % error.text())
            elif error.type() == QSqlError.TransactionError:
                Log.e("SQL Error [Transaction Error] - %s" % error.text())
            else:
                Log.e("SQL Error [Unknown Error] - %s" % error.text())
def load_data_in_bg():
    db_manager = DbManager()
    while True:
        db_manager.fetch_and_save_videos_from_youtube(SEARCH_QUERY_CRICKET)
        time.sleep(5)
def get_videos():
    db_manager = DbManager()
    page_num = request.args.get('page_num', 1, type=int)
    limit = request.args.get('limits', 5, type=int)
    data = db_manager.fetch(page_num, limit)
    return Response(status=200, response=data)
Example #12
0
watch_parser.add_argument('--resync',
                          action='store_true',
                          help='If true the whole PATH is resynced')

if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO,
                        format='%(asctime)s - %(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S')

    args = parser.parse_args()
    if args.sub == 'watch':
        path = args.path
        # todo resync option
        if args.resync:
            print('SHould resync')
        db_manager = DbManager('/home/dexmo/.dexuments/index.db', path)
        face_manager = FaceManager('/home/dexmo/.dexuments', db_manager)
        event_handler = UpdateEventHandler(db_manager, path,
                                           FileProcessor(face_manager))
        observer = Observer()
        observer.schedule(event_handler, path, recursive=True)
        observer.start()
        try:
            while True:
                time.sleep(1)
        except KeyboardInterrupt:
            observer.stop()
            db_manager.close()
        observer.join()
    elif args.sub == 'query':
        pass
Example #13
0
from db import DbManager

db = DbManager()
cursor = db.connection()
db.insertUser(cursor, ("*****@*****.**", "12344544", "Activo"))
db.insertParking(cursor, ("MXR471", "2020-11-03 15:00:00"))
#del db
Example #14
0
def set_up_modules(app, manager):
    DbManager.set_up_db(app, manager)

    for _, name in SourceScanner('.', r'set_up_(\w+)').apply_scanned_function(
            app, manager):
        logger.info('Set up module: {}'.format(name))