Skip to content

Commit

Permalink
release of project
Browse files Browse the repository at this point in the history
  • Loading branch information
prizrak3742 committed Sep 28, 2024
1 parent f5918f6 commit 303e83a
Show file tree
Hide file tree
Showing 9 changed files with 216 additions and 2 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ users.json
add_film.log
mysql_test.py

flask_config.py
mysql_config.py
aiogram_config.py
chat.log
Expand Down
2 changes: 1 addition & 1 deletion bot app/aiogram_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
##########################################################################
# REGISTRATION AND INITIALIZATION BOT

logging.basicConfig(filename="log.log", level=logging.INFO) # Setting the level of logs to INFO
logging.basicConfig(level=logging.INFO) # Setting the level of logs to INFO
bot = Bot(token) # Creating bot instance with token
dp = Dispatcher() # Create dispatcher type

Expand Down
Binary file modified mysql/__pycache__/mysql_command.cpython-312.pyc
Binary file not shown.
Binary file modified mysql/__pycache__/mysql_main.cpython-312.pyc
Binary file not shown.
2 changes: 1 addition & 1 deletion mysql/mysql_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ def add_db(code, headline, description, photo):
with conn.cursor() as cur:
cur.execute("INSERT INTO kinopoisk (code, headline, description, photo) VALUES (%s, %s, %s, %s)", (code, headline, description, photo)) # Извлекаем запрос и параметры из кортежа
conn.commit()
return True # Возвращаем True, если все прошло успешно
return True
except Exception as e:
print("Error in connection...")
print(e)
Expand Down
Binary file added web app/__pycache__/flask_config.cpython-312.pyc
Binary file not shown.
Empty file removed web app/app.py
Empty file.
86 changes: 86 additions & 0 deletions web app/flask_main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
from flask import Flask, render_template, request, redirect, url_for, flash, session, abort, g, jsonify
import sys
import requests
from flask_config import SECRET_KEY, API_KEY_OMBDB, DEBUG_STATUS
import base64
sys.path.append('D:/Kinopoisk project')
from mysql.mysql_main import add_db, take_db
from mysql.mysql_command import get_poster_by_code, get_all_codes, get_last_code

# =============================================================================
# Configuration
# =============================================================================

app = Flask(__name__)
app.config.from_object(__name__)
app.secret_key = SECRET_KEY

def get_movie_info_omdb(title, api_key=API_KEY_OMBDB):
url = f"http://www.omdbapi.com/?t={title}&apikey={api_key}"
response = requests.get(url)
if response.status_code == 200:
data = response.json()
if data['Response'] == 'True':
return {
'genre': data.get('Genre').split(",")[0],
'rating': data.get('imdbRating')
}
else:
return f"Movie not found: {data['Error']}"
else:
return f"Error: {response.status_code}"

# def movies():
# list = []
# for i in range(100, take_db(get_last_code(), 0)["code"]+1):
# image_data = take_db(get_poster_by_code(i), 0)["photo"]
# list.append(
# {"code": take_db(get_poster_by_code(i), 0)["code"],
# "headline": take_db(get_poster_by_code(i), 0)["headline"],
# "description": take_db(get_poster_by_code(i), 0)["description"],
# "encoded_image": base64.b64encode(image_data).decode('utf-8'),
# "rating": get_movie_info_omdb(take_db(get_poster_by_code(i), 0)["headline"])["rating"],
# "ganere": get_movie_info_omdb(take_db(get_poster_by_code(i), 0)["headline"])["genre"]}
# )
# return list


# =============================================================================

@app.route('/')
def home():
movies = []
for i in range(100, take_db(get_last_code(), 0)["code"]+1):
image_data = take_db(get_poster_by_code(i), 0)["photo"]
movies.append(
{"code": take_db(get_poster_by_code(i), 0)["code"],
"headline": take_db(get_poster_by_code(i), 0)["headline"],
"description": take_db(get_poster_by_code(i), 0)["description"],
"encoded_image": base64.b64encode(image_data).decode('utf-8'),
}
)

return render_template("index.html", movies=movies)

@app.route('/search', methods=['POST'])
def search():
movies = []
for i in range(100, take_db(get_last_code(), 0)["code"]+1):
image_data = take_db(get_poster_by_code(i), 0)["photo"]
movies.append(
{"code": take_db(get_poster_by_code(i), 0)["code"],
"headline": take_db(get_poster_by_code(i), 0)["headline"],
"description": take_db(get_poster_by_code(i), 0)["description"],
"encoded_image": base64.b64encode(image_data).decode('utf-8'),
}
)
query = request.form.get('query', '').lower()
try:
filtered_movies = [movie for movie in movies if query in str(movie['code']).lower()]
return jsonify({"movies": filtered_movies})
except Exception as e:
print(f"Error: {e}") # Вывод ошибки в консоль
return jsonify({"error": "An error occurred during search."}), 500

if __name__ == "__main__":
app.run(debug=DEBUG_STATUS)
127 changes: 127 additions & 0 deletions web app/templates/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PyCinema - Your Film Library</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<style>
.movie-img {
width: 305px;
height: 250px;
object-fit: cover;
}
</style>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="container-fluid">
<a class="navbar-brand" href="#">PyCinema</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav ms-auto">
<li class="nav-item">
<a class="nav-link" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Search</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Reviews</a>
</li>
</ul>
</div>
</div>
</nav>

<header class="bg-primary text-white text-center py-5">
<div class="container">
<h1>Welcome to PyCinema</h1>
<p>Your ultimate film library and review platform</p>
<form class="row g-3 mt-3" id="searchForm" method="POST">
<div class="col-md-8 offset-md-2">
<input type="text" class="form-control" id="searchQuery" name="query" placeholder="Search for movies by code...">
</div>
<div class="col-md-2 text-md-end">
<button type="submit" class="btn btn-warning">Search</button>
</div>
</form>
</div>
</header>

<main class="container mt-5">
<h2 class="text-center mb-4">Movies</h2>
<div id="movieList" class="row">
<!-- Movie cards will be injected here via JS -->
</div>
</main>

<footer class="bg-dark text-white text-center py-4 mt-5">
<p>&copy; 2024 PyCinema. All rights reserved.</p>
</footer>

<script>
$(document).ready(function() {
// Movies array from the Flask app
const movies = {{ movies | tojson | safe }};

// Function to inject movies into the DOM
function displayMovies(movieList) {
const movieContainer = $('#movieList');
movieContainer.empty(); // Clear existing content
movieList.forEach(movie => {
// Limit headline to 300 characters
let description = movie.description.length > 300 ? movie.description.substring(0, 300) + '...' : movie.description;

const movieCard = `
<div class="col-md-3">
<div class="card mb-4 shadow-sm">
<img src="data:image/jpeg;base64,${movie.encoded_image}" class="card-img-top movie-img" alt="${movie.headline}">
<div class="card-body">
<h5 class="card-title">${movie.headline} (${movie.code})</h5>
<p class="card-text">${description}</p>
<p class="card-text"></p>
<p class="card-text">${movie.ganere} ${movie.rating}</p>
</div>
</div>
</div>`;
movieContainer.append(movieCard);
});
}

// Load movies initially
displayMovies(movies);

// Handle search form submission
$('#searchForm').submit(function(event) {
event.preventDefault();
const query = $('#searchQuery').val().toLowerCase();

// AJAX POST request to Flask
$.ajax({
type: 'POST',
url: '/search',
data: { query: query },
success: function(response) {
console.log('Response:', response); // Выводим ответ в консоль
if (response.movies && response.movies.length > 0) {
displayMovies(response.movies); // Display filtered movies
} else {
$('#movieList').empty(); // Clear existing movies
$('#movieList').append('<p class="text-center">No movies found</p>'); // Message if no movies found
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.log('Error details:', textStatus, errorThrown); // Выводим детали ошибки в консоль
alert('Error occurred while searching');
}
});
});
});
</script>
</body>
</html>

0 comments on commit 303e83a

Please sign in to comment.