Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
93 changes: 93 additions & 0 deletions Shops/skin_shop/app/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
# """5. Напишите программу магазина.
# Покупатели могут покупать какие-то продукты в магазине.

# Возможности покупателя:
# - посмотреть все товары и цены на них
# - выбрать товар
# - посмотреть сумму покупки(сумма цен выбранных товаров)
# Взаимодействие происходит через консоль.

# Товары храните просто в какой-нибудь из коллекций.
# Выбор товара - это ввод пользователем строки названия товара
# """

import json

products = [
("Rogozhka",100),
("Velour",200),
("Vicrovelour",300),
("Shenil",400),
]

order = []

def read_file(filename: str) -> dict:

with open(filename) as file:
data = json.load(file)
return data


# № function 1
def get_all_products() -> list:
data = read_file('Shops\skin_shop\\app\storage.json')
id = 0
result = ''
for product in data.get('products'):
print(product)
id += 1
#result += f'{id}.{product[0]} : {product[1]}$' + "\n"

return result

# № function 2
def add_product(product_id: int) ->str:

order.append(products[product_id - 1])
result = f'Вы выбрали {products[product_id - 1][0]} стоимость {products[product_id - 1][1]}$' + "\n"
return result

# № function 3
def get_sum_price() -> str:
sum = 0
for order_item in order:
sum += order_item[1]
return sum


def managment_func(num_func: int):
result = ""
if num_func == 1:
result = get_all_products()
elif num_func == 2:
product_id = int(input(get_all_products() + 'Введите номер продукта: '))
result = add_product(product_id)
elif num_func == 3:
result = f'Сумма покупки {get_sum_price()}$'
else:
result = 'Введены неверные значения'

return result

def menu():
menu = """
0 - Выход
1 - Посмотреть товары
2 - Добавить в корзину
3 - Посмотреть корзину
""" + "\n" + "Выберите действие: "
return menu


def run() -> None:
choice = ""
while choice != 'Выход':
choice = int(input(menu()))
message = managment_func(choice)
print(message)

run()



Empty file.
6 changes: 6 additions & 0 deletions Shops/skin_shop/youtubePractic/website/article/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from django.contrib import admin
from .models import Article, Comment
admin.site.register(Article)
admin.site.register(Comment)

# Register your models here.
7 changes: 7 additions & 0 deletions Shops/skin_shop/youtubePractic/website/article/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
from django.apps import AppConfig


class ArticleConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'article'
verbose_name = 'blog'
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# Generated by Django 4.0.6 on 2022-08-03 21:12

from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):

initial = True

dependencies = [
]

operations = [
migrations.CreateModel(
name='Article',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('article_title', models.CharField(max_length=200, verbose_name='имя статьи')),
('article_text', models.TextField(verbose_name='текс статьи')),
('pub_date', models.DateTimeField(verbose_name='дата публикации')),
],
),
migrations.CreateModel(
name='comment',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('author_name', models.CharField(max_length=50, verbose_name='автор комментария')),
('comment_text', models.CharField(max_length=200, verbose_name='текс комментария')),
('article', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='article.article')),
],
),
]
Empty file.
25 changes: 25 additions & 0 deletions Shops/skin_shop/youtubePractic/website/article/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import datetime
from django.db import models
from django.utils import timezone

class Article(models.Model):
article_title = models.CharField('имя статьи', max_length = 200)
article_text = models.TextField('текс статьи')
pub_date = models.DateTimeField('дата публикации')


def __str__(self):
return self.article_title

def was_publisher_recently(self):
return self.pub_date >= (timezone.now() - datetime.timedelta(days = 7))


class Comment(models.Model):
article = models.ForeignKey(Article, on_delete = models.CASCADE)
author_name = models.CharField('автор комментария', max_length = 50)
comment_text= models.CharField('текс комментария', max_length = 200)


def __str__(self):
return self.author_name
3 changes: 3 additions & 0 deletions Shops/skin_shop/youtubePractic/website/article/tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.test import TestCase

# Create your tests here.
7 changes: 7 additions & 0 deletions Shops/skin_shop/youtubePractic/website/article/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
from django.urls import path
from .import views


urlpatterns = [
path('', views.index, name = '_index_'),
]
8 changes: 8 additions & 0 deletions Shops/skin_shop/youtubePractic/website/article/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
from django.shortcuts import render

def index(request):
return render(request, 'article/list.html')




22 changes: 22 additions & 0 deletions Shops/skin_shop/youtubePractic/website/manage.py
Original file line number Diff line number Diff line change
@@ -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', 'website.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()
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{% extends 'base.html' %}

{% block title %}Последние статьи{% endblock %}

{% block content %}
Проверка...
{% endblock %}
Empty file.
12 changes: 12 additions & 0 deletions Shops/skin_shop/youtubePractic/website/templates/base.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{% block title %}My site{% endblock %}</title>
</head>
<body>
{% block content %}{% endblock %}


</body>
</html>
Empty file.
16 changes: 16 additions & 0 deletions Shops/skin_shop/youtubePractic/website/website/asgi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"""
ASGI config for website 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.0/howto/deployment/asgi/
"""

import os

from django.core.asgi import get_asgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'website.settings')

application = get_asgi_application()
125 changes: 125 additions & 0 deletions Shops/skin_shop/youtubePractic/website/website/settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
"""
Django settings for website project.

Generated by 'django-admin startproject' using Django 4.0.6.

For more information on this file, see
https://docs.djangoproject.com/en/4.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.0/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.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-i62z$8@#wacsfw4o7*f1a51%ege8*q#7oxln2u#8msp^3t0_q+'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'article',
]

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 = 'website.urls'

TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(PROJECT_ROOT, 'templates')],
'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 = 'website.wsgi.application'


# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}


# Password validation
# https://docs.djangoproject.com/en/4.0/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.0/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.0/howto/static-files/

STATIC_URL = 'static/'

# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
Loading