Ejemplo n.º 1
0
    def onStart(self):
        # open up the database connection
        db_init()

        self.registerForm('MAIN', MainForm())
        self.registerForm('USERAVAILABILITY', UserAvailabilityForm())
        self.registerForm('DATETIME', DateTimeForm())
Ejemplo n.º 2
0
 def stopFramework(self):
     # 清空数据库
     database.db_clear()
     database.db_init()
     # 添加超级用户
     privilegeM.priv_add_superuser()
     # 初始化权限管理模块
     privilegeM.priv_init()
Ejemplo n.º 3
0
Archivo: app.py Proyecto: io-tea/teapot
def main(init, fake):
    if init:
        db_init()
        click.echo('Database initialized')
        if fake:
            click.echo('Populating fake data')
            generate_fake_data(3, 100)
    app.run(host='0.0.0.0')
Ejemplo n.º 4
0
    def run():
        #加锁,只能启动一个服务
        if ServerClass._lock:
            log.logError("server is already running..")
            return
        ServerClass._lock = True
        #初始化数据库
        database.db_init()
        #添加超级用户
        privilegeM.priv_add_superuser()
        #初始化权限管理模块
        privilegeM.priv_init()

        #解析命令行, 有了这行,还可以看到日志...
        #options.parse_command_line()
        settings = {
                    'debug': False,
                    'gzip': True,
                    'autoescape': None,
                    'xsrf_cookies': False,
                    'cookie_secret':"61oETzKXQAGaYdkL5gEmGeJJFuYh7EQnp2XdTP1o/Vo=",
                    'template_path':os.path.join(os.path.dirname(__file__), "playground"),
                    'static_path':os.path.join(os.path.dirname(__file__), "playground/main/static"),
                    'login_url':'/playground/login'
                }
        application = web.Application(
            [
                (HTTP_RES['root'], handlers.rootHandle),
                (HTTP_RES['user'], handlers.usersHandle),
                (HTTP_RES['userOne'], handlers.userOneHandle),
                (HTTP_RES['device'], handlers.devicesHandle),
                (HTTP_RES['deviceOne'], handlers.deviceOneHandle),
                (HTTP_RES['sensor'], handlers.sensorsHandle),
                (HTTP_RES['sensorOne'], handlers.sensorOneHandle),
                (HTTP_RES['dataSet'], handlers.datasetHandle),
                (HTTP_RES['commandSet'], handlers.commandsetHandle),
                (HTTP_RES['commandSetOne'], handlers.commandsetOneHandle),
                (HTTP_RES['deviceAuth'], handlers.deviceauthHandle),
                (HTTP_RES['accessKey'], handlers.accessKeyHandle),
                (HTTP_RES['userLogin'], handlers.userLoginHandle),
                (HTTP_RES['userLogout'], handlers.userLogoutHandle),
                ##playgruod below
                (r'/playground', playground.rootHandle),
                (r'/playground/login', playground.loginHandle),
            ], **settings)
        ServerClass.server = HTTPServer(application)
        ServerClass.server.listen(configure.server_port,configure.server_ip)
        try:
            ioloop.IOLoop.instance().start()
        except Exception,e:
            log.logFatal("start server fail, exception:"+e.message)
            ServerClass._lock = False
def home():
    db.db_init()        # establishes connection to the database and create tables (if they don't exist yet)
    option = st.sidebar.selectbox('Select module', ['', 'Patients', 'Doctors', 'Prescriptions', 'Medical Tests', 'Departments'])
    if option == 'Patients':
        patients()
    elif option == 'Doctors':
        doctors()
    elif option == 'Prescriptions':
        prescriptions()
    elif option == 'Medical Tests':
        medical_tests()
    elif option == 'Departments':
        departments()
Ejemplo n.º 6
0
def reset_password_request(username, email):
    global error

    db = dbase.db_init(login_db)
    with db:
        cursor = db.cursor()
        cursor.execute("SELECT * FROM Users WHERE username = ?", [username])

        user = cursor.fetchone()

        if user:
            if user["email"] != email:
                error = "The e-mail address you provided does not match the one in our database."
                return False

            dtime = datetime.now()
            hash = hashlib.sha512()
            hash.update(username)
            hash.update(str(datetime.now()))
            hash.update(os.urandom(20))

            cursor.execute(
                "UPDATE Users SET password_reset_link = ?, password_reset_date = ? WHERE username = ?;",
                [hash.hexdigest(), dtime, username])

            if send_mail(
                    user["email"], "Mekong.com.au: Reset password request",
                    "Dear %s,\n\nWe have received a request to reset your password.\n\nBefore resetting your password, it is our policy to request that you click the following link, http://www.cse.unsw.edu.au/~chrisdb/mekong.cgi?page=reset-password&link=%s.\n\nIf you did not authorise this request, you may choose to ignore this email.\n\nIf you didn't create an account with Mekong, please contact us at [email protected] immediately. Do not provide personal details in this email."
                    % (user["firstname"], hash.hexdigest())):
                return True
        else:
            error = "Could not find username '%s'" % (username)
        return False
Ejemplo n.º 7
0
def authenticate_user(username, password):
    global error
    error = "Authentication error: "

    if legal_username(username):
        db = dbase.db_init(login_db)

        with db:
            cursor = db.cursor()
            cursor.execute("SELECT * FROM Users WHERE username = ?",
                           [username])

            user = cursor.fetchone()

            hash = hashlib.sha512()
            hash.update(password)
            password = hash.hexdigest()

            if not user:
                error += "username '" + username + "' does not exist."
            elif password != user["password"]:
                error += "incorrect username or password."
            elif user[
                    "confirmed"]:  # a value here means that they haven't clicked on the link yet!
                error += "please confirm your registration prior to logging in."
            else:
                error = ""
                return user
    else:
        error += "incorrect username or password."
    return None
Ejemplo n.º 8
0
def execute_order(account, month, year, credit_card, postage):
    global error
    if year == date.today().year and month < date.today().month:
        error = "Your card has expired."
    else:
        db = dbase.db_init(checkout_db)
        
        with db:
            cursor = db.cursor()
            cursor.execute("SELECT * FROM Baskets WHERE username = ?;", [account["username"]])
            
            books = cursor.fetchall()
            if books:
                isbn = ""
                hash = hashlib.sha512(credit_card)
                last_four = credit_card[-4:]
                now = datetime.now()
                for b in books:
                   isbn += "%s*%d;" % (b["isbn"], b["quantity"])
                
                cursor.execute("INSERT INTO Orders(username, credit_card, expiry, last_four, isbns, date_of_order, postage, total_price) VALUES(?, ?, ?, ?, ?, ?, ?, ?);",\
                                             [account["username"], hash.hexdigest(), "%s/%s" % (str(month), str(year)), last_four, isbn, now, postage, trolley.total_basket(account["username"])])
                cursor.execute("DELETE FROM Baskets WHERE username = ?;", [account["username"]])
                return True
            else:
                error = "Your trolley is empty!"
    return False
Ejemplo n.º 9
0
def change_password_backend(username, current_password, new_password):
    global error

    db = dbase.db_init(login_db)
    with db:
        cursor = db.cursor()
        cursor.execute(
            "SELECT * FROM Users WHERE username = ? AND password = ?;",
            [username, current_password])

        user = cursor.fetchone()

        if user:
            if legal_password(new_password, user["username"],
                              user["firstname"], user["lastname"]):
                hash = hashlib.sha512()
                hash.update(new_password)

                if hash.hexdigest() != user["password"]:
                    cursor.execute(
                        "UPDATE Users SET password = ? WHERE username = ? AND password = ?;",
                        [hash.hexdigest(), username, user["password"]])
                    error = ""
                    return True
                else:
                    error = "Password update error: new password cannot match old password."
        else:
            error = "Password update error: incorrect password."

    return False
Ejemplo n.º 10
0
def unique_email(email):
    db = dbase.db_init(login_db)
    rows = None
    with db:
        cursor = db.cursor()
        cursor.execute("SELECT * FROM Users WHERE email = ?", [email])

        rows = cursor.fetchone()
    return rows is None
Ejemplo n.º 11
0
def handle_requests():
    db.db_init()
    front_end_path='http://localhost:8080'
    if request.method == 'POST':
        print(request.json)
        
        if  request.json['header'] == 'insert':
            return db.db_insert(request.json)

        if request.json['header']  == 'update':
            db.db_update(request.json)        
        
        if request.json['header']  == 'fetch':
            return db.db_search(request.json)

        return str(request.method)

    if request.method == 'GET':
        return str(request.method)
Ejemplo n.º 12
0
def unique_username(username):
    db = dbase.db_init(login_db)
    rows = None
    with db:
        cursor = db.cursor()
        cursor.execute("SELECT * FROM Users WHERE username = ?", [username])

        rows = cursor.fetchone()

    return rows is None
Ejemplo n.º 13
0
def read_basket(username, order, asc):
    db = dbase.db_init(basket_db)
    rows = None
    
    with db:
        cursor = db.cursor()
        cursor.execute("PRAGMA foreign_keys = ON")
        cursor.execute("SELECT * FROM Baskets WHERE username = ? ORDER BY (SELECT %s FROM Books WHERE Books.isbn = isbn) %s" % (dbase.sanitise(order), dbase.sanitise(asc)), [username])
        
        rows = cursor.fetchall()
    return rows
Ejemplo n.º 14
0
def search_books(criteria, category, order, asc):
    db = dbase.db_init(books_db)
    
    with db:
        cursor = db.cursor()
        if (category == "isbn" and legal_isbn(criteria)):
            cursor.execute("SELECT * FROM Books WHERE isbn = ?", [criteria])
        else:
            cursor.execute("SELECT * FROM Books WHERE " + dbase.sanitise(category) + " REGEXP ? ORDER BY " + dbase.sanitise(order) + " " + dbase.sanitise(asc), [criteria])

        booklist = cursor.fetchall()
    return booklist
Ejemplo n.º 15
0
def add_basket(username, isbn, quantity):
    db = dbase.db_init(basket_db)
    
    with db:
        cursor = db.cursor()
        cursor.execute("SELECT * FROM Baskets WHERE username = ? AND isbn = ?", [username, isbn])
        
        book = cursor.fetchone()
        if book:
            cursor.execute("UPDATE Baskets SET quantity = ? WHERE username = ? AND isbn = ?", [int(book["quantity"]) + int(quantity), username, isbn])
        else:
            cursor.execute("INSERT INTO Baskets VALUES(?, ?, ?);", [username, isbn, quantity])
Ejemplo n.º 16
0
def reset_password_validate(link):
    global error

    db = dbase.db_init(login_db)
    with db:
        cursor = db.cursor()
        cursor.execute("SELECT * FROM Users WHERE password_reset_link = ?;",
                       [link])

        user = cursor.fetchone()

        if user:
            now = datetime.now()
            then = user["password_reset_date"]
            #            time_difference = now - then
            #            if time_difference.total_seconds() < (60 * 60 * 24 * 2): # seconds/minute * minutes/hour * hours/day * max days before timeout
            print """
<div class="bs-callout bs-callout-info">
  <h4>Nearly there!</h4>
  <p>Just enter your new password into the boxes below and press the button to reset your password!</p>
</div>

                
<form class="form-group" action="mekong.cgi?page=validate-password" method="post">
  <div class="control-group">
    <label for="username">
      New password
    </label>
    <div class="controls">
      <input name="password" class="form-control" type="password" maxlen="64" required />
      <p class="help-block"></p>
    </div>
  </div>
  <div class="form-group">
    <label for="email">
      Confirm new password
    </label>
    <input name="confirm-password" class="form-control" type="password" maxlen="64" required />
  </div>
  <div class="controls">
    <input type="hidden" name="userid" value="%s" />
    <button type="submit" class="btn btn-info">Reset my password</button>
  </div>
</form>
""" % (link)
            return True
#            else:
#                error = "The link timed out. You only have two days to reset your password."
#                return False
        else:
            error = "Invalid link"
            return False
    return False
Ejemplo n.º 17
0
def first_look():
    db = dbase.db_init(books_db)
    random_books = []
    with db:
        cursor = db.cursor()
        cursor.execute("SELECT * FROM Books WHERE salesrank <= 10 ORDER BY salesrank ASC")
       
        books = cursor.fetchall()
        
        for i in range(1, 10):
            random_books.append(books[i])
            
    return random_books
Ejemplo n.º 18
0
def read_basket(username, order, asc):
    db = dbase.db_init(basket_db)
    rows = None

    with db:
        cursor = db.cursor()
        cursor.execute("PRAGMA foreign_keys = ON")
        cursor.execute(
            "SELECT * FROM Baskets WHERE username = ? ORDER BY (SELECT %s FROM Books WHERE Books.isbn = isbn) %s"
            % (dbase.sanitise(order), dbase.sanitise(asc)), [username])

        rows = cursor.fetchall()
    return rows
Ejemplo n.º 19
0
def count_basket(username):
    items = 0
    
    db = dbase.db_init(basket_db)
    with db:
        cursor = db.cursor()
        cursor.execute("SELECT * FROM Baskets WHERE username = ?;", [username])
        
        trolley = cursor.fetchall()
        
        for item in trolley:
            items += item["quantity"]
            
    return items
Ejemplo n.º 20
0
def set_basket(username, isbn, quantity):
    db = dbase.db_init(basket_db)
    
    with db:
        cursor = db.cursor()
        cursor.execute("SELECT * FROM Baskets WHERE username = ? AND isbn = ?;", [username, isbn])
        book = cursor.fetchone()
       
        if book:
            cursor.execute("UPDATE Baskets SET quantity = ? WHERE username = ? AND isbn = ?;", [quantity, username, isbn])
            cursor.execute("DELETE FROM Baskets WHERE quantity <= 0;")
        else:
            if quantity > 0:
                cursor.execute("INSERT INTO Baskets VALUES(?, ?, ?);", [username, isbn, quantity])
Ejemplo n.º 21
0
def delete_basket(username, isbn, quantity):
    db = dbase.db_init(basket_db)
    
    with db:
        cursor = db.cursor()
        cursor.execute("SELECT * FROM Baskets WHERE username = ? AND isbn = ?", [username, isbn])
        
        book = cursor.fetchone()
        if book:
            new_quantity = book["quantity"] - quantity
            if new_quantity > 0:
                cursor.execute("UPDATE Baskets SET quantity = ? WHERE username = ? AND isbn = ?", [new_quantity, username, isbn])
            else:
                cursor.execute("DELETE FROM Baskets WHERE username = ? AND isbn = ?", [username, isbn])
Ejemplo n.º 22
0
def count_basket(username):
    items = 0

    db = dbase.db_init(basket_db)
    with db:
        cursor = db.cursor()
        cursor.execute("SELECT * FROM Baskets WHERE username = ?;", [username])

        trolley = cursor.fetchall()

        for item in trolley:
            items += item["quantity"]

    return items
Ejemplo n.º 23
0
def total_basket(username):
    total_price = 0.00
    
    db = dbase.db_init(basket_db)
    with db:
        cursor = db.cursor()
        cursor.execute("SELECT * FROM Baskets WHERE username = ?;", [username])
        
        trolley = cursor.fetchall()
        
        for item in trolley:
            cursor.execute("SELECT price FROM Books WHERE isbn = ?;", [item["isbn"]])
            book = cursor.fetchone()
            total_price += (book["price"] * item["quantity"])
            
        return total_price
Ejemplo n.º 24
0
def add_basket(username, isbn, quantity):
    db = dbase.db_init(basket_db)

    with db:
        cursor = db.cursor()
        cursor.execute("SELECT * FROM Baskets WHERE username = ? AND isbn = ?",
                       [username, isbn])

        book = cursor.fetchone()
        if book:
            cursor.execute(
                "UPDATE Baskets SET quantity = ? WHERE username = ? AND isbn = ?",
                [int(book["quantity"]) + int(quantity), username, isbn])
        else:
            cursor.execute("INSERT INTO Baskets VALUES(?, ?, ?);",
                           [username, isbn, quantity])
Ejemplo n.º 25
0
def total_basket(username):
    total_price = 0.00

    db = dbase.db_init(basket_db)
    with db:
        cursor = db.cursor()
        cursor.execute("SELECT * FROM Baskets WHERE username = ?;", [username])

        trolley = cursor.fetchall()

        for item in trolley:
            cursor.execute("SELECT price FROM Books WHERE isbn = ?;",
                           [item["isbn"]])
            book = cursor.fetchone()
            total_price += (book["price"] * item["quantity"])

        return total_price
Ejemplo n.º 26
0
def delete_basket(username, isbn, quantity):
    db = dbase.db_init(basket_db)

    with db:
        cursor = db.cursor()
        cursor.execute("SELECT * FROM Baskets WHERE username = ? AND isbn = ?",
                       [username, isbn])

        book = cursor.fetchone()
        if book:
            new_quantity = book["quantity"] - quantity
            if new_quantity > 0:
                cursor.execute(
                    "UPDATE Baskets SET quantity = ? WHERE username = ? AND isbn = ?",
                    [new_quantity, username, isbn])
            else:
                cursor.execute(
                    "DELETE FROM Baskets WHERE username = ? AND isbn = ?",
                    [username, isbn])
Ejemplo n.º 27
0
def set_basket(username, isbn, quantity):
    db = dbase.db_init(basket_db)

    with db:
        cursor = db.cursor()
        cursor.execute(
            "SELECT * FROM Baskets WHERE username = ? AND isbn = ?;",
            [username, isbn])
        book = cursor.fetchone()

        if book:
            cursor.execute(
                "UPDATE Baskets SET quantity = ? WHERE username = ? AND isbn = ?;",
                [quantity, username, isbn])
            cursor.execute("DELETE FROM Baskets WHERE quantity <= 0;")
        else:
            if quantity > 0:
                cursor.execute("INSERT INTO Baskets VALUES(?, ?, ?);",
                               [username, isbn, quantity])
Ejemplo n.º 28
0
def confirm_account(link):
    global error

    db = dbase.db_init(login_db)
    with db:
        cursor = db.cursor()
        cursor.execute("SELECT * FROM Users WHERE confirmed = ?;", [link])

        user = cursor.fetchone()

        if user:
            cursor.execute(
                "UPDATE Users SET confirmed = '' WHERE confirmed = ?;", [link])
            return True
        else:
            error = """
Accounts can only be confirmed once, so you might have already confirmed your account. If this is the case please log in using the form at the top of the page.<br/>
If you haven't confirmed your account yet, please ensure that you copied the URL from your email correctly.<br/>Queries may be sent to [email protected].<br/>
"""
            return False
Ejemplo n.º 29
0
def create_account(user):
    global error
    if legal_username(user["username"]):
        if not unique_username(user["username"]):
            error = "Create account error: username is not unique"
        if not unique_email(user["email"]):
            error = "Create account error: e-mail is not unique"
        else:
            if legal_password(user["password"], user["username"],
                              user["firstname"], user["lastname"]):
                db = dbase.db_init(login_db)

                with db:
                    cursor = db.cursor()

                    hash = hashlib.sha512()
                    hash.update(user["password"])
                    pwd = hash.hexdigest()

                    hash = hashlib.sha512()
                    hash.update(user["username"])
                    hash.update(user["firstname"])
                    hash.update(str(datetime.now()))
                    hash.update(os.urandom(20))

                    confirmation = hash.hexdigest()

                    if not send_mail(
                            user["email"], "Mekong.com.au: Account activation",
                            "Dear %s,\n\nThis email is to confirm that you have requested an account with mekong.com.au.\n\nIf you created the account, please click on the following link http://www.cse.unsw.edu.au/~chrisdb/mekong.cgi?page=confirm-account&link=%s.\n\nIf you did not create the account, please send an email to [email protected] to rectify the issue.\n\nKind regards,\n\nMekong staff"
                            % (user["firstname"], confirmation)):
                        return False

                    cursor.execute("INSERT INTO Users VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", [user["username"], pwd, user["firstname"], user["lastname"],\
                                            user["address"], user["suburb"], user["state"], user["postcode"], user["dob"], user["email"], user["phone"], user["sex"], confirmation, "", ""])
                    return True
    return False
Ejemplo n.º 30
0
def reset_password(link, password):
    global error

    db = dbase.db_init(login_db)
    with db:
        cursor = db.cursor()
        cursor.execute("SELECT * FROM Users WHERE password_reset_link = ?",
                       [link])

        user = cursor.fetchone()

        if user:
            if change_password_backend(user["username"], user["password"],
                                       password):
                cursor.execute(
                    "UPDATE Users SET password_reset_link = '', password_reset_date = '' WHERE username = ?;",
                    [user["username"]])
                return True
        else:
            error = "User does not exist."
            return False
    error += '<br/><a href="mekong.cgi?page=reset-password&link=%s">Click here</a> to try again' % (
        link)
    return False
Ejemplo n.º 31
0
from flask import Flask
import database

app = Flask(__name__)
app.config.from_object('config')
db = database.db_init()

from app import views
Ejemplo n.º 32
0
                        "comment":comment_tag.string,
                        "quote":quote_tag.string,
                        "rating_date":rating_date_tag.string
                    }
                    self._db[_COLL_NAME].insert(spec_doc, w=1)

            next_page_tag = soup.find("a", class_="nav next rndBtn ui_button primary taLnk")
            if next_page_tag is not None:
                route = next_page_tag.attrs["href"]
                logging.info("has next route and continue...")
            else:
                # print content
                # print bubble_tags
                break

db = db_init(db_name="spider")

def run():
    logging.info("spiders start work...")
    user_agent = random.choice(user_agents)
    headers = {
        "User-agent":user_agent,
        "Referer":"https://www.tripadvisor.cn",
        "accept":"*/*",
        "Host":"www.tripadvisor.cn",
    }
    headers = {}
    def prepare_thread():
        name = "crawl_thread1"
        # init_route = "/Hotel_Review-g664891-d657141-Reviews-The_Venetian_Macao_Resort_Hotel-Macau.html"
        init_route = "/Hotel_Review-g664891-d657141-Reviews-or1510-The_Venetian_Macao_Resort_Hotel-Macau.html#REVIEWS"
Ejemplo n.º 33
0
 def get(self):
     database.db_init()
     # self.render('templates/list.html', title='Drop DB and fill with prepared data')
     self.redirect('/')
Ejemplo n.º 34
0
    def create_widgets(self):
        self.frame = tk.Frame(master=self.master, bg="#353a40")
        self.frame.pack(fill=tk.BOTH, expand=True)
        self.frame.columnconfigure((0, 1), weight=1)
        self.frame.rowconfigure(3, weight=1)

        self.weekday_label = tk.Label(
            master=self.frame,
            text=ToDo.week_days[datetime.now().weekday()],
            font="Roboto 16 bold",
            bg="#27292D",
            fg="#e2e9f1")
        self.date_label = tk.Label(master=self.frame,
                                   text=date.today().strftime("%b %d, %Y"),
                                   font="Roboto 12",
                                   bg="#27292D",
                                   fg="#5c636b")
        self.weekday_label.grid(row=0, column=0, columnspan=2, sticky="ew")
        self.date_label.grid(row=1, column=0, columnspan=2, sticky="new")

        self.empty_label = tk.Label(master=self.frame, bg="#27292D")
        self.empty_label.grid(row=2, column=0, columnspan=2, sticky="nsew")

        self.todo_list = tk.Listbox(master=self.frame,
                                    font="Roboto 16 italic",
                                    bg="#27292D",
                                    bd=0,
                                    fg="#DFDFDD",
                                    highlightthickness=0,
                                    selectbackground="#273a64")
        self.todo_list.grid(row=3, column=0, columnspan=2, sticky="nsew")

        self.entry_todo = tk.Entry(master=self.frame,
                                   font="Roboto 14 italic",
                                   fg="#DFDFDD",
                                   justify="left",
                                   bd=0,
                                   width="10",
                                   bg="#2D2F34")
        self.entry_todo.grid(row=4, column=0, sticky="nsew")

        self.insert_btn = tk.Button(
            master=self.frame,
            text="Add",
            background="#2D2F34",  # фоновый цвет кнопки
            foreground="#DFDFDD",  # цвет текста
            activebackground="#1D1D1D",
            activeforeground="#8C8C8C",
            borderwidth=0,
            padx="0",  # отступ от границ до содержимого по горизонтали
            pady="0",  # отступ от границ до содержимого по вертикали
            font="Roboto 14",  # высота шрифта
            command=self.add_item)

        self.delete_btn = tk.Button(
            master=self.frame,
            text="Delete",
            background="#2D2F34",  # фоновый цвет кнопки
            foreground="#DFDFDD",  # цвет текста
            activebackground="#1D1D1D",
            activeforeground="#8C8C8C",
            borderwidth=0,
            padx="0",  # отступ от границ до содержимого по горизонтали
            pady="0",  # отступ от границ до содержимого по вертикали
            font="Roboto 14",  # высота шрифта
            command=self.delete_item)

        self.done_btn = tk.Button(
            master=self.frame,
            text="Done",
            background="#2D2F34",  # фоновый цвет кнопки
            foreground="#DFDFDD",  # цвет текста
            activebackground="#1D1D1D",
            activeforeground="#8C8C8C",
            borderwidth=0,
            padx="0",  # отступ от границ до содержимого по горизонтали
            pady="0",  # отступ от границ до содержимого по вертикали
            font="Roboto 14",  # высота шрифта
            command=self.done_item)

        self.statistic_btn = tk.Button(
            master=self.frame,
            text="Get statistic",
            background="#2D2F34",  # фоновый цвет кнопки
            foreground="#DFDFDD",  # цвет текста
            activebackground="#1D1D1D",
            activeforeground="#8C8C8C",
            borderwidth=0,
            padx="0",  # отступ от границ до содержимого по горизонтали
            pady="0",  # отступ от границ до содержимого по вертикали
            font="Roboto 14",  # высота шрифта
            command=self.get_statistic)

        self.insert_btn.grid(row=4, column=1, sticky="nsew")
        self.delete_btn.grid(row=5, column=1, sticky="ew")
        self.done_btn.grid(row=5, column=0, sticky="ew")
        self.statistic_btn.grid(row=6, column=0, columnspan=2, sticky="ew")

        database.db_init(self.conn)
        self.get_data_from_database()
Ejemplo n.º 35
0
# @Time    : 2020/1/14 14:35
# @Author  : 帅气的陈小陌
# @Email   : [email protected]
# File     : database_init.py
# Software : PyCharm
from database import db_init

db_init()



Ejemplo n.º 36
0
from typing import List, Dict, Set, Tuple

########################### FLASK and SOCKETIO setup ###########################
app = Flask('web_server')
# CORS(app)
# cors = CORS(app, resources={
# 	r'/*': {
# 		'origin': '*'
# 	}
# })

socketio = SocketIO(app, cors_allowed_origins='*')

########################### Database setup ###########################
db = db_init()

############################### Global Variables ###############################
# Stores all parties in a dictionary keyed by `party_id`
page_sids: Dict[str, Set[str]] = defaultdict(set)
user_to_page: Dict[str, str] = {}
thread_messages: Dict[str, List[dict]] = defaultdict(list)
page_threads: Dict[str, List[str]] = defaultdict(list)
mouse_pos: Dict[str, Tuple[int, int]] = {}
sids = set()


################################ HTML Rendering ################################
# This method is only used to render the test webpage and can be diabled on your
# own webserver
@app.route('/')
Ejemplo n.º 37
0
def present_trolley(username):
    str = ""
    db = dbase.db_init(basket_db)
    with db:
        cursor = db.cursor()
        cursor.execute("SELECT * FROM Baskets WHERE username = ?;", [username])

        trolley = cursor.fetchall()

        for item in trolley:
            cursor.execute("SELECT * FROM Books WHERE isbn = ?;",
                           [item["isbn"]])

            book = cursor.fetchone()

            str += """
<div class="media-body">
    <div class="row">
      <div class="col-md-2">
        <center>
          <a href="#%s" data-toggle="modal">
            <img class="media-object alt="No picture to display" src="%s">
          </a>
        </center>
      </div>
      <div class="col-md-8">
        <a href="#%s" data-toggle="modal">
          <h4 class="media-heading">%s</h4>
        </a>
      </div>
      <div class="col-md-2" align="right">
        <h4 class="media-heading">$%.2f</h4>
      </div>
      </br>
      <div class="col-md-7">
        <strong>%s</strong>
      </div>
      <div class="col-md-3" align="right">
        <strong>Published by %s</strong>
      </div>
      <br/>
    </div>
  </div>
<div class="media">
  <form action="mekong.cgi?page=trolley" method="post">
    <div class="row">
      <div class="col-md-7"></div>
      <div class="col-md-1"><strong>Quantity:</strong></div>
      <div class="col-md-1">
        <input type="text" class="form-control" name="qty" placeholder="%d" style="width: 60px;" pattern="\d*" maxlen="4" />
        <input type="hidden" name="isbn" value="%s" />
      </div>
      <div class="col-md-1">
        <button type="submit" class="btn btn-success" name="isbn-to-add">Update</button>
      </div>
      <div class="col-md-1">
        <button type="submit" class="btn btn-danger" name="remove" onclick="document.getElementsByName('qty')[0].value = 0;">Remove</button>
      </div>
    </div>
  </form>
</div>
<hr/>
""" % (book["isbn"], book["smallimageurl"], book["isbn"], book["title"],
            book["price"], book["authors"], book["publisher"], item["quantity"],
            book["isbn"])

            str += product_description(book, item["quantity"])
    str += """
<div class="col-md-8"></div>
<div class="col-md-2">
  <h4>Total price: $%.2f</h4>
</div>
<div class="mod-md-2">
  <form action="mekong.cgi?page=checkout" method="post">
    <button type="submit" class="btn btn-info">
      Proceed to checkout
    </button>
  </form>
</div>
""" % total_basket(username)
    return str
Ejemplo n.º 38
0
def init_debug():
    import os.path
    if not os.path.isfile(app.config['DB_NAME'] + '.db'):
        db = db_connect(app.config)
        db_init(db)
        db.close()
Ejemplo n.º 39
0
from discord.ext.commands import Bot

#all bot commands will begin with "!"
mm_bot = Bot(command_prefix="!")


@mm_bot.event
async def on_read():
    print("Client logged in")


#typing !hello will trigger this.
@mm_bot.command()
async def hello(*args):
    return await mm_bot.say("What's up, ")


@mm_bot.command()
async def register(*args):
    user = ''
    print("args: ", args)

    message = "User registered (not really tho, database not implimented yet ;) \n full message: " + str(
        args) + "\n Args[1]: " + str(args[1])
    return await mm_bot.say(message)


#initializing database
database.db_init()
#Starting bot
mm_bot.run(secrets.bot_token)
Ejemplo n.º 40
0
Файл заполняет базу данных

@author: utrobinmv
"""

import os
import json
import zipfile
import base64

from database import db_connect, db_init, db_disconnect, db_insert_selhoz, db_insert_rosreestr, db_insert_img, db_insert_ndvi

connect = db_connect()

db_init(connect)

#Загрузка данных сельхоз земель (закомментировано так как загружаем разные таблицы в разное время)
# with open("data/result.json", "r") as read_file:
#     data = json.load(read_file)
#     for id_object in data:
#         el_obj = data[id_object]
#         db_insert_selhoz(connect, id_object, el_obj)

#Загрузка данных Росреестра (закомментировано так как загружаем разные таблицы в разное время)
# zipFile = zipfile.ZipFile('data/objects.zip', 'r')
# list_files = zipFile.namelist()
# for i, file_name in enumerate(list_files):
#     zipInfo = zipFile.getinfo(file_name)
#     if zipInfo.file_size > 0:
#         # zipFile.extract(file_name, "tmp", )
Ejemplo n.º 41
0
import database
from bson.objectid import ObjectId

donne_database = None

if __name__ == '__main__':
    donne_database = database.Database(url='localhost',
                                       port=27017,
                                       db_name='donne_documents')
    database.db_init(donne_database, [
        database.DOC_1, database.DOC_2, database.DOC_3, database.DOC_4,
        database.DOC_5, database.DOC_6
    ])
Ejemplo n.º 42
0
import Tkinter as tk

from database import db_init
from data import populate_all_tables
from authorization import Authorzation
from user import User
from localization import Province, Store
from receipt import Receipt, Category, Item, ReceiptItem

"""MAIN APPLICATION - PART 1"""
db_exists = os.path.isfile('test.db')

db = 'sqlite:///:memory:'
#db = 'sqlite:///test.db'

session = db_init(db)

if not db_exists:
    populate_all_tables(session)
"""END OF MAIN APPLICATION"""


print("Welcome! Shall we dive in and judge your spending habits?")
print("We can start by figuring out who's here.")

"""INITIALIZING TEST DATA"""
session_user = User('Jacob', 'Hooey', 'jhooey', 'p')

province = session.query(Province).\
                        filter(Province.abbreviation == 'QC').first() 
Ejemplo n.º 43
0
def main():
    db_init()

    link_counter = 0
    course_counter = 0
    links = get_category_links()
    for link in links:
        link_counter += 1
        print("########## PROCESSING COURSE CATALOG ENTRY {0} ##########".format(link_counter))

        courses = get_course_mappings(link)

        for course in courses:
            course_counter += 1
            print("########## PROCESSING COURSE {0} ##########".format(course_counter))

            courseinfo = parse_courseinfo(course)
            #print("COURSE INFO: {0}".format(courseinfo))

            # Skip courses without instructors
            if(courseinfo.get('instructor')) is None:
                continue

            inames = courseinfo.get('instructor')
            #print("INSTRUCTOR: {0}".format(inames))
            #print("DEPARTMENT: {0}".format(courseinfo.get('dept')))
            instructor_query = User.query.filter(
                User.lname == inames.get('lname')).filter(
                User.fname.startswith(inames.get('fname')[0]))

            if len(instructor_query.all()) == 1:
                instructor = instructor_query.first()
            else:
                instructor = instructor_query.filter(User.dept.like(courseinfo.get('dept'))).first()

            #print("INSTRUCTOR QUERY BY NAME/DEPT: {0}".format(instructor))

            if instructor is None:
                idict = get_instructor_info(courseinfo)
                print("COURSE INFO: {0}".format(courseinfo))
                print("INSTRUCTOR INFO: {0}".format(idict))
                if not idict:
                    continue
                #print("ONID: {0}".format(idict.get('ONID Username')))
                instructor = User.query.filter(User.onid == idict.get('ONID Username')).first()

                #print("INSTRUCTOR QUERY BY ONID: {0}".format(instructor))

                if instructor is None:
                    instructor = instructor_dict_to_model(idict)
                    db_session.add(instructor)

            event = Event.query.filter(
                Event.user.any(onid=instructor.onid)) .filter(
                    Event.crn == courseinfo.get('crn')).filter(
                        Event.term == courseinfo.get('term')).filter(
                            Event.sec == courseinfo.get('sec')).first()

            if event is None:
                #print("COURSEINFO: {0}".format(courseinfo))
                event = courseinfo_to_model(courseinfo)
                instructor.events.append(event)

            db_session.commit()



    db_session.commit()
    db_session.remove()
Ejemplo n.º 44
0
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager
from flask_wtf.csrf import CsrfProtect
from config import BASE_DIR, DATABASE_NAME
from flask_bootstrap import Bootstrap
import os

app = Flask(__name__)
app.config.from_object('config')
CsrfProtect(app)
lm = LoginManager(app)
lm.login_view = 'login'
Bootstrap(app)
db = SQLAlchemy(app)


from views import *
import models


if __name__ == '__main__':

    # Checking if our db exists, creating and supplying initial data if it doesn't.
    # NOTE: this will work fine only for SQLite engine (the db file is saved on disk).
    if not os.path.exists(os.path.join(BASE_DIR, DATABASE_NAME)):
        from database import db_init
        db_init()
    app.run(debug=True)
Ejemplo n.º 45
0
def present_trolley(username):
    str = ""
    db = dbase.db_init(basket_db)
    with db:
        cursor = db.cursor()
        cursor.execute("SELECT * FROM Baskets WHERE username = ?;", [username])
        
        trolley = cursor.fetchall()
        
        for item in trolley:
            cursor.execute("SELECT * FROM Books WHERE isbn = ?;", [item["isbn"]])
            
            book = cursor.fetchone()
            
            str += """
<div class="media-body">
    <div class="row">
      <div class="col-md-2">
        <center>
          <a href="#%s" data-toggle="modal">
            <img class="media-object alt="No picture to display" src="%s">
          </a>
        </center>
      </div>
      <div class="col-md-8">
        <a href="#%s" data-toggle="modal">
          <h4 class="media-heading">%s</h4>
        </a>
      </div>
      <div class="col-md-2" align="right">
        <h4 class="media-heading">$%.2f</h4>
      </div>
      </br>
      <div class="col-md-7">
        <strong>%s</strong>
      </div>
      <div class="col-md-3" align="right">
        <strong>Published by %s</strong>
      </div>
      <br/>
    </div>
  </div>
<div class="media">
  <form action="mekong.cgi?page=trolley" method="post">
    <div class="row">
      <div class="col-md-7"></div>
      <div class="col-md-1"><strong>Quantity:</strong></div>
      <div class="col-md-1">
        <input type="text" class="form-control" name="qty" placeholder="%d" style="width: 60px;" pattern="\d*" maxlen="4" />
        <input type="hidden" name="isbn" value="%s" />
      </div>
      <div class="col-md-1">
        <button type="submit" class="btn btn-success" name="isbn-to-add">Update</button>
      </div>
      <div class="col-md-1">
        <button type="submit" class="btn btn-danger" name="remove" onclick="document.getElementsByName('qty')[0].value = 0;">Remove</button>
      </div>
    </div>
  </form>
</div>
<hr/>
""" % (book["isbn"], book["smallimageurl"], book["isbn"], book["title"], book["price"], book["authors"], book["publisher"], item["quantity"], book["isbn"])
            
            str += product_description(book, item["quantity"])
    str += """
<div class="col-md-8"></div>
<div class="col-md-2">
  <h4>Total price: $%.2f</h4>
</div>
<div class="mod-md-2">
  <form action="mekong.cgi?page=checkout" method="post">
    <button type="submit" class="btn btn-info">
      Proceed to checkout
    </button>
  </form>
</div>
""" % total_basket(username)
    return str