def delete_item(item_id: UUID4):
    item = None
    with db_connection() as db:
        db.execute(f"select * from items where id = '{item_id}'")
        item = db.fetchone()

    if not item:
        raise HTTPException(status_code=400, detail="Item not found.")

    with db_connection() as db:
        db.execute(f"delete from items where id = '{item_id}'")
        return {"detail": f"Deleted item with id {item_id}"}
def get_item(item_id: UUID4):
    with db_connection() as db:
        db.execute(f"select * from items where id = '{item_id}'")
        item = db.fetchone()
        if item:
            return item
    raise HTTPException(status_code=400, detail="Item not found.")
Beispiel #3
0
def main():
    connection = db.db_connection('crypto.db')
    coins = get_coins_links(cryptocurrencies)
    data_coin = get_history(coins, connection)
    db.data_record(data_coin, connection)
    connection.commit()
    connection.close()
Beispiel #4
0
def data_status():
    sql = """SELECT web FROM polls_search GROUP BY web"""
    results = db.db_select(sql)
    list_web = {}
    for result in results:
        list_web[result[0]] = {}
    list_status = {"not-read": 0, "applied": 0, "inadequate": 0, "expired": 0, "other": 0}
    for web in list_web:
        list_web[web].update(list_status)
    sql = """SELECT status, COUNT(status), polls_search.web FROM polls_ad
        LEFT JOIN polls_search ON polls_ad.site_id = polls_search.id
        GROUP BY status, polls_search.web"""
    results = db.db_select(sql)
    for result in results:
        list_web[result[2]][result[0]] = result[1]
    conn = db.db_connection()
    for data in list_web:
        total = list_web[data]["not-read"] + list_web[data]["applied"] + list_web[data]["inadequate"] + list_web[data]["expired"] + list_web[data]["other"]
        sql = """INSERT INTO polls_stat (web, not_read, applied, inadequate, expired, other, total)
                VALUES ('{}', {}, {}, {}, {}, {}, {})"""\
        .format(data, list_web[data]["not-read"], list_web[data]["applied"], list_web[data]["inadequate"], list_web[data]["expired"], list_web[data]["other"], total)
        insert = db.injection_sql(conn, sql)
        if insert == "update":
            sql = """UPDATE polls_stat SET not_read={}, applied={}, inadequate={}, expired={}, other={}, total={}
                    WHERE web = '{}'"""\
                .format(list_web[data]["not-read"], list_web[data]["applied"], list_web[data]["inadequate"], list_web[data]["expired"], list_web[data]["other"], total, data)
            db.injection_sql(conn, sql)
    db.db_close(conn)
Beispiel #5
0
 def __init__(self, *args, **kwargs):
     Page.__init__(self, *args, **kwargs)
     label = tk.Label(self, text="This is all exercises")
     label.grid(row=0, column=0)
     all_done_acts_query = "SELECT * FROM done_acts"
     all_done = db_connection(all_done_acts_query, receive=True)
     page_list = ListViewer(self)
     for record in all_done:
         page_list.populate_list(record)
def get_items(response: Response, offset: int = 0, limit: int = 100):
    with db_connection() as db:
        db.execute(
            f"select * from items order by name offset {offset} limit {limit}")
        items = db.fetchall()
        if items:
            response.headers["Content-Range"] = str(len(items))
            return items
    response.headers["Content-Range"] = "0"
    return []
Beispiel #7
0
def lk(result):
    req = requests.get(result[2])
    soup = BeautifulSoup(req.content, "html.parser")
    ads = soup.find_all('li', class_="result-card")
    conn = db.db_connection()
    for ad in ads:
        link = ad.a['href'].split("?")[0]
        title = ad.h3.text.capitalize()
        location = ad.find('span', class_="job-result-card__location").text
        check_status(result[0], title, location, link, description, conn)
    db.db_close(conn)
Beispiel #8
0
def entry_db(business_name, address, contact):
    db, cursor = db_connection()
    cursor.execute(
        "SELECT * from bangalore_ayurvedic_doctors where business_name = %s and address = %s and mobile_number = %s",
        (business_name, address, contact))
    record = cursor.fetchall()
    if record == []:
        cursor.execute(
            "INSERT INTO bangalore_ayurvedic_doctors (business_name,address,mobile_number) VALUES (%s,%s,%s)",
            (business_name, address, contact))
        db.commit()
    db.close()
def update_item(item_id: UUID4,
                item_update: ItemUpdate = Body(
                    ...,
                    example={
                        "name": "An Updated Item",
                        "description": "What it is now."
                    })):
    item = None
    with db_connection() as db:
        db.execute(f"select * from items where id = '{item_id}'")
        item = db.fetchone()

    if not item:
        raise HTTPException(status_code=400, detail="Item not found.")

    with db_connection() as db:
        db.execute(
            f"update items set name = '{item_update.name}', "
            f"description = '{item_update.description}', "
            f"updated_at = '{item_update.updated_at}' where id = '{item_id}'")
        return item_update
Beispiel #10
0
def ep(result):
    req = requests.get(result[2])
    soup = BeautifulSoup(req.content, "html.parser")
    ads = soup.find_all('li', class_="result")
    conn = db.db_connection()
    for ad in ads:
        link = "{}{}".format("https://candidat.pole-emploi.fr", ad.a['href'])
        title = ad.h2.text.replace("\n", "").capitalize()
        location = ad.find('p', class_="subtext").text.replace("\n", "")
        description = ad.find('p', class_="description").text.replace('"', "")
        check_status(result[0], title, location, link, description, conn)
    db.db_close(conn)
def create_item(item_create: ItemCreate = Body(
    ...,
    example={
        "name": "An Item",
        "description": "What it is."
    },
)):
    dict_item = item_create.dict()
    keys, values = ', '.join(dict_item.keys()), ', '.join(
        map(lambda v: f"'{str(v)}'", dict_item.values()))
    with db_connection() as db:
        db.execute(f"insert into items ({keys}) values ({values})")
        return item_create
Beispiel #12
0
    def __init__(self):
        # Error/Info log. not to be confused with message logger
        self.log = logging.getLogger(__name__)

        self.log.info("Initializing...")

        self.r = database.db_connection()
        self.parse_config()
        self.deferred = defer.Deferred()
        self.logger = database.MessageLogger()

        self.log.info("Getting Commands...")
        self.commands = {"!chattiness": self.set_chattiness}

        self.log.info("Generating model...")
        self.get_model()

        self.log.info("...Initialized.")
Beispiel #13
0
 def __init__(self, curWin, uiMan, entryBox, s):
     super().__init__('Submit Score',
                      center_x=480,
                      center_y=_height / 2 - 20,
                      width=250,
                      height=40)
     self.curWindow = curWin
     self.ui_manager = uiMan
     self.entry = entryBox
     self.score = s
     self.dbCon = database.db_connection()
     #button colors, set them to whatever
     self.set_style_attrs(
         font_color=arcade.color.BLACK,
         font_color_hover=arcade.color.BLACK,
         font_color_press=arcade.color.BLACK,
         bg_color=(128, 128, 128),  #Gray
         bg_color_hover=(211, 211, 211),  #Light Gray
         bg_color_press=(255, 255, 255),  #White
         border_color=(64, 224, 208),  #Turquoise
         border_color_hover=arcade.color.BLACK,
         border_color_press=arcade.color.BLACK)
Beispiel #14
0
        Returns Binary 
        """
        flag = False
        if card_number == source_card_number:
            print("\nYou can't transfer money to the same account!")
        elif self.get_checksum(card_number[:-1]) != card_number[-1]:
            print("\nProbably you made a mistake in the card number. Please try again!")
        elif not database.validate_card(connection, card_number):
            print("\nSuch a card does not exist.")
        else:
            flag = True
        return flag


bank = Bank()
connection = database.db_connection()
database.create_table(connection)

while True:
    choice = input(INPUT_PROMPT)
    if choice == "1":
        card_number = bank.generate_card_number()
        pin = bank.generate_pin()
        database.insert_record(connection, card_number, pin)
    elif choice == "2":
        login_card_number = input("\nEnter your card number:\n")
        login_pin = input("Enter your PIN:\n")
        if database.validate_login(connection, login_card_number, login_pin):
            print("\nYou have successfully logged in!")
            bank.login_choices(connection, login_card_number)
        else:
Beispiel #15
0
 def __init__(self):
     self.db_connection = database.db_connection()
     self.token_validator = None
Beispiel #16
0
def update_sql():
    conn = db.db_connection()
    for id_ad in list_id_expired:
        sql = """UPDATE polls_ad SET status='expired' WHERE id={}""".format(id_ad)
        db.injection_sql(conn, sql)
    db.db_close(conn)
Beispiel #17
0
                      bg='green')

        b1.pack(side="left")
        b2.pack(side="left")
        l1.pack(side="left")

        p1.show()


if __name__ == "__main__":

    name = ['acts', 'made', 'days', 'reps', 'avg']
    percentage = []
    for item in get_all_stats():
        for ins in item:
            percentage.append(ins)

    all_acts_querry = "SELECT * FROM acts"
    all_acts = db_connection(all_acts_querry, receive=True)
    all_acts_list = []
    for item in all_acts:
        all_acts_list.append(item[1])
    domain = [[act[1] for act in all_acts], ['total acts made'],
              ['total days with action'], ['total reps'], ['avg reps pro act']]
    root = tk.Tk()
    root.title('Exercise counter')
    main = MainView(root)
    main.pack(side="top", fill="both", expand=True)
    root.wm_geometry("400x350+340+350")
    root.mainloop()
Beispiel #18
0

def insert_done_acts_test_data():
    for line in test_db_record(350):
        add_done_act(line[0], line[1], line[2], line[3])
    print('Finished')


if __name__ == "__main__":
    if not os.path.isfile("exercise.db"):
        print('No database detected, creating...')
        first_time_db()
        print(get_column_names())
    else:
        print('database detected with, \nTable name: ',
              db_connection(sql_command_dict['table_name_sql'], receive=True))
        print()
        if not get_acts():
            print('Adding acts....')
            insert_first_acts()
            print(get_acts())
        else:
            print('Table "acts" items', get_acts())
            if not get_done_acts():
                print('Table "done_acts items :', get_done_acts(),
                      '\nempty table, need data...')
                print('inserting test data for "done_acts" table')
                insert_done_acts_test_data()
            else:
                print("***** Current done acts ***")
                #print(db_connection(sql_command_dict['all_done_acts_sql'], receive=True))