Пример #1
0
def main(request):
    database = DB()
    list = database.getOrderList()
    car = database.getCarList()
    for elem in list:
        print elem
    return render(request, 'main_page.html', {'list': list, 'car': car})
Пример #2
0
 def __init__(self):
     self.list = list()
     self.comments = []  # 评论结果
     self.comments_userurl = []  # 从评论里面爬取到的用户url
     self.likes = []  # 赞爬取结果
     self.queue = Queue()  # 爬取队列对象
     self.db = DB()
Пример #3
0
    def initialize_dump(self):
        # self.stop_thread()
        for dbname in os.listdir(self.DUMP_DIR):
            if dbname.endswith('.sql'):

                dbname = dbname.replace(".sql", "")
                self.server_sql.create_db(dbname)

                db_config = self.config
                db_config['database'] = dbname
                db = DB(db_config)

                db.upload_sql(self.DUMP_DIR + self.DIR_SEP + dbname + ".sql")

                shutil.move(self.DUMP_DIR + self.DIR_SEP + dbname + ".sql",
                            self.STRUCTURE_DIR + self.DIR_SEP)

                del (db)

            q = "select * from db where db_name='%s'" % dbname
            result = self.nebula_sql.select(q)
            if (len(result) == 0):
                q = "insert into db (db_name) values('%s')" % dbname
                id = self.nebula_sql.insert(q)
            else:
                id = result[0]['db_id']
            q = "INSERT INTO `log`( `cloud_id`, `db_id`) SELECT cloud_id,'%s' from cloud WHERE type = 'main'" % id
            self.nebula_sql.insert(q)
Пример #4
0
def setTime(request):
    database = DB()
    if 'eventTime' in request.GET:
        database.setEventTime(request.GET['eventTime'])
        return redirect(
            reverse('index') + '?message=Time changed to ' +
            str(request.GET['eventTime']))
    return redirect(reverse('index'))
Пример #5
0
def initialize_database(request):
    database = DB()
    database.initialization()

    # User.objects.initialize()
    # Product.objects.initialize()
    # Department.objects.initialize()

    return redirect('/')
Пример #6
0
 def register_sub_server(self, host, username, password):
     config = {"host": host, "user": username, "password": password}
     db = DB(config)
     if db.connection_status():
         q = "insert into cloud (host,username,password,type)values('%s','%s','%s','%s')" % (
             host, username, password, "sub")
         self.nebula_sql.insert(q)
         return True
     else:
         return False
Пример #7
0
def main():

    db = DB("test.db")

    #db.genRandomUsers(200)

    result = db.dbExecute("select count(*) from users")
    print("Total entries:", result[0][0], end="")

    db.dbCloseConnection()
    def capture_register(self):
        self.show_facial_register_GUI_signal.emit()
        name_text = self.name_line.text()
        password_text = self.password_line.text()
        self.register_account_pwd_signal.emit(name_text, password_text)
        DATABASE = DB()
        signup = Signup()
        face, facecode = signup.get_face()
        DATABASE.registration(name_text, 'student', facecode, password_text)

        em = QErrorMessage(self)
        em.setWindowTitle("success")
        em.showMessage("Success!")
Пример #9
0
 def refresh_show(self):
     message_type = self.comboBox.currentText()
     self.pushButton.setText(message_type)
     database = DB()
     print(signup.login_user)
     if message_type == 'Personal':
         display = database.message_looking(signup.login_user)
         self.textEdit.setPlainText(display)
     if message_type == 'Group':
         display = database.group_message_looking(signup.login_user)
         self.textEdit.setPlainText(display)
     if message_type == 'ALL':
         display = database.message_looking('all')
         self.textEdit.setPlainText(display)
Пример #10
0
def main(request):
    database = DB()
    msgs = []
    if 'fromLength' in request.GET and 'toLength' in request.GET \
            and request.GET['fromLength'] != '' and request.GET['toLength'] != '':
        list = database.getOrderListByLength(int(request.GET['fromLength']),
                                             int(request.GET['toLength']))
        msgs.append('by travel length')
    elif 'car_id' in request.GET and request.GET['car_id'] != '0':
        list = database.getOrderListByDriverID(int(request.GET['car_id']))
        msgs.append('by driver name')
    elif 'excludeWord' in request.GET and request.GET['excludeWord'] != '':
        list = database.getListExcluded(request.GET['excludeWord'])
        msgs.append('without : ' + request.GET['excludeWord'])
    elif 'includeWord' in request.GET and request.GET['includeWord'] != '':
        list = database.getListIncluded(request.GET['includeWord'])
        msgs.append('with : ' + request.GET['includeWord'])
    else:
        list = database.getOrderList()
    car = database.getCarList()
    return render(request, 'main_page.html', {
        'msgs': msgs,
        'list': list,
        'car': car
    })
Пример #11
0
    def insert_to_database(self):

        cursor = DB.cursor()
        query = "INSERT INTO products (id, name, subname, price, score)\
            VALUES(%s, %s, %s, %s, %s)"

        values = (self.id, self.name, self.subname, self.price, self.score)
        try:
            cursor.execute(query, values)
        except mysql.connector.errors.DataError:
            pass
        except mysql.connector.errors.IntegrityError:
            pass
        self.opinions.insert_to_database()
        DB.commit()
Пример #12
0
 def setUp(self):
     GameUtil.flush_cache()
     self.cur = DB.cursor()
     self.cur.execute("DELETE FROM account")
     self.cur.execute("DELETE FROM account_actor")
     self.cur.execute("DELETE FROM actor")
     self.cur.execute("DELETE FROM actor_message")
     self.cur.execute("DELETE FROM actor_properties")
     self.cur.execute("DELETE FROM item")
     self.cur.execute("DELETE FROM item_owner")
     self.cur.execute("DELETE FROM item_properties")
     self.cur.execute("DELETE FROM location")
     self.cur.execute("DELETE FROM location_properties")
     self.cur.execute("DELETE FROM log_raw_action")
     DB.commit()
    def check_login(account, pwd):
        DATABASE = DB()
        password = DATABASE.password_looking(account)[0]
        print(account)
        print(password)
        if pwd == password:
            #print("login")
            signup.login_user = account
            print(signup.login_user)
            personal_pane.show()
            login_pane.hide()


        else:
            login_pane.show_error_animation()
Пример #14
0
    def __init__(self, from_conf, to_conf, db_sql_path):
        self.from_db = DB(from_conf)
        self.to_db = DB(to_conf)
        self.sql_array = []

        sql_file = open(db_sql_path, 'r')

        q = ""
        for line in sql_file:
            line = line.strip()
            if line != "" and not line.startswith("--"):
                q += " " + line
                if q.endswith(";"):
                    self.sql_array.append(q)
                    q = ""
Пример #15
0
def product(id):
    cursor = DB.cursor(dictionary=True)

    cursor.execute(
        "SELECT p.*, COUNT(o.id) AS opinions FROM products p LEFT JOIN opinions o ON p.id = o.product_id WHERE p.id=%s",
        (id, ))
    product = cursor.fetchall()

    cursor.execute("SELECT * FROM opinions WHERE product_id=%s", (id, ))
    opinions = cursor.fetchall()

    for opinion in opinions:
        cursor.execute("SELECT text from pros WHERE opinion_id = %s",
                       (opinion['id'], ))
        pros = cursor.fetchall()
        opinion['pros'] = pros

    for opinion in opinions:
        cursor.execute("SELECT text from cons WHERE opinion_id = %s",
                       (opinion['id'], ))
        cons = cursor.fetchall()
        opinion['cons'] = cons

    return render_template("product.html",
                           subname=f"Produkt - {id} - {product[0]['name']}",
                           id=id,
                           mod="product",
                           opinions=opinions,
                           product=product[0])
Пример #16
0
    def on_load(self):
        self._item_ids = set()
        self._item_types = {}
        self._changes = set()

        # Now load the contents of the container
        my_id = self.identity()
        cur = DB.cursor()
        cur.execute(
            'SELECT item.id, item.type' + ' FROM item, item_owner' +
            ' WHERE item.id = item_owner.item_id' +
            '   AND item_owner.owner_type = %(owner_type)s' +
            '   AND item_owner.owner_id = %(owner_id)s' +
            '   AND item_owner.container = %(container)s', {
                'owner_type': my_id[0],
                'owner_id': my_id[1],
                'container': my_id[2]
            })

        row = cur.fetchone()
        while row is not None:
            # Update the list by ID
            self._item_ids.add(row[0])
            # Update the list by name
            iset = self._item_types.setdefault(row[1], set())
            iset.add(row[0])
            row = cur.fetchone()
Пример #17
0
    def load_by_pos(cls, pos, allprops=False):
        """Load a complete location stack by position"""
        rpos = repr(pos)
        if rpos in Location.cache_by_pos:
            stack = Location.cache_by_pos[rpos]
            overlays = stack.keys()
            overlays.sort()
            return stack[overlays[-1]]

        cur = DB.cursor()
        cur.execute(
            'SELECT id, state FROM location ' +
            'WHERE x=%(x)s AND y=%(y)s AND layer=%(layer)s ' +
            'ORDER BY overlay', pos.as_dict())
        row = cur.fetchone()
        location = None
        while row is not None:
            # Load the overlay
            tmploc = cls._load_from_row(row, allprops)
            # Set up a doubly-linked list
            tmploc._underneath = location
            if location is not None:
                location._above = tmploc
            # Push the underlying location down
            location = tmploc
            row = cur.fetchone()

        if location is not None:
            location._above = None

        return location
Пример #18
0
def touch_account(accid):
    cur = DB.cursor()
    cur.execute(
        "UPDATE account SET last_seen = %{now}s" +
        " WHERE account_id = %{id}s", {
            'now': time.time(),
            'id': accid
        })
Пример #19
0
    def transporter(self, phone, phone_other, name, price, product_name, image_path, password, id, cate, description):
        thread = threading.Thread(target=DB.upload_product_image, args=(
            DB(), cate, image_path, phone, phone_other, name, price, product_name, password, id, description))
        thread.start()

        thread.join()

        self.actively_reg()
Пример #20
0
def create_account(name, email, nickname=None):
    cur = DB.cursor()
    cur.execute(
        "INSERT INTO account (username, email, nickname)" +
        " VALUES (%{username}s, %{email}s, %{nick}s", {
            'username': name,
            'email': email,
            'nick': nickname
        })
Пример #21
0
def get_id_from_name(name):
    cur = DB.cursor()
    cur.execute(
        "SELECT account_id FROM account" + " WHERE username = %{username}s",
        {'username': display_identifier})
    row = cur.fetchone()
    if row is None:
        return None
    return row[0]
Пример #22
0
def set_session_key(accid, key):
    cur = DB.cursor()
    cur.execute(
        "UPDATE account " + " SET key = %{key}s, " +
        "     last_seen = %{now}s" + " WHERE account_id = %{id}s", {
            'key': key,
            'id': accid,
            'now': time.time()
        })
Пример #23
0
 def random_host(self, cloud_id):
     q = "SELECT * FROM cloud where cloud_id <> '%s' ORDER BY RAND()  LIMIT 1;" % cloud_id
     result = self.nebula_sql.select(q)
     db = DB(self.get_config(result[0]))
     if (db.connection_status):
         return result[0]
     else:
         print "Connection to %s failed" % result[0]['host']
         return False
Пример #24
0
def recommendation_ratio(id):
    cursor = DB.cursor()

    cursor.execute("SELECT recommendation FROM opinions WHERE product_id=%s",
                   (id, ))
    rec = cursor.fetchall()
    cursor.close()

    return jsonify(rec)
Пример #25
0
	def message(self, message, msg_type='message'):
		"""Write a message to the actor's message log"""
		cur = DB.cursor()
		cur.execute("INSERT INTO actor_message"
					+ " (stamp, actor_id, msg_type, message)"
					+ " VALUES (%(stamp)s, %(id)s, %(msg_type)s, %(message)s)",
					{ 'stamp': time.time(),
					  'id': self._id,
					  'msg_type': msg_type,
					  'message': message })
Пример #26
0
def initialize_database(request):
    Address.objects.initialize()
    Car.objects.initialize()
    Client.objects.initialize()
    database = DB()
    TaxiOrder.model.objects.all().delete()
    from django.db import connection
    cur = connection.cursor()
    cur.execute("ALTER TABLE taxi_order AUTO_INCREMENT = 1")
    with open('order.csv', 'rb') as csvfile:
        passengers = csv.reader(csvfile, quotechar=',')
        for pas in passengers:
            car = Car.objects.get(id=int(pas[2]))
            client = Client.objects.get(id=int(pas[3]))
            start = Address.objects.get(id=int(pas[0]))
            finish = Address.objects.get(id=int(pas[1]))
            database.saveOrder(start, finish, car, client, pas[4])

    return redirect('/')
Пример #27
0
def opinions_per_stars(id):
    cursor = DB.cursor(dictionary=True)

    cursor.execute(
        "SELECT stars, count(id) AS opinions FROM opinions WHERE product_id=%s GROUP BY stars ORDER BY stars ASC",
        (id, ))
    stars = cursor.fetchall()
    cursor.close()

    return jsonify(stars)
Пример #28
0
    def __init__(self):

        self.DUMP_DIR = "dump"
        self.STRUCTURE_DIR = "structure"
        self.DIR_SEP = "/"
        self.NEBULA = False

        hostname = socket.gethostname()
        ip_addr = socket.gethostbyname(hostname)

        self.config = {"host": ip_addr, "user": "******", "password": "******"}
        self.server_sql = DB(self.config)

        nebula_config = self.config
        nebula_config['database'] = "nebula"

        self.nebula_sql = DB(nebula_config)

        self.update_main_ip(ip_addr)
Пример #29
0
def editSale(request, id):
    database = DB()
    if request.method == 'GET':
        customers = database.getUsers()
        departments = database.getDepartments()
        products = database.getProducts()
        sale = database.getSale(id)
        print sale
        return render(request,'editSale.html', {'customers':customers, 'departments':departments, 'products':products, 'sale': sale })
    else:
        database.updateSale(id, request.POST['userId'],request.POST['productId'],request.POST['departmentId'],
                  request.POST['saleType'],request.POST['saleDescription'])
        return redirect(reverse('index') + '?message=Changed Sale')
Пример #30
0
 def __init__(self):
     # Create a new record in the database for this object and get
     # its ID
     cur = DB.cursor()
     cur.execute('SELECT nextval(\'' + self._table + '_id_seq\');')
     row = cur.fetchone()
     self._id = row[0]
     cur.execute(
         'INSERT INTO ' + self._table +
         ' (id, state) VALUES (%(id)s, NULL)', {'id': self._id})
     self._setup()
     Triggerable.__init__(self)
Пример #31
0
from django.test import TestCase

# Create your tests here.
from Database import DB

database = DB()
database.initial()
res = database.analyzeOrders()
print res