This commit is contained in:
Sklvd
2023-05-12 23:05:02 +03:00
69 changed files with 1041 additions and 79 deletions
@@ -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()
+22
View File
@@ -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)) - для проверки
+70
View File
@@ -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)
@@ -14,15 +14,14 @@ Image = soup.find_all(attrs={"class": "holder-img"})
connection = psycopg2.connect(host='localhost', dbname='dbdata', user='postgres', password='Q1w2e3r4') connection = psycopg2.connect(host='localhost', dbname='dbdata', user='postgres', password='Q1w2e3r4')
cursor = connection.cursor() cursor = connection.cursor()
create_q = '''CREATE TABLE Food create_q = '''CREATE TABLE Food (ID serial primary key, Name varchar(500), Price varchar(60), src varchar(100))'''
(ID serial primary key, Name varchar(500), Price varchar(60), src varchar(100))'''
cursor.execute(create_q) cursor.execute(create_q)
connection.commit() connection.commit()
#https://smartomato.ams3.cdn.digitaloceanspaces.com/uploads/media/photo/769221/dish_large__1.jpg #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'] 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) wget.download(url, tempf)
insert_query = f'''INSERT into public.Food(Name, Price, src) values ('{Name[j].text}', '{Price[j].text}', '{tempf}') ''' insert_query = f'''INSERT into public.Food(Name, Price, src) values ('{Name[j].text}', '{Price[j].text}', '{tempf}') '''
cursor.execute(insert_query) cursor.execute(insert_query)
+28
View File
@@ -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()
+44
View File
@@ -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)
@@ -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)
@@ -5,7 +5,7 @@ from selenium.webdriver.chrome.service import Service
from wget import download from wget import download
import psycopg2 as psyc 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" 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 = webdriver.Chrome()
brow.get(URL) 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"}) 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: with conn.cursor() as cursor:
for i, product in enumerate(penny[1:]): for i, product in enumerate(penny[1:]):
image_link = product.find("img").attrs.get("src") image_link = product.find("img").attrs.get("src")
image_name = product.find("img").attrs.get("alt") image_name = product.find("img").attrs.get("alt")
price = product.find("p", attrs={"class": "price"}).text.strip() 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')""") values ('{image_link}', '{image_name}', '{price}', 'images/{i}.jpg')""")
conn.commit() conn.commit()
@@ -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()
+85
View File
@@ -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)
+10 -7
View File
@@ -49,12 +49,15 @@ for i in range(len(productst)):
u.append(features[10*i+j].text) u.append(features[10*i+j].text)
wget.download(url, filename) wget.download(url, filename)
t = pricest[i].text.replace("\xa0", " ") t = pricest[i].text.replace("\xa0", " ")
insert = f"""INSERT INTO public.laptops( try:
Product, Price, Diagonal, Resolution, CPU, RAM, Graphics_Controller, Volume, src) insert = f"""INSERT INTO public.laptops(
VALUES Product, Price, Diagonal, Resolution, CPU, RAM, Graphics_Controller, Volume, src)
('{productst[i].text.strip()}', '{t.strip()}', '{u[0][:u[0].find("/")]}', '{u[0][u[0].find("/")+1:]}', VALUES
'{u[2]}', '{u[4]+" "+u[5]}', '{u[6]}', '{u[8]}', '{filename}');""" ('{productst[i].text.strip()}', '{t.strip()}', '{u[0][:u[0].find("/")]}', '{u[0][u[0].find("/")+1:]}',
cursor.execute(insert) '{u[2]}', '{u[4]+" "+u[5]}', '{u[6]}', '{u[8]}', '{filename}');"""
connection.commit() cursor.execute(insert)
connection.commit()
except:
connection.rollback()
cursor.close() cursor.close()
connection.close() connection.close()
@@ -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
+32 -15
View File
@@ -1,15 +1,23 @@
import telebot import telebot
import psycopg2 import psycopg2
import config import config
def execute_request(request): bot = telebot.TeleBot(config.bot_token)
connection = psycopg2.connect(host=config.host, dbname=config.dbname, user=config.user, password=config.password)
cursor = connection.cursor() def select(request):
cursor.execute(request) try:
result = cursor.fetchall() connection = psycopg2.connect(host=config.host, dbname=config.dbname, user=config.user,
cursor.close() password=config.password)
connection.close() cursor = connection.cursor()
return result cursor.execute(request)
max_id = int(execute_request("select count(*) from laptops")[0][0]) 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 = telebot.TeleBot(config.bot_token)
@bot.message_handler(commands=["start"]) @bot.message_handler(commands=["start"])
def start(m, res=False): def start(m, res=False):
@@ -26,12 +34,21 @@ def from_bd(message):
bot.send_message(message.chat.id, "ID больше, чем количество товаров. Попробуйте снова:") bot.send_message(message.chat.id, "ID больше, чем количество товаров. Попробуйте снова:")
return return
else: else:
data = execute_request(f"select * from laptops where id = {current_id}")[0][1:-1] try:
names_of_columns = ["Товар", "Цена", "Диагональ", "Разрешение", "Процессор", "Оперативная память", "Графический контроллер", "Объём диска"] data = select(f"select * from laptops where id = {current_id}")[0][1:]
everydata = [] if type(data) == str:
for data_name, column_name in zip(data, names_of_columns): bot.send_message(message.chat.id, "Ошибка на сервере")
everydata.append(column_name.capitalize() + ": " + data_name) return
bot.send_message(message.chat.id, "\n\n".join(everydata)) 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.send_message(message.chat.id, f"Введите следующий ID от 1 до {max_id}:")
bot.polling(none_stop=True, interval=0) bot.polling(none_stop=True, interval=0)
+49
View File
@@ -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()
@@ -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)
+2 -1
View File
@@ -1,8 +1,9 @@
import psycopg2 import psycopg2
import wget import wget
from bs4 import BeautifulSoup from bs4 import BeautifulSoup
from selenium import webdriver from selenium import webdriver
from selenium.webdriver.chrome.service import Service from selenium.webdriver.chrome.service import Service
connection = psycopg2.connect(host='localhost', dbname='dbdata', user='postgres', password='Q1w2e3r4') connection = psycopg2.connect(host='localhost', dbname='dbdata', user='postgres', password='Q1w2e3r4')
cursor = connection.cursor() cursor = connection.cursor()
+38
View File
@@ -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)
+21 -25
View File
@@ -4,36 +4,32 @@ from selenium.webdriver.chrome.service import Service
import psycopg2 import psycopg2
import wget 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') connection = psycopg2.connect(host='localhost', dbname='dbdata', user='postgres', password='Q1w2e3r4')
cursor = connection.cursor() cursor = connection.cursor()
create_q = '''CREATE TABLE F0ood (ID serial primary key, Name varchar(5000), Info varchar(5000), Des varchar(10000), Price varchar(600), src varchar(1000))'''
crtable = """ create table Notebooks cursor.execute(create_q)
(id serial primary key, name varchar(500), description varchar(500), code varchar(200), price varchar(100),
picture varchar(500)) """
cursor.execute(crtable)
connection.commit() connection.commit()
s = Service('C:\\Users\\Yekaterina\\Downloads\\chromedriver_win32\\chromedriver.exe') for j in range(25):
browser = webdriver.Chrome(service=s) url = Image[j].find('img').attrs['src']
browser.get('https://www.citilink.ru/catalog/noutbuki/') tempf = f"img\\food{j}.jpg"
html_text = browser.page_source wget.download(url, tempf)
soup = BeautifulSoup(html_text, 'lxml') 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') cursor.execute("SELECT * from F0ood")
description = soup.find_all('div', class_='app-catalog-1o4umte eevw8x70') print(cursor.fetchall())
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.close() cursor.close()
connection.close() connection.close()
+29 -22
View File
@@ -1,36 +1,43 @@
import telebot import telebot
import psycopg2 import psycopg2
import config
from telebot import types from telebot import types
import random 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() 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()) 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"]) @bot.message_handler(commands=["start"])
def start(m, res=False): def start(m, res=False):
markup=types.ReplyKeyboardMarkup(resize_keyboard=True) markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
item1=types.KeyboardButton("Выбери ноутбук") item1 = types.KeyboardButton("Роллы")
item2=types.KeyboardButton("Еще!") item2 = types.KeyboardButton("Хочу еще!")
markup.add(item1) markup.add(item1)
markup.add(item2) markup.add(item2)
bot.send_message(m.chat.id, 'Нажми: \nВыбери ноутбук' bot.send_message(m.chat.id,
' для просмотра товара\nЕще! ' '"Роллы" - получите случайную порцию роллов\n'
'— для повтора', reply_markup=markup) ' "Хочу еще!" - вдруг вы не наелись', reply_markup=markup)
i = random.choice(array)
@bot.message_handler(content_types=["text"]) @bot.message_handler(content_types=["text"])
def handle_text(message): def handle_text(message):
if message.text.strip() == 'Выбери ноутбук' : global i
q = random.choice(array) if (message.text.strip() == 'Роллы'):
answer = f'Название: {q[1]}\nОписание: {q[2]}\nКод: {q[3]}\nЦена: {q[4]}\n' i = random.choice(array)
bot.send_message(message.chat.id, answer) ans = f'Название: {i[1]}\nГраммы: {i[2]}\nОписание: {i[3]}\nЦена за 4 штуки: {i[4]}\n'
bot.send_picture(message.chat.id, open(q[5], 'rb')) bot.send_message(message.chat.id, ans)
elif message.text.strip() == 'Еще!': bot.send_photo(message.chat.id, open(i[5], 'rb'))
bot.send_message(message.chat.id, 'Ввод: '+ message.text) elif (message.text.strip() == 'Хочу еще!'):
bot.send_message(message.chat.id, 'Ввод: ' + message.text)
bot.polling(none_stop=True, interval=0) bot.polling(none_stop=True, interval=0)
+4 -2
View File
@@ -8,7 +8,9 @@ browser = webdriver.Chrome(service=s)
browser.get('https://www.citilink.ru/catalog/noutbuki/') browser.get('https://www.citilink.ru/catalog/noutbuki/')
html_text = browser.page_source html_text = browser.page_source
soup = BeautifulSoup(html_text, 'lxml') soup = BeautifulSoup(html_text, 'lxml')
name=soup.find_all('div', class_='app-catalog-1tp0ino e1an64qs0') 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') description=soup.find_all('div', class_='app-catalog-1o4umte eevw8x70')
print (description[0].text) print (description[1].text)
+37
View File
@@ -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()
@@ -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"
@@ -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
+22
View File
@@ -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()
@@ -0,0 +1,3 @@
from django.contrib import admin
# Register your models here.
@@ -0,0 +1,6 @@
from django.apps import AppConfig
class PollsConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'polls'
@@ -0,0 +1,5 @@
from django import forms
class TestForm(forms.Form):
test_data = forms.CharField(label="test data", max_length=128)
@@ -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')),
],
),
]
@@ -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)
@@ -0,0 +1,9 @@
h1 {
color: green;
}
table, tr, th {
width: 50%;
border: 1px solid;
margin-left: auto;
margin-right: auto;
}
@@ -0,0 +1,21 @@
<!DOCTYPE html>
<html>
<head>
{% load static %}
<link rel="stylesheet" href="{% static 'polls/style.css' %}">
<title>TEST</title>
</head>
<body>
<h1>{{ text }}</h1>
<table>
{% for i in list %}
<tr>
<th>{{ i }}</th>
<th>{% widthratio i 1 i %}</th>
</tr>
{% endfor %}
</table>
</body>
</html>
@@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.
@@ -0,0 +1,8 @@
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("test", views.test, name="other")
]
@@ -0,0 +1,16 @@
from django.http import HttpResponse
from django.shortcuts import render
# from db_get_data import exec_query
def index(request):
context = {
"text": "test",
"list": range(101)
}
return HttpResponse(render(request, "polls/index.html", context))
def test(req):
return HttpResponse("test")
@@ -0,0 +1,16 @@
"""
ASGI config for test_site project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.2/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'test_site.settings')
application = get_asgi_application()
@@ -0,0 +1,124 @@
"""
Django settings for test_site project.
Generated by 'django-admin startproject' using Django 4.2.1.
For more information on this file, see
https://docs.djangoproject.com/en/4.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.2/ref/settings/
"""
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-wc(+rz#@&jg8t!crsb4rzot^rw+xe4d(w7)4#yvztg6t(zj!u('
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
"polls.apps.PollsConfig",
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'test_site.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'test_site.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/4.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.2/howto/static-files/
STATIC_URL = '/static/'
# Default primary key field type
# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
@@ -0,0 +1,7 @@
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path("", include("polls.urls"))
]
@@ -0,0 +1,16 @@
"""
WSGI config for test_site project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'test_site.settings')
application = get_wsgi_application()