コード例 #1
0
    def create_table_withdrawn_stuffs(self):
        try:
            DB().mydb.create_collection("withdrawn_stuffs")
            vexpr = {"$jsonSchema":
                {
                    "bsonType": "object",
                    "required": ["name"],
                    "properties": {
                        "name": {
                            "bsonType": "string",
                            "description": "must be a string and is required"
                        },
                        "stuff": {
                            "enum": ['drugs', 'guns', 'forbidden literature',
                                     None],
                            "description": "can only be one of the enum values and is required"
                        },
                    }
                }
            }

            query = [('collMod', 'withdrawn_stuffs'),
                     ('validator', vexpr),
                     ('validationLevel', 'moderate')]
            query = OrderedDict(query)
            DB().mydb.command(query)
        except BulkWriteError as bwe:
            print(bwe.details)
コード例 #2
0
 def test_delete_is_working(self):
     with DB() as database:
         test = Test().create()
         test.id = database.execute('''SELECT id FROM tests WHERE title = ?''', \
          (test.title,)).fetchone()[0]
     with DB() as database:
         test.delete()
     self.assertEqual(Test.find(test.id), None)
コード例 #3
0
 def test_delete_is_working(self):
     with DB() as database:
         question = Question().create()
         question.id = database.execute('''SELECT id FROM questions WHERE question = ?''', \
          (question.question,)).fetchone()[0]
     with DB() as database:
         question.delete()
     self.assertEqual(Question.find(question.id), None)
コード例 #4
0
def cnaesecundario_to_mongoDB():
    """Essa função insere o arquivo cnae_secundarios.csv no banco de dados mongoDB."""
    db = DB().connexion()
    if 'cnaesecundario' in db.list_collection_names():
        db.cnaesecundario.rename('cnaesecundario2')
    print('Insert CNAEs secundários ')
    cnae_dir = str(path.data_path) + '/cnaes_secundarios.csv'
    DB().insert_many(cnae_dir, 'cnae_secundario')

    db.cnaesecundario2.drop()
コード例 #5
0
 def test_update_is_working(self):
     with DB() as database:
         question = Question().create()
         question.id = database.execute('''SELECT id FROM questions WHERE question = ?''', \
          (question.question,)).fetchone()[0]
     with DB() as database:
         question.update(["NewQuestion", question.correct_answer],
                         question.answers).edit()
     self.assertEqual(Question.find(question.id),
                      question)  # find Question with id question id
コード例 #6
0
 def test_update_is_working(
     self
 ):  # might not work with different test titles (which is why DISTINCT exists!)
     with DB() as database:
         test = Test().create()
         test.id = database.execute('''SELECT id FROM tests WHERE title = ?''', \
          (test.title,)).fetchone()[0]
     with DB() as database:
         test.update("NewTest", test.questions).edit()
     self.assertEqual(Test.find(test.id), test)
コード例 #7
0
ファイル: __init__.py プロジェクト: joemill78/CRASD_WEB
def get_csv_charts():
    pg = DB()
    pg.connect()
    data_memory = pg.get_mem_utilized()
    load_avg = pg.get_load_avg()
    pg.close()
    title = 'Memory Utilization\n'
    headers = 'Value,Time\n'
    data = ""
    for line in data_memory:
        data += '{0},{1}\n'.format(line[0], line[1])

    title2 = '\n\nLoad Average\n'
    headers2 = 'Value,Time\n'
    data2 = ""
    for line in load_avg:
        data2 += '{0},{1}\n'.format(line[0], line[1])

    csv = (title + headers + data + title2 + headers2 + data2)
    return Response(csv,
                    mimetype="text/csv",
                    headers={
                        "Content-disposition":
                        "attachment; filename=charts_report.csv"
                    })
コード例 #8
0
ファイル: __init__.py プロジェクト: joemill78/CRASD_WEB
def delete_mon_device(device_id):
    if not session.get('logged_in'):
        return render_template('login.html')
    pg = DB()
    pg.connect()
    output = pg.get_device_info()
    datums = pg.get_device_datums()
    monitored_device = pg.get_monitored_device(device_id)
    # print monitored_device

    if request.method == "POST":

        if request.form['submit_button'] == 'Cancel':
            return redirect(url_for('dashboard'))
        elif request.form['submit_button'] == 'Delete':
            pg.delete_mon_device(device_id)
            flash("Monitored Device: " + device_id + " Deleted")
            return redirect(url_for('dashboard'))
    else:
        return render_template('delete_mon_device.html',
                               output=output,
                               datums=datums,
                               split_line=split_line,
                               to_mbps=to_mbps,
                               mem_to_g=mem_to_g,
                               monitored_device=monitored_device)
コード例 #9
0
 def loadUserMailAndPass(mail, password):
     with DB() as db:
         values = (mail, password,)
         row = db.execute('SELECT * FROM Users WHERE mail = ? AND password = ?', values).fetchone()
     if not row:
         return None
     return Users(*row)
コード例 #10
0
 def loadUserId(Id):
     with DB() as db:
         values = (Id,)
         row = db.execute('SELECT * FROM Users WHERE id = ?', values).fetchone()
     if not row:
         return None
     return Users(*row)
コード例 #11
0
 def __init__(self, subj, crse):
     # connect to database
     self.db = DB()
     self.db.useDatabase()
     self.subj = subj
     self.crse = crse
     self.classList = self.createClassList(subj, crse)
コード例 #12
0
 def create(self):
     with DB() as db:
         values = (self.username, self.password)
         db.execute('''
             INSERT INTO users (username, password)
             VALUES (?, ?)''', values)
         return self
コード例 #13
0
 def find_by_seller_id(seller_id):
     with DB() as db:
         rows = db.execute(
             'SELECT * FROM advertisements WHERE seller_id = ?',
             (seller_id,)
         ).fetchall()
         return [Advertisement(*row) for row in rows]
コード例 #14
0
 def find(id):
     with DB() as db:
         row = db.execute(
             'SELECT * FROM advertisements WHERE id = ?',
             (id,)
         ).fetchone()
         return Advertisement(*row)
コード例 #15
0
    def initCourseList(self):
        self.courseList.setHeaderLabel("Course Available")
        # show the horizontal scrollbar when needed
        self.courseList.header().setSectionResizeMode(
            QHeaderView.ResizeToContents)
        self.courseList.header().setStretchLastSection(False)

        # connect to database
        db = DB()
        db.useDatabase()
        # fetch and display data
        subjects = db.getSubject()  # list of subject
        for x in subjects:  # x: subject name
            subjItem = QTreeWidgetItem(self.courseList)
            subjItem.setText(0, x)
            levels = db.getLevel(x)
            for y in levels:  # y: level in subject x
                lvItem = QTreeWidgetItem(subjItem)
                lvItem.setFlags(lvItem.flags() | Qt.ItemIsTristate
                                | Qt.ItemIsUserCheckable)
                lvItem.setText(0, "{} Level".format(y))
                lvItem.setCheckState(0, Qt.Unchecked)
                courses = db.getCourse(x, y)
                for z in courses:  # z: course name in "subject x - level y"
                    crseItem = QTreeWidgetItem(lvItem)
                    title = db.getTitle(x, z)
                    crseItem.setFlags(crseItem.flags()
                                      | Qt.ItemIsUserCheckable)
                    crseItem.setText(0, "{} - {}".format(z, title[0]))
                    crseItem.setCheckState(0, Qt.Unchecked)

        self.courseList.sortItems(0, Qt.AscendingOrder)
        db.close()
コード例 #16
0
 def sold_ads(id):
     with DB() as db:
         values = (id, )
         rows = db.execute(
             'SELECT * FROM advertisements WHERE seller_id = ? AND active = 0',
             values).fetchall()
         return [Advertisement(*row) for row in rows]
コード例 #17
0
def loves_movie(userId, movieId):
    cur = DB()

    # check that inputs are digits
    if not userId.isdigit():
        return error(str(userId) + ' is not a valid userId')
    # check that the movieId is a digit
    if not movieId.isdigit():
        return error(str(movieId) + ' is not a valid movieId')

    cur.execute(
        """SELECT * FROM Views v WHERE v.UserID = %s AND v.MovieID = %s""",
        [userId, movieId])

    results = cur.fetchall()

    if len(results) > 0:
        return error('User already liked this movie')
    else:
        cur.execute("""INSERT INTO View (UserID, MovieID) VALUES(%s, %s)""",
                    [userId, movieId])

    return Response(json.dumps({'msg': 'Success'}),
                    status=200,
                    mimetype='application/json')
コード例 #18
0
 def buyer_name_by_id(buyer_id):
     with DB() as db:
         name = db.execute(
             'SELECT name FROM users WHERE id = ?',
             (buyer_id,)
         ).fetchone()
         return name[0]
コード例 #19
0
ファイル: user_api.py プロジェクト: Natali2205/pymongo
 def __init__(self):
     self.fields_from_collection_users = list(DB().mydb['users'].find(
         {}, {
             '_id': False,
             'id': False
         }).limit(1)[0])
     self.fields = self.fields_from_collection_users if self.fields_from_collection_users else users_fields
コード例 #20
0
 def buyer_info_by_id(buyer_id):
     with DB() as db:
         row = db.execute(
             'SELECT * FROM users WHERE id = ?',
             (buyer_id,)
         ).fetchone()
         return User(*row)       
コード例 #21
0
 def userAllMovies(self):
     with DB() as db:
         values = (self.id,)
         rows = db.execute('SELECT Movies.id, Movies.title, Movies.description, Movies.directorId, Movies.ageLimit, Movies.date FROM Movies INNER JOIN Third ON Movies.id = Third.movieId WHERE Third.userId = ?'
                           , values).fetchall()
         print(rows)
     return [Movies(*row) for row in rows]
コード例 #22
0
 def create(self):
     with DB() as db:
         values = (self.title, self.description, self.price, self.date, self.active, self.buyer_id, self.seller_id)
         db.execute('''
             INSERT INTO advertisements (title, description, price, date, active, buyer_id, seller_id)
             VALUES (?, ?, ?, ?, ?, ?, ?)''', values)
         return self
コード例 #23
0
 def loadUserMail(mail):
     with DB() as db:
         values = (mail,)
         row = db.execute('SELECT * FROM Users WHERE mail = ?', values).fetchone()
         if not row:
             return None
     return Users(*row)
コード例 #24
0
 def buy(self, buyer_id):
     with DB() as db:
         values = (buyer_id, self.id)
         db.execute('''UPDATE advertisements SET active = 0, buyer_id = ? WHERE id = ?''', values)
         self.active = 0
         self.buyer_id = buyer_id
         return self
コード例 #25
0
 def __init__(self, name="RDResource", coap_server=None):
     super(RDResource, self).__init__(name,
                                      coap_server,
                                      visible=True,
                                      observable=True,
                                      allow_children=True)
     self.db = DB.DB()
コード例 #26
0
ファイル: post.py プロジェクト: Boris14/project
 def find(id):
     with DB() as db:
         row = db.execute('SELECT * FROM categories WHERE id = ?', (id,)) \
             .fetchone()
         if not row:
             return Ad(0, "No ad","",0,"",False,"")
         return Ad(*row)
コード例 #27
0
ファイル: __init__.py プロジェクト: joemill78/CRASD_WEB
def get_csv_device():
    pg = DB()
    pg.connect()
    output = pg.get_device_info()
    datums = pg.get_device_datums()
    pg.close()
    title = 'Device Information\n'
    headers = 'Server ID,Status,IP Address,Address,City,State,Zip,Country,Download Rate,Upload Rate\n'
    data = '{0},{1},{2},{3},{4},{5},{6},{7},{8},{9}\n'.format(
        output['device_id'], output['status'], output['ip'], output['address'],
        output['city'], output['state'], output['zip'], output['country'],
        output['download_rate'], output['upload_rate'])

    title2 = '\n\nSystem Information\n'
    headers2 = 'OS,Kernel,CPU Vendor,CPU Model,RAM (Gigs)\n'
    data2 = '{0},{1},{2},{3},{4}\n'.format(datums['os'], datums['kernel'],
                                           datums['cpu_vendor'],
                                           datums['cpu_model'],
                                           mem_to_g(datums['mem']))

    csv = title + headers + data + title2 + headers2 + data2
    return Response(csv,
                    mimetype="text/csv",
                    headers={
                        "Content-disposition":
                        "attachment; filename=device_report.csv"
                    })
コード例 #28
0
ファイル: post.py プロジェクト: Boris14/project
 def find_by_category(category):
     with DB() as db:
         rows = db.execute(
             'SELECT * FROM ads WHERE category_id = ?',
             (category.id,)
         ).fetchall()
         return [Ad(*row) for row in rows]
コード例 #29
0
ファイル: __init__.py プロジェクト: joemill78/CRASD_WEB
def dashboard():
    if not session.get('logged_in'):
        return render_template('login.html')


# Get data from Postgres
    pg = DB()
    pg.connect()
    output = pg.get_device_info()
    datums = pg.get_device_datums()
    monitored_devices = pg.get_monitored_devices()
    active_mon_events = pg.get_active_mon_events()
    active_reachability_events = pg.get_active_reachability_events()
    interface_status = pg.get_interface_status()
    crasd = process_check('crasd')

    pg.close()
    return render_template(
        'home.html',
        output=output,
        datums=datums,
        mem_to_g=mem_to_g,
        split_line=split_line,
        to_mbps=to_mbps,
        monitored_devices=monitored_devices,
        active_mon_events=active_mon_events,
        active_reachability_events=active_reachability_events,
        interface_status=interface_status,
        crasd=crasd)
コード例 #30
0
ファイル: post.py プロジェクト: Boris14/project
 def create(self):
     with DB() as db:
         values = (self.title, self.description, self.price, self.date, self.is_active, self.buyer)
         db.execute('''
             INSERT INTO ads (title, description, price, date, is_active, buyer)
             VALUES (?, ?, ?, ?, ?, ?)''', values)
         return self