-
Автор темы
- #1
Обратите внимание, пользователь заблокирован на форуме. Не рекомендуется проводить сделки.
Исходник маркетплейса
С рабочей авторизацией, бд, баланс, отзывы, роли, продажи, покупки
Ss -
ПЕРЕД ТЕМ КАК ПИСАТЬ /DEL
ЭТО КОД ПОД НАЧАЛО, ЕСЛИ ТЫ НЕ УМЕЕШЬ ПОЧТИ ВСЕ, ТО ЭТО НЕ ДЛЯ ТЕБЯ, В КОДЕ НУЖНО МНОГО ВСЕГО ПРОРАБАТЫВАТЬ
ctrl c + ctrl v
С рабочей авторизацией, бд, баланс, отзывы, роли, продажи, покупки
Ss -
Пожалуйста, авторизуйтесь для просмотра ссылки.
ПЕРЕД ТЕМ КАК ПИСАТЬ /DEL
ЭТО КОД ПОД НАЧАЛО, ЕСЛИ ТЫ НЕ УМЕЕШЬ ПОЧТИ ВСЕ, ТО ЭТО НЕ ДЛЯ ТЕБЯ, В КОДЕ НУЖНО МНОГО ВСЕГО ПРОРАБАТЫВАТЬ
Код:
import os
import sqlite3
from flask import Flask, render_template_string, request, redirect, url_for, session, flash
from werkzeug.security import generate_password_hash, check_password_hash
app = Flask(__name__)
app.secret_key = os.urandom(24)
DATABASE = 'marketplace.db'
def get_db():
conn = sqlite3.connect(DATABASE)
conn.row_factory = sqlite3.Row
return conn
def init_db():
with app.app_context():
db = get_db()
try:
db.execute('ALTER TABLE users ADD COLUMN role TEXT DEFAULT "user"')
except sqlite3.OperationalError:
pass
db.execute('''CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL UNIQUE,
password TEXT NOT NULL,
role TEXT DEFAULT "user",
balance INTEGER DEFAULT 0)''')
db.execute('''CREATE TABLE IF NOT EXISTS products (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
description TEXT NOT NULL,
price INTEGER NOT NULL,
game TEXT NOT NULL,
seller_id INTEGER,
FOREIGN KEY(seller_id) REFERENCES users(id))''')
db.execute('''CREATE TABLE IF NOT EXISTS reviews (
id INTEGER PRIMARY KEY AUTOINCREMENT,
product_id INTEGER,
user_id INTEGER,
rating INTEGER,
comment TEXT,
FOREIGN KEY(product_id) REFERENCES products(id),
FOREIGN KEY(user_id) REFERENCES users(id))''')
db.execute('''CREATE TABLE IF NOT EXISTS chats (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user1_id INTEGER,
user2_id INTEGER,
message TEXT,
FOREIGN KEY(user1_id) REFERENCES users(id),
FOREIGN KEY(user2_id) REFERENCES users(id))''')
db.execute('''CREATE TABLE IF NOT EXISTS purchases (
id INTEGER PRIMARY KEY AUTOINCREMENT,
product_id INTEGER,
buyer_id INTEGER,
FOREIGN KEY(product_id) REFERENCES products(id),
FOREIGN KEY(buyer_id) REFERENCES users(id))''')
insert_test_data()
def insert_test_data():
db = get_db()
db.execute('INSERT OR IGNORE INTO users (username, password, role, balance) VALUES (?, ?, ?, ?)',
('ivan', generate_password_hash('1234'), 'admin', 500))
db.execute('INSERT OR IGNORE INTO users (username, password, role, balance) VALUES (?, ?, ?, ?)',
('alex', generate_password_hash('1234'), 'user', 0))
db.execute('INSERT OR IGNORE INTO users (username, password, role, balance) VALUES (?, ?, ?, ?)',
('maria', generate_password_hash('1234'), 'moderator', 100))
db.execute('INSERT OR IGNORE INTO products (title, description, price, game, seller_id) VALUES (?, ?, ?, ?, ?)',
('Minecraft Account', 'Аккаунт Minecraft, полный доступ', 100, 'Minecraft', 1))
db.execute('INSERT OR IGNORE INTO products (title, description, price, game, seller_id) VALUES (?, ?, ?, ?, ?)',
('CS2 Skins', 'Скины для CS2', 200, 'CS2', 2))
db.commit()
@app.route('/')
def index():
db = get_db()
search_query = request.args.get('search', '')
if search_query:
products = db.execute('SELECT * FROM products WHERE title LIKE ?', ('%' + search_query + '%',)).fetchall()
else:
products = db.execute('SELECT * FROM products').fetchall()
return render_template_string('''
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Маркетплейс</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background-color: #121212;
color: #fff;
}
.header {
background-color: #333;
padding: 20px;
display: flex;
justify-content: space-between;
align-items: center;
}
.header h1 {
color: #fff;
}
.menu a {
color: #fff;
text-decoration: none;
padding: 10px;
border-radius: 5px;
transition: background-color 0.3s;
}
.menu a:hover {
background-color: #444;
}
h2 {
color: #fff;
text-align: center;
}
.search-form input {
padding: 8px;
margin: 10px;
border-radius: 5px;
border: none;
}
.products-list {
display: flex;
flex-wrap: wrap;
justify-content: space-around;
}
.product-item {
background-color: #333;
padding: 20px;
margin: 10px;
width: 250px;
border-radius: 10px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
transition: transform 0.3s;
}
.product-item:hover {
transform: scale(1.05);
}
.product-item h3 {
color: #fff;
}
.product-item p {
color: #ccc;
}
.btn {
display: block;
background-color: #555;
color: white;
padding: 10px;
border-radius: 5px;
text-align: center;
margin-top: 10px;
text-decoration: none;
}
.btn:hover {
background-color: #666;
}
.form-container {
max-width: 500px;
margin: 50px auto;
padding: 20px;
background-color: #333;
border-radius: 10px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}
.form-container input {
width: 100%;
padding: 10px;
margin: 10px 0;
background-color: #444;
border: none;
border-radius: 5px;
color: #fff;
}
.form-container button {
width: 100%;
padding: 10px;
background-color: #555;
border: none;
border-radius: 5px;
color: #fff;
cursor: pointer;
}
.form-container button:hover {
background-color: #666;
}
.form-container h2 {
text-align: center;
color: #fff;
}
</style>
</head>
<body>
<div class="header">
<h1>Маркетплейс</h1>
<div class="menu">
{% if session.get('user_id') %}
<a href="{{ url_for('profile') }}">Мой профиль</a>
<a href="{{ url_for('logout') }}">Выйти</a>
{% else %}
<a href="{{ url_for('login') }}">Войти</a>
<a href="{{ url_for('register') }}">Зарегистрироваться</a>
{% endif %}
</div>
</div>
<h2>Добро пожаловать в наш маркетплейс!</h2>
<form class="search-form" method="GET">
<input type="text" name="search" placeholder="Поиск товаров..." value="{{ request.args.get('search', '') }}">
<button type="submit">Искать</button>
</form>
<div class="products-list">
{% for product in products %}
<div class="product-item">
<h3>{{ product['title'] }}</h3>
<p>{{ product['description'] }}</p>
<p>Цена: {{ product['price'] }} руб.</p>
<a href="{{ url_for('product_page', product_id=product['id']) }}" class="btn">Подробнее</a>
</div>
{% endfor %}
</div>
</body>
</html>
''', products=products)
@app.route('/product/<int:product_id>')
def product_page(product_id):
db = get_db()
product = db.execute('SELECT * FROM products WHERE id = ?', (product_id,)).fetchone()
if not product:
flash('Товар не найден')
return redirect(url_for('index'))
return render_template_string('''
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{ product['title'] }}</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background-color: #121212;
color: #fff;
}
.header {
background-color: #333;
padding: 20px;
display: flex;
justify-content: space-between;
align-items: center;
}
.header h1 {
color: #fff;
}
.product-detail {
margin: 50px auto;
padding: 20px;
background-color: #333;
border-radius: 10px;
width: 80%;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}
.product-detail h2 {
color: #fff;
}
.product-detail p {
color: #ccc;
}
.btn {
display: block;
background-color: #555;
color: white;
padding: 10px;
border-radius: 5px;
text-align: center;
margin-top: 10px;
text-decoration: none;
}
.btn:hover {
background-color: #666;
}
</style>
</head>
<body>
<div class="header">
<h1>Маркетплейс</h1>
<div class="menu">
{% if session.get('user_id') %}
<a href="{{ url_for('profile') }}">Мой профиль</a>
<a href="{{ url_for('logout') }}">Выйти</a>
{% else %}
<a href="{{ url_for('login') }}">Войти</a>
<a href="{{ url_for('register') }}">Зарегистрироваться</a>
{% endif %}
</div>
</div>
<div class="product-detail">
<h2>{{ product['title'] }}</h2>
<p>{{ product['description'] }}</p>
<p>Цена: {{ product['price'] }} руб.</p>
<a href="#" class="btn">Купить</a>
</div>
</body>
</html>
''', product=product)
@app.route('/profile')
def profile():
if 'user_id' not in session:
flash('Пожалуйста, войдите в систему.')
return redirect(url_for('login'))
db = get_db()
user_id = session['user_id']
user = db.execute('SELECT * FROM users WHERE id = ?', (user_id,)).fetchone()
purchases = db.execute('SELECT * FROM purchases WHERE buyer_id = ?', (user_id,)).fetchall()
sales = db.execute('SELECT * FROM products WHERE seller_id = ?', (user_id,)).fetchall()
return render_template_string('''
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Мой профиль</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background-color: #121212;
color: #fff;
}
.header {
background-color: #333;
padding: 20px;
display: flex;
justify-content: space-between;
align-items: center;
}
.header h1 {
color: #fff;
}
.profile-info {
padding: 20px;
background-color: #333;
border-radius: 10px;
margin: 20px;
width: 80%;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}
.profile-info h2 {
color: #fff;
}
.profile-info p {
color: #ccc;
}
.profile-info ul {
list-style-type: none;
padding: 0;
}
.profile-info li {
margin: 10px 0;
}
.profile-info .btn {
background-color: #555;
padding: 10px;
border-radius: 5px;
text-decoration: none;
color: #fff;
}
.profile-info .btn:hover {
background-color: #666;
}
</style>
</head>
<body>
<div class="header">
<h1>Маркетплейс</h1>
<div class="menu">
<a href="{{ url_for('index') }}">Главная</a>
<a href="{{ url_for('logout') }}">Выйти</a>
</div>
</div>
<div class="profile-info">
<h2>Профиль пользователя</h2>
<p>Имя пользователя: {{ user['username'] }}</p>
<p>Баланс: {{ user['balance'] }} руб.</p>
<p>Роль: {{ user['role'] }}</p>
<h3>Мои покупки:</h3>
<ul>
{% for purchase in purchases %}
<li>Товар: {{ purchase['product_id'] }}</li>
{% endfor %}
</ul>
<h3>Мои продажи:</h3>
<ul>
{% for sale in sales %}
<li>Товар: {{ sale['title'] }}</li>
{% endfor %}
</ul>
<a href="{{ url_for('index') }}" class="btn">На главную</a>
</div>
</body>
</html>
''', user=user, purchases=purchases, sales=sales)
@app.route('/register', methods=['GET', 'POST'])
def register():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
password_hash = generate_password_hash(password)
db = get_db()
db.execute('INSERT INTO users (username, password) VALUES (?, ?)', (username, password_hash))
db.commit()
flash('Регистрация прошла успешно. Теперь вы можете войти в свой аккаунт.')
return redirect(url_for('login'))
return render_template_string('''
<form method="POST">
<h2>Регистрация</h2>
<input type="text" name="username" placeholder="Имя пользователя" required>
<input type="password" name="password" placeholder="Пароль" required>
<button type="submit">Зарегистрироваться</button>
</form>
''')
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
db = get_db()
user = db.execute('SELECT * FROM users WHERE username = ?', (username,)).fetchone()
if user and check_password_hash(user['password'], password):
session['user_id'] = user['id']
session['username'] = user['username']
flash('Вы успешно вошли в систему!')
return redirect(url_for('index'))
flash('Неверный логин или пароль.')
return render_template_string('''
<form method="POST">
<h2>Вход</h2>
<input type="text" name="username" placeholder="Имя пользователя" required>
<input type="password" name="password" placeholder="Пароль" required>
<button type="submit">Войти</button>
</form>
''')
@app.route('/logout')
def logout():
session.clear()
flash('Вы вышли из системы.')
return redirect(url_for('index'))
if __name__ == '__main__':
init_db()
app.run(debug=True)