diff --git a/Задания/task1/Epifanov/tgBot(try-exc-finally+usage of func-s in wwfuncs.py).py b/Задания/task1/Epifanov/tgBot(try-exc-finally+usage of func-s in wwfuncs.py).py new file mode 100644 index 0000000..4b804da --- /dev/null +++ b/Задания/task1/Epifanov/tgBot(try-exc-finally+usage of func-s in wwfuncs.py).py @@ -0,0 +1,63 @@ +#Небольшое предисловие: кнопки item1, item2 и item3 похожи по своему функционалу, однако между ними есть разница в реализации - item3 реализована через функцию, прописанную в доп.файле +import telebot +import psycopg2 +from telebot import types +import random +from wwfuncs import select #импорт функции из другого файла + +connection = psycopg2.connect(host='localhost', dbname='FHWDB', user='postgres', password='Q1w2e3r4') +cursor = connection.cursor() + +try: + s_query = """SELECT * FROM public.parse""" + cursor.execute(s_query) +except psycopg2.errors.UndefinedTable: #рассматриваем случай, когда таблицы нет + connection.rollback() #возвращаемся "на действие назад" + import FHWDB #создаём и заполняем таблицу, если её не существовало ранее + connection = psycopg2.connect(host='localhost', dbname='FHWDB', user='postgres', password='Q1w2e3r4') + cursor = connection.cursor() + s_query = '''SELECT * FROM public.parse''' + cursor.execute(s_query) +finally: + arr = list(cursor.fetchall()) + +bot = telebot.TeleBot('5980905704:AAH2qIP4Gy60nhuKNAojOGpmI6zwNoJK1Iw') + +@bot.message_handler(commands=["start"]) +def start(m, res=False): + markup = types.ReplyKeyboardMarkup(resize_keyboard=True) + item1 = types.KeyboardButton("Хочу информацию о любых цветах, пожалуйста") + item2 = types.KeyboardButton("Хочу картинку любых цветов, пожалуйста") + item3 = types.KeyboardButton("Хочу информацию о предложении дня, пожалуйста") + item4 = types.KeyboardButton("Общая информация о сведениях, находящихся в базе данных") + markup.add(item1) + markup.add(item2) + markup.add(item3) + markup.add(item4) + bot.send_message(m.chat.id, + '"Хочу информацию о любых цветах, пожалуйста" - для получения карточки цветов;\n "Хочу картинку любых цветов, пожалуйста" - для получения картинки цветов;\n "Хочу информацию о предложении дня, пожалуйста" - сводка о конкретных цветах;\n "Общая информация о сведениях, находящихся в базе данных" - сводка об характеристиках товаров, информация о которых находится в БД.', + reply_markup=markup) + +@bot.message_handler(content_types=["text"]) +def handle_text(message): + if (message.text.strip() == "Хочу информацию о любых цветах, пожалуйста"): + i = random.choice(arr) + a1 = f'Название: {i[1]};\nЦена: {i[2]};\nСкидка(в процентах): {i[3]};\n' + bot.send_message(message.chat.id, a1) + elif (message.text.strip() == "Хочу картинку любых цветов, пожалуйста"): + i = random.choice(arr) + bot.send_photo(message.chat.id, open(i[4], 'rb')) + elif (message.text.strip() == "Хочу информацию о предложении дня, пожалуйста"): + j = random.randint(1, 61) + i = list(select(j)) + a1 = f'Название: {i[1]};\nЦена: {i[2]};\nСкидка(в процентах): {i[3]};\n' + bot.send_message(message.chat.id, "Предложение дня:\n") + bot.send_message(message.chat.id, a1) + bot.send_photo(message.chat.id, open(i[4], 'rb')) + else: + bot.send_message(message.chat.id, "С помощью данного бота вы можете получить информацию о 60-и цветах одного из московских магазинов по их продаже, в частности их: название, цену, скидку(в процентах) и фото. Вы можете это осуществить, взаимодействуя с ботом. Попробуйте! ") + +bot.polling(none_stop=True, interval=0) + +cursor.close() +connection.close() diff --git a/Задания/task1/Epifanov/wwfuncs.py b/Задания/task1/Epifanov/wwfuncs.py new file mode 100644 index 0000000..598f98f --- /dev/null +++ b/Задания/task1/Epifanov/wwfuncs.py @@ -0,0 +1,22 @@ +import psycopg2 + +connection = psycopg2.connect(host='localhost', dbname='FHWDB', user='postgres', password='Q1w2e3r4') +cursor = connection.cursor() + +def edit(Col, N, NN, value):#Функция внесения изменений и сортировки + upd_query = f'''UPDATE Parse SET {Col} = '{NN}' WHERE {Col} = '{N}' ''' + cursor.execute(upd_query) + ord_query = f'''SELECT * FROM public.parse order by {value};''' + cursor.execute(ord_query) + connection.commit() + +edit('Name', 'Ирисы небесно-голубого цвета', 'Ирисы', 'ID') + +#print(cursor.fetchall()) - для проверки + +def select(ID): + s_query = f'''SELECT * FROM public.Parse where ID = {ID}''' + cursor.execute(s_query) + return cursor.fetchone() + +#print(select(44)) - для проверки diff --git a/Задания/task1/Filcheva/Subot.py b/Задания/task1/Filcheva/Subot.py new file mode 100644 index 0000000..9149111 --- /dev/null +++ b/Задания/task1/Filcheva/Subot.py @@ -0,0 +1,70 @@ +import telebot +import psycopg2 +from telebot import types +# Создаем экземпляр бота +bot = telebot.TeleBot('5898574743:AAF2y_y3U2IfWwQVJ_lF6mmiDPlx1YgU9-Q') +# Функция, обрабатывающая команду /start + +def reply_to_user(message, bot): + query = f"insert into Distilleries(name, place, contacts) values ('{message.text.strip()}', " + bot.send_message(message.chat.id, "Введите адрес винокурни") + bot.register_next_step_handler(message, f2, bot, query) + +def f2(message, bot, query): + query += f"'{message.text.strip()}', " + bot.send_message(message.chat.id, "Введите контакты") + bot.register_next_step_handler(message, f3, bot, query) + +def f3(message, bot, query): + query += f"'{message.text.strip()}')" + connection = psycopg2.connect(host='localhost', dbname='dbdata', user='postgres', password='Q1w2e3r4t5') + cursor = connection.cursor() + cursor.execute(query) + connection.commit() + cursor.close() + connection.close() + bot.send_message(message.chat.id, "Done") + +@bot.message_handler(commands=["start"]) +def start_messanger(messanger): + connection = psycopg2.connect(host='localhost', dbname='dbdata', user='postgres', password='Q1w2e3r4t5') + cursor = connection.cursor() + cursor.execute("select id, name from Distilleries") + first_step = [] + for id, name in cursor.fetchall(): + f_s = str(id) + '. ' + name + first_step.append(f_s) + my_str = '\n'.join(first_step) + bot.send_message(messanger.chat.id, 'Я на связи. Выберите интересующую вас Винокурню, введите ее номер\n' + my_str.strip()) + cursor.close() + connection.close() + + +@bot.message_handler(content_types=["text"]) +def output(put): + n = put.text.strip() + if n.isalpha(): + if n == 'Да': + bot.send_message(put.chat.id, 'Введите название винокурни') + bot.register_next_step_handler(put, reply_to_user, bot) + elif n == 'Нет': + bot.send_message(put.chat.id, 'Хорошего дня') + + else: + connection = psycopg2.connect(host='localhost', dbname='dbdata', user='postgres', password='Q1w2e3r4t5') + cursor = connection.cursor() + cursor.execute(f"select place, contacts, imagelink from Distilleries where id = {n}") + for place, contacts, imagelink in cursor.fetchall(): + answer = 'Адрес: ' + place + ' ' + 'Контакты: ' + contacts + ' ' + 'Фото: ' + imagelink + bot.send_message(put.chat.id, answer) + cursor.close() + connection.close() + markup = types.ReplyKeyboardMarkup(resize_keyboard=True) + item1 = types.KeyboardButton('Да') + item2 = types.KeyboardButton('Нет') + markup.add(item1) + markup.add(item2) + bot.send_message(put.chat.id, 'Хотите ли добавить еще одну винокурнею Крыма?', reply_markup=markup ) + + +bot.polling(none_stop=True, interval=0) diff --git a/Задания/task1/Garanyan/main.py b/Задания/task1/Garanyan/parser.py similarity index 84% rename from Задания/task1/Garanyan/main.py rename to Задания/task1/Garanyan/parser.py index 8e6da15..e4432ec 100644 --- a/Задания/task1/Garanyan/main.py +++ b/Задания/task1/Garanyan/parser.py @@ -14,15 +14,14 @@ Image = soup.find_all(attrs={"class": "holder-img"}) connection = psycopg2.connect(host='localhost', dbname='dbdata', user='postgres', password='Q1w2e3r4') cursor = connection.cursor() -create_q = '''CREATE TABLE Food - (ID serial primary key, Name varchar(500), Price varchar(60), src varchar(100))''' +create_q = '''CREATE TABLE Food (ID serial primary key, Name varchar(500), Price varchar(60), src varchar(100))''' cursor.execute(create_q) connection.commit() #https://smartomato.ams3.cdn.digitaloceanspaces.com/uploads/media/photo/769221/dish_large__1.jpg -for j in range(15): +for j in range(19): url = Image[j].find('img').attrs['src'] - tempf = f"C:\\Users\\Harutyun\\Desktop\\prog\\food{j}.jpg" + tempf = f"img\\food{j}.jpg" wget.download(url, tempf) insert_query = f'''INSERT into public.Food(Name, Price, src) values ('{Name[j].text}', '{Price[j].text}', '{tempf}') ''' cursor.execute(insert_query) diff --git a/Задания/task1/Garanyan/problems.py b/Задания/task1/Garanyan/problems.py new file mode 100644 index 0000000..9cfb872 --- /dev/null +++ b/Задания/task1/Garanyan/problems.py @@ -0,0 +1,28 @@ +import psycopg2 +import wget + +from Задания.task1.Garanyan import parser + +connection = psycopg2.connect(host='localhost', dbname='dbdata', user='postgres', password='Q1w2e3r4') +cursor = connection.cursor() +create_q = '''CREATE TABLE Food (ID serial primary key, Name varchar(500), Price varchar(60), src varchar(100))''' + +try: + cursor.execute(create_q) + connection.commit() +except psycopg2.errors.DuplicateTable: + print("duplicate error") + +for j in range(15): + url = parser.Image[j].find('img').attrs['src'] + tempf = f"img\\food{j}.jpg" + wget.download(url, tempf) + try: + insert_query = f'''INSERT into public.Food(Name, Price, src) values ('{parser.Name[j].text}', '{parser.Price[j].text}', '{tempf}') ''' + cursor.execute(insert_query) + connection.commit() + except: + connection.rollback() + +cursor.close() +connection.close() \ No newline at end of file diff --git a/Задания/task1/Garanyan/tgbot.py b/Задания/task1/Garanyan/tgbot.py new file mode 100644 index 0000000..f02959a --- /dev/null +++ b/Задания/task1/Garanyan/tgbot.py @@ -0,0 +1,44 @@ +import telebot +import psycopg2 +from telebot import types +import random + +connection = psycopg2.connect(host='localhost', dbname='dbdata', user='postgres', password='Q1w2e3r4') +cursor = connection.cursor() +try: + sel_query = """SELECT * FROM public.food""" + cursor.execute(sel_query) +except psycopg2.errors.UndefinedTable: + connection.rollback() + import problems + sel_query = """SELECT * FROM public.food""" + cursor.execute(sel_query) + +array = list(cursor.fetchall()) +bot = telebot.TeleBot('841097550:AAFc5MoFRivTEfv-gOSJctqH53NfYMTKpCc') + +@bot.message_handler(commands=["start"]) +def start(m, res=False): + markup = types.ReplyKeyboardMarkup(resize_keyboard=True) + item1 = types.KeyboardButton("Хот-доги и не только!") + item2 = types.KeyboardButton("Цена товара") + markup.add(item1) + markup.add(item2) + bot.send_message(m.chat.id, + '"Хот-доги и не только!" - для получения случайного товара из нашей хотдожной\n' + ' "Цена товара" - для вывода цены', reply_markup=markup) + +i = random.choice(array) +@bot.message_handler(content_types=["text"]) +def handle_text(message): + global i + if (message.text.strip() == 'Хот-доги и не только!'): + i = random.choice(array) + ans = f'Название: {i[1]}\n' + bot.send_message(message.chat.id, ans) + bot.send_photo(message.chat.id, open(i[3], 'rb')) + elif (message.text.strip() == 'Цена товара'): + ans = f'Цена: {i[2]}\n' + bot.send_message(message.chat.id, ans) + +bot.polling(none_stop=True, interval=0) \ No newline at end of file diff --git a/Задания/task1/Gasanova/bot_database.py b/Задания/task1/Gasanova/bot_database.py new file mode 100644 index 0000000..1c3d867 --- /dev/null +++ b/Задания/task1/Gasanova/bot_database.py @@ -0,0 +1,67 @@ +import telebot +import psycopg2 +from telebot import types +import random + +connection = psycopg2.connect(host='localhost', dbname='work', user='dialuna', password='Timka07') # да-да :D +cursor = connection.cursor() + +try: + sel_query = """SELECT * FROM bot""" + cursor.execute(sel_query) +except psycopg2.errors.UndefinedTable: + connection.rollback() + import problems + sel_query = """SELECT * FROM bot""" + cursor.execute(sel_query) + +array = list(cursor.fetchall()) + + +bot = telebot.TeleBot('secret') + +@bot.message_handler(commands=['start']) +def start(message): + sti = open('st.webp', 'rb') + bot.send_sticker(message.chat.id, sti) + bot.send_message(message.chat.id, "ЙОУ, {0.first_name}!\nЯ твой помощник в мире скейтбординга😎".format(message.from_user, bot.get_me())) + + markup = types.ReplyKeyboardMarkup(resize_keyboard=True) #создание кнопок + btn1 = types.KeyboardButton("Лучший скейтборд этого сезона") + btn2 = types.KeyboardButton("Предложение дня") + btn3 = types.KeyboardButton("Выбор редакции нашей компании") + markup.add(btn1, btn2, btn3) + bot.send_message(message.chat.id, + 'Лучший скейтборд этого сезона - это именно то, что тебе нужно, если хочешь быть самым крутым.\nПредложение дня - то, что актуально на сегодняшний день.\nВыбор редакции - просто доверься выбору наших сотрудников и тебе понравится :)\n', + reply_markup=markup) + + +@bot.message_handler(content_types=['text']) +def handle_text(message): + if (message.text.strip() == "Лучший скейтборд этого сезона"): + i = random.choice(array) + inf = f'Название: {i[2]}\nЦена: {i[3]}\n' + bot.send_message(message.chat.id, inf) + bot.send_photo(message.chat.id, open(i[4], 'rb')) + cat = open('kotik.webm', 'rb') + bot.send_video(message.chat.id, cat) + elif (message.text.strip() == "Предложение дня"): + i = random.choice(array) + inf = f'Название: {i[2]}\nЦена: {i[3]}\n' + bot.send_message(message.chat.id, inf) + bot.send_photo(message.chat.id, open(i[4], 'rb')) + cat = open('kotik.webm', 'rb') + bot.send_video(message.chat.id, cat) + elif (message.text.strip() == "Выбор редакции нашей компании"): + i = random.choice(array) + inf = f'Название: {i[2]}\nЦена: {i[3]}\n' + bot.send_message(message.chat.id, inf) + bot.send_photo(message.chat.id, open(i[4], 'rb')) + cat = open('kotik.webm', 'rb') + bot.send_video(message.chat.id, cat) + else: + bot.send_message(message.chat.id, "Наш бот поможет подобрать вам или близким скейтборд мечты. Скорее пробуйте! ") + + + +bot.polling(none_stop=True, interval=0) diff --git a/Задания/task1/Gasanova/penny.py b/Задания/task1/Gasanova/parsing.py similarity index 82% rename from Задания/task1/Gasanova/penny.py rename to Задания/task1/Gasanova/parsing.py index 686e539..ffecd72 100644 --- a/Задания/task1/Gasanova/penny.py +++ b/Задания/task1/Gasanova/parsing.py @@ -5,7 +5,7 @@ from selenium.webdriver.chrome.service import Service from wget import download import psycopg2 as psyc -# s = Service("chromedriver") на Ubuntu можно не указывать путь до драйвера :) +# s = Service("chromedriver") на Ubuntu можно не указывать путь до драйвера если что :) URL = "https://proskateshop.ru/skejtbordy/?utm_source=yandex&utm_medium=cpc&utm_campaign=cn%7Cskeyty_gz-1%7Ccid%7C51517250%7Csearch&utm_content=gid%7C4180310153%7Caid%7C8980588780%7C20506942844_20506942844%7Cmain&utm_term=%D0%9F%D0%B5%D0%BD%D0%BD%D0%B8%20%D0%B1%D0%BE%D1%80%D0%B4%20%D0%BA%D1%83%D0%BF%D0%B8%D1%82%D1%8C&etext=2202.N39xvihj0F0Od_d4etv_6nh36sdlRP-T26wHLuCJfjo_JZtVI5O7HY5f8FOJnzuLZXB6eWZoZnp2dG1laHBlcA.aceac50a24e4832d82874cd59ca1f9a315d9b351&_openstat=ZGlyZWN0LnlhbmRleC5ydTs1MTUxNzI1MDs4OTgwNTg4NzgwO3lhbmRleC5ydTpndWFyYW50ZWU&yclid=1445113833197462400" brow = webdriver.Chrome() brow.get(URL) @@ -16,14 +16,15 @@ soup = BeautifulSoup(html, "lxml") penny = soup.find_all(attrs={"class": "product-layout product-grid col-lg-4 col-md-4 col-sm-6 col-xs-6"}) -with psyc.connect(dbname="db_for_parse", user="dialuna") as conn: +with psyc.connect(host = "localhost", dbname="work", user="dialuna", password = "Timka07") as conn: with conn.cursor() as cursor: for i, product in enumerate(penny[1:]): image_link = product.find("img").attrs.get("src") image_name = product.find("img").attrs.get("alt") price = product.find("p", attrs={"class": "price"}).text.strip() + download( product.find("img").attrs.get("src"), f"images/{i}.jpg") - cursor.execute(f"""insert into test(link, name, price, file) + cursor.execute(f"""insert into bot(link, name, price, file) values ('{image_link}', '{image_name}', '{price}', 'images/{i}.jpg')""") conn.commit() diff --git a/Задания/task1/Kulikov/db_parsV2.0.py b/Задания/task1/Kulikov/db_parsV2.0.py new file mode 100644 index 0000000..2892449 --- /dev/null +++ b/Задания/task1/Kulikov/db_parsV2.0.py @@ -0,0 +1,54 @@ +from bs4 import BeautifulSoup +from selenium.webdriver import Chrome +from selenium import webdriver +from selenium.webdriver.chrome.service import Service +import time +import wget +import psycopg2 +import re +s = Service('C:\Users\Alex\PycharmProjects\pythonProject\chromedriver.exe') +browser = webdriver.Chrome(service=s) +browser.get('https://music.yandex.ru/chart') +time.sleep (1) +html_text = browser.page_source +soup = BeautifulSoup(html_text, 'lxml') +Трек=soup.find_all('a', class_='d-track__title deco-link deco-link_stronger') +Длительность=soup.find_all('div', class_='d-track__info d-track__nohover') +Автор=soup.find_all('span', class_='d-track__artists') +Картинки=soup.find_all('img', class_='entity-cover__image deco-pane') +str_Картинки=[] +for i in range(len(Картинки)): + str_Картинки.append(Картинки[i]) +str_Картинки=str(str_Картинки) +str_Картинки=re.findall(r'src="(.*?)"',str_Картинки) +for i in range(len(str_Картинки)): + str_Картинки[i]='https:'+str_Картинки[i] +#for i in range(len(str_cartinki)): + #wget.download(str_cartinki[i], 'TOP'+str((i+1))+'.jpeg') + + +connection = psycopg2.connect(dbname = 'dbdata', + user='postgres', password='Q1w2e3r4', + host='localhost') +cursor=connection.cursor() +creat_table="""CREATE TABLE music + (id serial primary key, "Трек" varchar(100), + "Длительность" varchar(100), + "Автор" varchar(100), + "Картинки" varchar(100))""" +cursor.execute(creat_table) +connection.commit() +for Трек, Длительность, Автор, Картинки in zip(Трек, Автор, Длительность, Картинки): + qwery=f"""INSERT INTO public.music( + Трек, Длительность, Автор, Картинки) + VALUES + ('{Трек.text}','{Длительность.text}','{Автор.text}', '{Картинки.text}' )""" + cursor.execute(qwery) + connection.commit() +for i in range(1,len(str_Картинки)+1): + puti = r'C:\papkta' + str(i) + '.jpeg' + qwery=f"""UPDATE public.music + SET Картинки='{puti}' + WHERE id={i}""" + cursor.execute(qwery) + connection.commit() \ No newline at end of file diff --git a/Задания/task1/Kuranova/bot_beer.py b/Задания/task1/Kuranova/bot_beer.py new file mode 100644 index 0000000..844fd7e --- /dev/null +++ b/Задания/task1/Kuranova/bot_beer.py @@ -0,0 +1,85 @@ +import telebot +import random +from telebot import types +import psycopg2 + +bot = telebot.TeleBot('6279990552:AAHxC0hfpQcOrcGKHwvWT7AabQqdE3a5Tp8') + +def request(a): + info = [] + connection = psycopg2.connect(host='localhost', dbname='breweries', user='postgres', password='Q1w2e3r4t5') + cursor = connection.cursor() + cursor.execute(a) + res = cursor.fetchall() + for id, name, place, link in res: + s = [id, name, place, link] + info.append(s) + cursor.close() + connection.close() + return info + +quote = ['В вине есть мудрость, в пиве есть свобода, в воде есть бактерии.\n\nБенджамин Франклин', + 'Пиво — интеллектуальный напиток. Какая досада, что его пьет так много идиотов.\n\nРэй Брэдбери', +'Пьянство — особая форма самоубийства, позволяющая тебе оживать на следующий день. Я, кажется, уже прожил десять или ' +'пятнадцать тысяч жизней.\n\nЧарльз Буковски', +'Я пью, чтобы окружающие меня люди становились интереснее.\n\nДжордж Жан Натан', +'— Уинстон, да вы пьяны!\n— Все верно. А вы уродина. Завтра утром я протрезвею. А вы так и останетесь уродиной.\n\nУинстон Черчилль', +'— Есть в мире вещи получше, чем алкоголь.\n— Да, сэр. Но алкоголь компенсирует их отсутствие.\n\nТерри Пратчетт', +'Если вы заметите человека, который пытается утопить свои горести в стакане, сообщите ему, что горести умеют плавать.\n\nПиттакус Лор', +'Алкоголь, возможно, опаснейший враг человека, но в Библии сказано: возлюби врага своего.\n\nФрэнк Синатра', +'Меня как-то спросили, мучит ли меня похмелье. Нет, ведь для того, чтобы случилось похмелье, нужно перестать пить.\n\nЛемми Килмистер', +'У меня нет проблем с алкоголем. За исключением тех случаев, когда я не могу достать выпивку.\n\nТом Уэйтс', +'Будь осторожен с крепкими напитками. Они могут заставить тебя выстрелить в сборщика налогов… и промахнуться.\n\nРоберт Хайнлайн', +'Плохого виски не бывает. Просто некоторые сорта виски лучше других.\n\nУильям Фолкнер', +'Не всякий, кто пьет, является поэтом. Многие пьют как раз из-за того, что они не поэты.\n\nДадли Мур', +'Компьютер позволяет совершить больше ошибок быстрее, чем какое-либо изобретение в человеческой истории, за исключением, ' +'возможно, револьвера и текилы.\n\nМитч Рэдклифф', +'Я не доверяю верблюдам, и вообще всем, кто может неделю не пить.\n\nДжо Луис', +'Алкоголик — это тип, который тебе не нравится и который пьет столько же, сколько ты.\n\nДилан Томас', +'За алкоголь! Причину и решение всех проблем.\n\nГомер Симпсон'] + +c = request('select id, name, place, imagelink from Information') +def share(message): + a = message.text + b = a.split(',') + connection = psycopg2.connect(host='localhost', dbname='breweries', user='postgres', password='Q1w2e3r4t5') + cursor = connection.cursor() + p = """INSERT INTO Information(id,Name, Place, ImageLink) VALUES + ( '"""+str(int(c[-1][0])+1)+"""', '"""+b[0]+"""', '"""+b[1]+"""', '"""+b[2]+"""');""" + cursor.execute(p) + connection.commit() + cursor.close() + connection.close() + bot.send_message(message.chat.id, 'Вы сделали неоценимую услугу! Спасибо вам большое!') +@bot.message_handler(commands=["start"]) +def start(m, res=False): + markup=types.ReplyKeyboardMarkup(resize_keyboard=True) + item1=types.KeyboardButton("Где выпить?") + item2 = types.KeyboardButton("Знаешь еще места, где можно выпить? Поделись)") + item3 = types.KeyboardButton("Хочешь выпить, но нет повода или тоста? Не переживай, мы и такое предусмотрели;)") + markup.add(item1) + markup.add(item2) + markup.add(item3) + bot.send_message(m.chat.id, 'Если не хочешь заморачиваться, то просто нажми любую из предложенных кнопок\n' + f'А можешь ввести число от {c[0][0]} до {c[-1][0]}, мы тебе выведем номер самой ' + f'лучшей пивоварни :)', reply_markup=markup) + +@bot.message_handler(content_types=["text"]) +def handle_text(message): + if message.text.strip() == 'Где выпить?': + choice = random.randint(1, len(c)-1) + bot.send_message(message.chat.id, f'{c[choice]}') + elif message.text.strip().isnumeric(): + try: + bot.send_message(message.chat.id, f'{c[int(message.text) - 1]}') + except: + bot.send_message(message.chat.id, "Кажись, вы попали не в тот интервал. Попробуйте снова.") + elif message.text.strip() == 'Знаешь еще места, где можно выпить? Поделись)': + bot.send_message(message.chat.id, 'Пиши название, адрес, контакты через запятую!') + bot.register_next_step_handler(message, share) + elif message.text.strip() == 'Хочешь выпить, но нет повода или тоста? Не переживай, мы и такое предусмотрели;)': + bot.send_message(message.chat.id, 'Лови!') + choice1 = random.randint(1, len(quote)-1) + bot.send_message(message.chat.id, quote[choice1]) + +bot.polling(none_stop=True, interval=0) \ No newline at end of file diff --git a/Задания/task1/Lahin/postgres.py b/Задания/task1/Lahin/postgres.py index fe8a029..c0620eb 100644 --- a/Задания/task1/Lahin/postgres.py +++ b/Задания/task1/Lahin/postgres.py @@ -49,12 +49,15 @@ for i in range(len(productst)): u.append(features[10*i+j].text) wget.download(url, filename) t = pricest[i].text.replace("\xa0", " ") - insert = f"""INSERT INTO public.laptops( - Product, Price, Diagonal, Resolution, CPU, RAM, Graphics_Controller, Volume, src) - VALUES - ('{productst[i].text.strip()}', '{t.strip()}', '{u[0][:u[0].find("/")]}', '{u[0][u[0].find("/")+1:]}', - '{u[2]}', '{u[4]+" "+u[5]}', '{u[6]}', '{u[8]}', '{filename}');""" - cursor.execute(insert) - connection.commit() + try: + insert = f"""INSERT INTO public.laptops( + Product, Price, Diagonal, Resolution, CPU, RAM, Graphics_Controller, Volume, src) + VALUES + ('{productst[i].text.strip()}', '{t.strip()}', '{u[0][:u[0].find("/")]}', '{u[0][u[0].find("/")+1:]}', + '{u[2]}', '{u[4]+" "+u[5]}', '{u[6]}', '{u[8]}', '{filename}');""" + cursor.execute(insert) + connection.commit() + except: + connection.rollback() cursor.close() connection.close() \ No newline at end of file diff --git a/Задания/task1/Lahin/select_and_edit'.py b/Задания/task1/Lahin/select_and_edit'.py new file mode 100644 index 0000000..298ef0b --- /dev/null +++ b/Задания/task1/Lahin/select_and_edit'.py @@ -0,0 +1,27 @@ + +import psycopg2 +import config +def edit(request): + try: + connection = psycopg2.connect(host=config.host, dbname=config.dbname, user=config.user, password=config.password) + cursor = connection.cursor() + cursor.execute(request) + print("Done") + except Exception as error: + print(f"Что-то не так. Ошибка:{error}") + finally: + cursor.close() + connection.close() +def select(request): + try: + connection = psycopg2.connect(host=config.host, dbname=config.dbname, user=config.user, + password=config.password) + cursor = connection.cursor() + cursor.execute(request) + result = cursor.fetchall() + except Exception as error: + result = f"Ошибка: {error}" + finally: + cursor.close() + connection.close() + return result \ No newline at end of file diff --git a/Задания/task1/Lahin/telegrambot.py b/Задания/task1/Lahin/telegrambot.py index 3031c38..57d6121 100644 --- a/Задания/task1/Lahin/telegrambot.py +++ b/Задания/task1/Lahin/telegrambot.py @@ -1,15 +1,23 @@ import telebot import psycopg2 import config -def execute_request(request): - connection = psycopg2.connect(host=config.host, dbname=config.dbname, user=config.user, password=config.password) - cursor = connection.cursor() - cursor.execute(request) - result = cursor.fetchall() - cursor.close() - connection.close() - return result -max_id = int(execute_request("select count(*) from laptops")[0][0]) +bot = telebot.TeleBot(config.bot_token) + +def select(request): + try: + connection = psycopg2.connect(host=config.host, dbname=config.dbname, user=config.user, + password=config.password) + cursor = connection.cursor() + cursor.execute(request) + result = cursor.fetchall() + except: + result = "Ошибка" + finally: + cursor.close() + connection.close() + return result + +max_id = int(select("select max(id) from laptops")[0][0]) bot = telebot.TeleBot(config.bot_token) @bot.message_handler(commands=["start"]) def start(m, res=False): @@ -26,12 +34,21 @@ def from_bd(message): bot.send_message(message.chat.id, "ID больше, чем количество товаров. Попробуйте снова:") return else: - data = execute_request(f"select * from laptops where id = {current_id}")[0][1:-1] - names_of_columns = ["Товар", "Цена", "Диагональ", "Разрешение", "Процессор", "Оперативная память", "Графический контроллер", "Объём диска"] - everydata = [] - for data_name, column_name in zip(data, names_of_columns): - everydata.append(column_name.capitalize() + ": " + data_name) - bot.send_message(message.chat.id, "\n\n".join(everydata)) + try: + data = select(f"select * from laptops where id = {current_id}")[0][1:] + if type(data) == str: + bot.send_message(message.chat.id, "Ошибка на сервере") + return + s = data[:-1] + names_of_columns = ["Товар", "Цена", "Диагональ", "Разрешение", "Процессор", "Оперативная память", + "Графический контроллер", "Объём диска"] + everydata = [] + for data_name, column_name in zip(s, names_of_columns): + everydata.append(column_name.capitalize() + ": " + data_name) + bot.send_message(message.chat.id, "\n\n".join(everydata)) + bot.send_photo(message.chat.id, open(data[-1], 'rb')) + except: + bot.send_message(message.chat.id, "Ошибка на сервере") bot.send_message(message.chat.id, f"Введите следующий ID от 1 до {max_id}:") bot.polling(none_stop=True, interval=0) diff --git a/Задания/task1/Markovich/db.py b/Задания/task1/Markovich/db.py new file mode 100644 index 0000000..e5f1c19 --- /dev/null +++ b/Задания/task1/Markovich/db.py @@ -0,0 +1,49 @@ +import telebot +import psycopg2 +from telebot import types +import random + +connection = psycopg2.connect(dbname='dbdata', user='postgres',password='Q1w2e3r4', host='localhost') +cursor = connection.cursor() + + +sel_query = """SELECT * FROM public.pizza""" +cursor.execute(sel_query) +array = list(cursor.fetchall()) + +bot = telebot.TeleBot('6161398146:AAEY99Cox8omow3OnURN_mwXDOpAOfTp09w') + +@bot.message_handler(commands=["start"]) +def start(m, res=False): + markup = types.ReplyKeyboardMarkup(resize_keyboard=True) + item1 = types.KeyboardButton("Хочу пирог!") + item2 = types.KeyboardButton("Какова цена?") + item3 = types.KeyboardButton("Описание") + markup.add(item1) + markup.add(item2) + markup.add(item3) + bot.send_message( + m.chat.id, '"Хочу пирог!" - для получения пирога\n "Какова цена?" - для получения цены\n "Описание" - описание', + reply_markup=markup) + +i = random.choice(array) +@bot.message_handler(content_types=["text"]) +def handle_text(message): + if (message.text.strip() == 'Хочу пирог!'): + ans = f'{i[1]}\n' + bot.send_message(message.chat.id, ans) + try: + bot.send_photo(message.chat.id, open(i[4], 'rb')) + except telebot.apihelper.ApiTelegramException: + bot.send_message(message.chat.id, "Проблемы с загрузкой картинки....Продолжайте") + elif (message.text.strip() == 'Какова цена?'): + ans = f'{i[3]}\n' + bot.send_message(message.chat.id, ans) + elif (message.text.strip() == 'Описание'): + ans = f'{i[2]}\n' + bot.send_message(message.chat.id, ans) + +bot.polling(none_stop=True, interval=0) + +cursor.close() +connection.close() \ No newline at end of file diff --git a/Задания/task1/Prokhorova/botpars.py b/Задания/task1/Prokhorova/botpars.py new file mode 100644 index 0000000..2063830 --- /dev/null +++ b/Задания/task1/Prokhorova/botpars.py @@ -0,0 +1,37 @@ +import telebot +import psycopg2 +from telebot import types +import random + +connection = psycopg2.connect(host='localhost', dbname='dbdata', user='postgres', password='Q1w2e3r4') + +cursor = connection.cursor() + +BD = """SELECT * FROM public.food""" +cursor.execute(BD) +array = list(cursor.fetchall()) + +bot = telebot.TeleBot('5696445699:AAEPKQgUAs39DTLr_iyQvlaFAsJNFK8DMnc') +@bot.message_handler(commands=["start"]) +def start(m, res=False): + markup = types.ReplyKeyboardMarkup(resize_keyboard=True) + item1 = types.KeyboardButton("Рандомный товар") + item2 = types.KeyboardButton("Повтор !") + markup.add(item1) + markup.add(item2) + bot.send_message(m.chat.id, + '"Рандомный товар" - для получения карточки товара\n "Повтори !" - для повторения сообщений.', + reply_markup=markup) + + +@bot.message_handler(content_types=["text"]) +def handle_text(message): + if (message.text.strip() == 'Рандомный товар'): + i = random.choice(array) + ans = f'Название: {i[1]}\nЦена: {i[2]}\nГрамм: {i[3]}\nРэйтинг: {i[4]}\n' + bot.send_message(message.chat.id, ans) + elif (message.text.strip() == 'Повтори !'): + bot.send_message(message.chat.id, 'Ввод: ' + message.text) + + +bot.polling(none_stop=True, interval=0) \ No newline at end of file diff --git a/Задания/task1/Prokhorova/dz.py b/Задания/task1/Prokhorova/dz.py index 2dfcb87..1a47e12 100644 --- a/Задания/task1/Prokhorova/dz.py +++ b/Задания/task1/Prokhorova/dz.py @@ -1,8 +1,9 @@ -import psycopg2 + import psycopg2 import wget from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.chrome.service import Service + connection = psycopg2.connect(host='localhost', dbname='dbdata', user='postgres', password='Q1w2e3r4') cursor = connection.cursor() diff --git a/Задания/task1/Sukhanov/BOT_TG.py b/Задания/task1/Sukhanov/BOT_TG.py index 8b13789..4972205 100644 --- a/Задания/task1/Sukhanov/BOT_TG.py +++ b/Задания/task1/Sukhanov/BOT_TG.py @@ -1 +1,39 @@ +import telebot +import psycopg2 +import config +from telebot import types +import random +connection = psycopg2.connect(host='localhost', dbname='dbdata', user='postgres', password='Q1w2e3r4') + +cursor = connection.cursor() + +sel_query = """SELECT * FROM public.parser""" +cursor.execute(sel_query) +array = list(cursor.fetchall()) + +bot = telebot.TeleBot('6293063008:AAEFscB5LEjxC_4irrcgT-z6Eb0NXYOxZng') +@bot.message_handler(commands=["start"]) +def start(m, res=False): + markup = types.ReplyKeyboardMarkup(resize_keyboard=True) + item1 = types.KeyboardButton("Рандомный продукт") + item2 = types.KeyboardButton("Повтори!") + markup.add(item1) + markup.add(item2) + bot.send_message(m.chat.id, + '"Рандомный продукт" - для получения карточки товара\n "Повтори!" - для повторения сообщений.', + reply_markup=markup) + + +@bot.message_handler(content_types=["text"]) +def handle_text(message): + if (message.text.strip() == 'Рандомный продукт'): + i = random.choice(array) + ans = f'Название: {i[1]}\nЦена: {i[2]}\nРейтинг: {i[3]}\n' + bot.send_message(message.chat.id, ans) + bot.send_photo(message.chat.id, open(i[4], 'rb')) + elif (message.text.strip() == 'Повтори!'): + bot.send_message(message.chat.id, 'Ввод: ' + message.text) + + +bot.polling(none_stop=True, interval=0) diff --git a/Задания/task1/Uskova/DataBaze.py b/Задания/task1/Uskova/DataBaze.py index bdd3ded..87851d1 100644 --- a/Задания/task1/Uskova/DataBaze.py +++ b/Задания/task1/Uskova/DataBaze.py @@ -4,36 +4,32 @@ from selenium.webdriver.chrome.service import Service import psycopg2 import wget +browser = webdriver.Chrome(service=Service('C:\\Users\\Yekaterina\\Downloads\\chromedriver_win32.zip\\chromedriver.exe')) +browser.get('https://msk.sushi-market.com/menu/rolly') +soup = BeautifulSoup(browser.page_source, "lxml") + +Name = soup.find_all(attrs={"class": "goodsBlockName device-show"}) +Info = soup.find_all(attrs={"class": "goodsBlockWeight"}) +Des = soup.find_all(attrs={"class": "cardsList_text"}) +Price = soup.find_all(attrs={"class": "product__price updated"}) +Image = soup.find_all(attrs={"class": "cardsList_img add-to-cart__img"}) + connection = psycopg2.connect(host='localhost', dbname='dbdata', user='postgres', password='Q1w2e3r4') cursor = connection.cursor() - -crtable = """ create table Notebooks - (id serial primary key, name varchar(500), description varchar(500), code varchar(200), price varchar(100), - picture varchar(500)) """ - -cursor.execute(crtable) +create_q = '''CREATE TABLE F0ood (ID serial primary key, Name varchar(5000), Info varchar(5000), Des varchar(10000), Price varchar(600), src varchar(1000))''' +cursor.execute(create_q) connection.commit() -s = Service('C:\\Users\\Yekaterina\\Downloads\\chromedriver_win32\\chromedriver.exe') -browser = webdriver.Chrome(service=s) -browser.get('https://www.citilink.ru/catalog/noutbuki/') -html_text = browser.page_source -soup = BeautifulSoup(html_text, 'lxml') +for j in range(25): + url = Image[j].find('img').attrs['src'] + tempf = f"img\\food{j}.jpg" + wget.download(url, tempf) + insert_query = f'''INSERT into public.F0ood(Name, Info, Des, Price, src) values ('{Name[j].text}','{Info[j].text}','{Des[j].text}', '{Price[j].text}', '{tempf}') ''' + cursor.execute(insert_query) +connection.commit() -name = soup.find_all('div', class_='app-catalog-1tp0ino e1an64qs0') -description = soup.find_all('div', class_='app-catalog-1o4umte eevw8x70') -code = soup.find_all('div', class_= 'app-catalog-0 e1dsj6g20') -price = soup.find_all('div', class_= 'app-catalog-0 e1dsj6g20') -picture = soup.find_all('div', class_='app-catalog-0 e1jarwcz0') - -for i in range(len(name)): - url = picture[i].find('img').attrs['src'] - file = f"C:\\Users\\Yekaterina\\Desktop\\baza\\pic{i}.JPG" - wget.download(url, file) - ins_qwery = f"""insert into public.Notebooks(name, description, code, price, picture) - values ('{name[i].text}', '{description[i].text}', '{code[i].text}', '{price[i].text}','{file}')""" - cursor.execute(ins_qwery) - connection.commit() +cursor.execute("SELECT * from F0ood") +print(cursor.fetchall()) cursor.close() connection.close() diff --git a/Задания/task1/Uskova/bott.py b/Задания/task1/Uskova/bott.py index 47436e0..4aa410c 100644 --- a/Задания/task1/Uskova/bott.py +++ b/Задания/task1/Uskova/bott.py @@ -1,36 +1,43 @@ import telebot import psycopg2 -import config from telebot import types import random -import tableCreator -connection = psycopg2.connect(host='localhost', dbname='parc', user='postgres', password='Q1w2e3r4') +connection = psycopg2.connect(host='localhost', dbname='dbdata', user='postgres', password='Q1w2e3r4') cursor = connection.cursor() +try: + sel_query = """SELECT * FROM public.f0ood""" + cursor.execute(sel_query) +except psycopg2.errors.UndefinedTable: + connection.rollback() + import problems + sel_query = """SELECT * FROM public.f0ood""" + cursor.execute(sel_query) -ins_query = """SELECT * FROM public.Notebooks""" -cursor.execute(ins_query) array = list(cursor.fetchall()) +bot = telebot.TeleBot('6280771915:AAG2rcsqHZbUjeaOD-llwR-UU-LabMprKBo') -bot = telebot.TeleBot('6205726630:AAF4zfV_P2b0f7bClm__sWuRmoZ1XpiC_xo') @bot.message_handler(commands=["start"]) - def start(m, res=False): - markup=types.ReplyKeyboardMarkup(resize_keyboard=True) - item1=types.KeyboardButton("Выбери ноутбук") - item2=types.KeyboardButton("Еще!") - markup.add(item1) - markup.add(item2) - bot.send_message(m.chat.id, 'Нажми: \nВыбери ноутбук' - ' для просмотра товара\nЕще! ' - '— для повтора', reply_markup=markup) + markup = types.ReplyKeyboardMarkup(resize_keyboard=True) + item1 = types.KeyboardButton("Роллы") + item2 = types.KeyboardButton("Хочу еще!") + markup.add(item1) + markup.add(item2) + bot.send_message(m.chat.id, + '"Роллы" - получите случайную порцию роллов\n' + ' "Хочу еще!" - вдруг вы не наелись', reply_markup=markup) + +i = random.choice(array) @bot.message_handler(content_types=["text"]) def handle_text(message): - if message.text.strip() == 'Выбери ноутбук' : - q = random.choice(array) - answer = f'Название: {q[1]}\nОписание: {q[2]}\nКод: {q[3]}\nЦена: {q[4]}\n' - bot.send_message(message.chat.id, answer) - bot.send_picture(message.chat.id, open(q[5], 'rb')) - elif message.text.strip() == 'Еще!': - bot.send_message(message.chat.id, 'Ввод: '+ message.text) + global i + if (message.text.strip() == 'Роллы'): + i = random.choice(array) + ans = f'Название: {i[1]}\nГраммы: {i[2]}\nОписание: {i[3]}\nЦена за 4 штуки: {i[4]}\n' + bot.send_message(message.chat.id, ans) + bot.send_photo(message.chat.id, open(i[5], 'rb')) + elif (message.text.strip() == 'Хочу еще!'): + bot.send_message(message.chat.id, 'Ввод: ' + message.text) + bot.polling(none_stop=True, interval=0) diff --git a/Задания/task1/Uskova/parcing.py b/Задания/task1/Uskova/parcing.py index 17aeb52..5c406ad 100644 --- a/Задания/task1/Uskova/parcing.py +++ b/Задания/task1/Uskova/parcing.py @@ -8,7 +8,9 @@ browser = webdriver.Chrome(service=s) browser.get('https://www.citilink.ru/catalog/noutbuki/') html_text = browser.page_source soup = BeautifulSoup(html_text, 'lxml') + + name=soup.find_all('div', class_='app-catalog-1tp0ino e1an64qs0') -print (name[0].text) +print (name[1].text) description=soup.find_all('div', class_='app-catalog-1o4umte eevw8x70') -print (description[0].text) +print (description[1].text) diff --git a/Задания/task1/Yaroshevskiy/oop.py b/Задания/task1/Yaroshevskiy/oop.py new file mode 100644 index 0000000..aac44f0 --- /dev/null +++ b/Задания/task1/Yaroshevskiy/oop.py @@ -0,0 +1,37 @@ +from time import time, sleep +from random import random + + +class Car: + def __init__(self, model: str = "Aston Martin", + color: str = "Black", + volume: int = 30, + consp: int = 1): + self.model = model + self.color = color + self.all_volume = volume + self.volume = volume + self.consumption = consp + + def start(self) -> int: + self.start_time = int(time()) + return self.volume // self.consumption + + def stop(self) -> int: + self.volume -= self.consumption * (int(time()) - self.start_time) + return self.volume + + def show_info(self) -> None: + print( + f"model: {self.model}; color: {self.color}; all volume: {self.all_volume}; volume left: {self.volume}") + + +car = Car(volume=10) + +time_sleep = int(car.start() * random()) +print(f"time for working: {time_sleep} seconds") + +sleep(time_sleep) + +car.stop() +car.show_info() diff --git a/Задания/task1/Yaroshevskiy/test_site/__pycache__/config.cpython-310.pyc b/Задания/task1/Yaroshevskiy/test_site/__pycache__/config.cpython-310.pyc new file mode 100644 index 0000000..ee62378 Binary files /dev/null and b/Задания/task1/Yaroshevskiy/test_site/__pycache__/config.cpython-310.pyc differ diff --git a/Задания/task1/Yaroshevskiy/test_site/__pycache__/db_get_data.cpython-310.pyc b/Задания/task1/Yaroshevskiy/test_site/__pycache__/db_get_data.cpython-310.pyc new file mode 100644 index 0000000..34bd719 Binary files /dev/null and b/Задания/task1/Yaroshevskiy/test_site/__pycache__/db_get_data.cpython-310.pyc differ diff --git a/Задания/task1/Yaroshevskiy/test_site/config.py b/Задания/task1/Yaroshevskiy/test_site/config.py new file mode 100644 index 0000000..22b3d2f --- /dev/null +++ b/Задания/task1/Yaroshevskiy/test_site/config.py @@ -0,0 +1,5 @@ +# i know i pushed the config file, but i literally don't care +# there is no useful info +token = "6273436128:AAGMHvICdBLgscqF-XCIO5Nah00q-QA8fcE" +db_name = "db_for_parse" +user = "perfecto" diff --git a/Задания/task1/Yaroshevskiy/test_site/db.sqlite3 b/Задания/task1/Yaroshevskiy/test_site/db.sqlite3 new file mode 100644 index 0000000..a34fefc Binary files /dev/null and b/Задания/task1/Yaroshevskiy/test_site/db.sqlite3 differ diff --git a/Задания/task1/Yaroshevskiy/test_site/db_get_data.py b/Задания/task1/Yaroshevskiy/test_site/db_get_data.py new file mode 100644 index 0000000..acec30b --- /dev/null +++ b/Задания/task1/Yaroshevskiy/test_site/db_get_data.py @@ -0,0 +1,10 @@ +import psycopg2 as ps +import config + + +def exec_query(query: str) -> list: + with ps.connect(dbname=config.db_name, user=config.user) as conn: + with conn.cursor() as cur: + cur.execute(query) + res = cur.fetchall() + return res diff --git a/Задания/task1/Yaroshevskiy/test_site/manage.py b/Задания/task1/Yaroshevskiy/test_site/manage.py new file mode 100755 index 0000000..cceae78 --- /dev/null +++ b/Задания/task1/Yaroshevskiy/test_site/manage.py @@ -0,0 +1,22 @@ +#!/usr/bin/env python +"""Django's command-line utility for administrative tasks.""" +import os +import sys + + +def main(): + """Run administrative tasks.""" + os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'test_site.settings') + try: + from django.core.management import execute_from_command_line + except ImportError as exc: + raise ImportError( + "Couldn't import Django. Are you sure it's installed and " + "available on your PYTHONPATH environment variable? Did you " + "forget to activate a virtual environment?" + ) from exc + execute_from_command_line(sys.argv) + + +if __name__ == '__main__': + main() diff --git a/Задания/task1/Yaroshevskiy/test_site/polls/__init__.py b/Задания/task1/Yaroshevskiy/test_site/polls/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/Задания/task1/Yaroshevskiy/test_site/polls/__pycache__/__init__.cpython-310.pyc b/Задания/task1/Yaroshevskiy/test_site/polls/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000..19f6e7d Binary files /dev/null and b/Задания/task1/Yaroshevskiy/test_site/polls/__pycache__/__init__.cpython-310.pyc differ diff --git a/Задания/task1/Yaroshevskiy/test_site/polls/__pycache__/__init__.cpython-311.pyc b/Задания/task1/Yaroshevskiy/test_site/polls/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000..a743e8d Binary files /dev/null and b/Задания/task1/Yaroshevskiy/test_site/polls/__pycache__/__init__.cpython-311.pyc differ diff --git a/Задания/task1/Yaroshevskiy/test_site/polls/__pycache__/admin.cpython-310.pyc b/Задания/task1/Yaroshevskiy/test_site/polls/__pycache__/admin.cpython-310.pyc new file mode 100644 index 0000000..6e27c1a Binary files /dev/null and b/Задания/task1/Yaroshevskiy/test_site/polls/__pycache__/admin.cpython-310.pyc differ diff --git a/Задания/task1/Yaroshevskiy/test_site/polls/__pycache__/admin.cpython-311.pyc b/Задания/task1/Yaroshevskiy/test_site/polls/__pycache__/admin.cpython-311.pyc new file mode 100644 index 0000000..0bbb505 Binary files /dev/null and b/Задания/task1/Yaroshevskiy/test_site/polls/__pycache__/admin.cpython-311.pyc differ diff --git a/Задания/task1/Yaroshevskiy/test_site/polls/__pycache__/apps.cpython-310.pyc b/Задания/task1/Yaroshevskiy/test_site/polls/__pycache__/apps.cpython-310.pyc new file mode 100644 index 0000000..f6a4f8c Binary files /dev/null and b/Задания/task1/Yaroshevskiy/test_site/polls/__pycache__/apps.cpython-310.pyc differ diff --git a/Задания/task1/Yaroshevskiy/test_site/polls/__pycache__/apps.cpython-311.pyc b/Задания/task1/Yaroshevskiy/test_site/polls/__pycache__/apps.cpython-311.pyc new file mode 100644 index 0000000..c0d1d68 Binary files /dev/null and b/Задания/task1/Yaroshevskiy/test_site/polls/__pycache__/apps.cpython-311.pyc differ diff --git a/Задания/task1/Yaroshevskiy/test_site/polls/__pycache__/forms.cpython-310.pyc b/Задания/task1/Yaroshevskiy/test_site/polls/__pycache__/forms.cpython-310.pyc new file mode 100644 index 0000000..4a8ab72 Binary files /dev/null and b/Задания/task1/Yaroshevskiy/test_site/polls/__pycache__/forms.cpython-310.pyc differ diff --git a/Задания/task1/Yaroshevskiy/test_site/polls/__pycache__/models.cpython-310.pyc b/Задания/task1/Yaroshevskiy/test_site/polls/__pycache__/models.cpython-310.pyc new file mode 100644 index 0000000..eeb1b32 Binary files /dev/null and b/Задания/task1/Yaroshevskiy/test_site/polls/__pycache__/models.cpython-310.pyc differ diff --git a/Задания/task1/Yaroshevskiy/test_site/polls/__pycache__/models.cpython-311.pyc b/Задания/task1/Yaroshevskiy/test_site/polls/__pycache__/models.cpython-311.pyc new file mode 100644 index 0000000..37c1c2f Binary files /dev/null and b/Задания/task1/Yaroshevskiy/test_site/polls/__pycache__/models.cpython-311.pyc differ diff --git a/Задания/task1/Yaroshevskiy/test_site/polls/__pycache__/urls.cpython-310.pyc b/Задания/task1/Yaroshevskiy/test_site/polls/__pycache__/urls.cpython-310.pyc new file mode 100644 index 0000000..2fb33ab Binary files /dev/null and b/Задания/task1/Yaroshevskiy/test_site/polls/__pycache__/urls.cpython-310.pyc differ diff --git a/Задания/task1/Yaroshevskiy/test_site/polls/__pycache__/urls.cpython-311.pyc b/Задания/task1/Yaroshevskiy/test_site/polls/__pycache__/urls.cpython-311.pyc new file mode 100644 index 0000000..9f5cb9e Binary files /dev/null and b/Задания/task1/Yaroshevskiy/test_site/polls/__pycache__/urls.cpython-311.pyc differ diff --git a/Задания/task1/Yaroshevskiy/test_site/polls/__pycache__/views.cpython-310.pyc b/Задания/task1/Yaroshevskiy/test_site/polls/__pycache__/views.cpython-310.pyc new file mode 100644 index 0000000..8d334b6 Binary files /dev/null and b/Задания/task1/Yaroshevskiy/test_site/polls/__pycache__/views.cpython-310.pyc differ diff --git a/Задания/task1/Yaroshevskiy/test_site/polls/__pycache__/views.cpython-311.pyc b/Задания/task1/Yaroshevskiy/test_site/polls/__pycache__/views.cpython-311.pyc new file mode 100644 index 0000000..b8a8c17 Binary files /dev/null and b/Задания/task1/Yaroshevskiy/test_site/polls/__pycache__/views.cpython-311.pyc differ diff --git a/Задания/task1/Yaroshevskiy/test_site/polls/admin.py b/Задания/task1/Yaroshevskiy/test_site/polls/admin.py new file mode 100644 index 0000000..8c38f3f --- /dev/null +++ b/Задания/task1/Yaroshevskiy/test_site/polls/admin.py @@ -0,0 +1,3 @@ +from django.contrib import admin + +# Register your models here. diff --git a/Задания/task1/Yaroshevskiy/test_site/polls/apps.py b/Задания/task1/Yaroshevskiy/test_site/polls/apps.py new file mode 100644 index 0000000..5a5f94c --- /dev/null +++ b/Задания/task1/Yaroshevskiy/test_site/polls/apps.py @@ -0,0 +1,6 @@ +from django.apps import AppConfig + + +class PollsConfig(AppConfig): + default_auto_field = 'django.db.models.BigAutoField' + name = 'polls' diff --git a/Задания/task1/Yaroshevskiy/test_site/polls/forms.py b/Задания/task1/Yaroshevskiy/test_site/polls/forms.py new file mode 100644 index 0000000..0653d74 --- /dev/null +++ b/Задания/task1/Yaroshevskiy/test_site/polls/forms.py @@ -0,0 +1,5 @@ +from django import forms + + +class TestForm(forms.Form): + test_data = forms.CharField(label="test data", max_length=128) diff --git a/Задания/task1/Yaroshevskiy/test_site/polls/migrations/0001_initial.py b/Задания/task1/Yaroshevskiy/test_site/polls/migrations/0001_initial.py new file mode 100644 index 0000000..a51a5aa --- /dev/null +++ b/Задания/task1/Yaroshevskiy/test_site/polls/migrations/0001_initial.py @@ -0,0 +1,32 @@ +# Generated by Django 4.2.1 on 2023-05-04 06:53 + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ] + + operations = [ + migrations.CreateModel( + name='Question', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('question_text', models.CharField(max_length=256)), + ('pub_date', models.DateTimeField(verbose_name='date published')), + ], + ), + migrations.CreateModel( + name='Choice', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('choice_text', models.CharField(max_length=256)), + ('votes', models.IntegerField(default=0)), + ('question', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='polls.question')), + ], + ), + ] diff --git a/Задания/task1/Yaroshevskiy/test_site/polls/migrations/__init__.py b/Задания/task1/Yaroshevskiy/test_site/polls/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/Задания/task1/Yaroshevskiy/test_site/polls/migrations/__pycache__/0001_initial.cpython-310.pyc b/Задания/task1/Yaroshevskiy/test_site/polls/migrations/__pycache__/0001_initial.cpython-310.pyc new file mode 100644 index 0000000..89fb16c Binary files /dev/null and b/Задания/task1/Yaroshevskiy/test_site/polls/migrations/__pycache__/0001_initial.cpython-310.pyc differ diff --git a/Задания/task1/Yaroshevskiy/test_site/polls/migrations/__pycache__/0001_initial.cpython-311.pyc b/Задания/task1/Yaroshevskiy/test_site/polls/migrations/__pycache__/0001_initial.cpython-311.pyc new file mode 100644 index 0000000..7c6e21e Binary files /dev/null and b/Задания/task1/Yaroshevskiy/test_site/polls/migrations/__pycache__/0001_initial.cpython-311.pyc differ diff --git a/Задания/task1/Yaroshevskiy/test_site/polls/migrations/__pycache__/__init__.cpython-310.pyc b/Задания/task1/Yaroshevskiy/test_site/polls/migrations/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000..ca86b94 Binary files /dev/null and b/Задания/task1/Yaroshevskiy/test_site/polls/migrations/__pycache__/__init__.cpython-310.pyc differ diff --git a/Задания/task1/Yaroshevskiy/test_site/polls/migrations/__pycache__/__init__.cpython-311.pyc b/Задания/task1/Yaroshevskiy/test_site/polls/migrations/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000..79d0124 Binary files /dev/null and b/Задания/task1/Yaroshevskiy/test_site/polls/migrations/__pycache__/__init__.cpython-311.pyc differ diff --git a/Задания/task1/Yaroshevskiy/test_site/polls/models.py b/Задания/task1/Yaroshevskiy/test_site/polls/models.py new file mode 100644 index 0000000..89cf214 --- /dev/null +++ b/Задания/task1/Yaroshevskiy/test_site/polls/models.py @@ -0,0 +1,12 @@ +from django.db import models + + +class Question(models.Model): + question_text = models.CharField(max_length=256) + pub_date = models.DateTimeField("date published") + + +class Choice(models.Model): + question = models.ForeignKey(Question, on_delete=models.CASCADE) + choice_text = models.CharField(max_length=256) + votes = models.IntegerField(default=0) diff --git a/Задания/task1/Yaroshevskiy/test_site/polls/static/polls/style.css b/Задания/task1/Yaroshevskiy/test_site/polls/static/polls/style.css new file mode 100644 index 0000000..01c2338 --- /dev/null +++ b/Задания/task1/Yaroshevskiy/test_site/polls/static/polls/style.css @@ -0,0 +1,9 @@ +h1 { + color: green; +} +table, tr, th { + width: 50%; + border: 1px solid; + margin-left: auto; + margin-right: auto; +} diff --git a/Задания/task1/Yaroshevskiy/test_site/polls/templates/polls/index.html b/Задания/task1/Yaroshevskiy/test_site/polls/templates/polls/index.html new file mode 100644 index 0000000..dcf7be9 --- /dev/null +++ b/Задания/task1/Yaroshevskiy/test_site/polls/templates/polls/index.html @@ -0,0 +1,21 @@ + + +
+ {% load static %} + +| {{ i }} | +{% widthratio i 1 i %} | +
|---|