Скриншот архива с проектом
Структура проекта
Задание
Написать приложение на Python и Flask - мини-сайт о путешествиях. Дожны использоваться библиотеки: Flask-WTF, Flask-SQLAlchemy.
Функционал программы
- добавление путешествий
- редактирование путешествий
- удаление путешествий
- поиск путешествий
- регистрация
Фрагмент программного кода
from flask import Flask, render_template, redirect, url_for, flash, request from flask_sqlalchemy import SQLAlchemy from flask_wtf import FlaskForm from wtforms import StringField, IntegerField, DateField from wtforms.fields.numeric import FloatField from wtforms.fields.simple import PasswordField from wtforms.validators import DataRequired, EqualTo from datetime import datetime, timezone app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///voyages.db' app.config['SECRET_KEY'] = 'your_secret_key_here' db = SQLAlchemy(app) class Voyage(db.Model): id = db.Column(db.Integer, primary_key=True) departure_point = db.Column(db.String(100), nullable=False) departure_date = db.Column(db.DateTime, nullable=False, default=datetime.now(timezone.utc)) destination_country = db.Column(db.String(100), nullable=False) destination_city = db.Column(db.String(100), nullable=False) arrival_date = db.Column(db.DateTime, nullable=False, default=datetime.now(timezone.utc)) trip_cost = db.Column(db.Float, nullable=False) trip_duration = db.Column(db.Integer, nullable=False) class VoyageForm(FlaskForm): departure_point = StringField('Point de Départ', validators=[DataRequired()]) departure_date = DateField('Date de Départ', validators=[DataRequired()]) destination_country = StringField('Pays de Destination', validators=[DataRequired()]) destination_city = StringField('Ville de Destination', validators=[DataRequired()]) arrival_date = DateField('Date Arrivée', validators=[DataRequired()]) trip_cost = FloatField('Coût du Voyage', validators=[DataRequired()]) trip_duration = IntegerField('Durée du voyage (jours)', validators=[DataRequired()]) class RegistrationForm(FlaskForm): username = StringField('Username', validators=[DataRequired()]) email = StringField('Email', validators=[DataRequired()]) password = PasswordField('Password', validators=[DataRequired()]) confirm_password = PasswordField('Confirm Password', validators=[DataRequired(), EqualTo('password')]) @app.route('/register', methods=['GET', 'POST']) def register(): form = RegistrationForm() if form.validate_on_submit(): flash(f'Account created for {form.username.data}!', 'success') return redirect(url_for('index')) return render_template('register.html', title='Register', form=form) @app.route('/') @app.route('/home') def index(): return render_template("index.html") @app.route('/voyages', methods=['POST', 'GET']) def voyages(): form = VoyageForm() if form.validate_on_submit(): departure_point = form.departure_point.data departure_date = form.departure_date.data destination_country = form.destination_country.data destination_city = form.destination_city.data arrival_date = form.arrival_date.data trip_cost = form.trip_cost.data trip_duration = form.trip_duration.data voyage = Voyage(departure_point=departure_point, departure_date=departure_date, destination_country=destination_country, destination_city=destination_city, arrival_date=arrival_date, trip_cost=trip_cost, trip_duration=trip_duration) db.session.add(voyage) db.session.commit() flash('Voyage ajouté avec succès!', 'success') return redirect(url_for('index')) voyages = Voyage.query.all() return render_template('voyages.html', title='Ajouter un Voyage', form=form, voyages=voyages) @app.route('/voyages/<int:id>') def détails_voyage(id): voyage = Voyage.query.get(id) return render_template("détails_voyage.html", voyage=voyage) @app.route('/voyages/<int:id>/edit', methods=['POST', 'GET']) def edit_voyage(id): voyage = Voyage.query.get(id) form = VoyageForm(obj=voyage) if request.method == 'POST': voyage.departure_point = request.form['departure_point'] voyage.destination_country = request.form['destination_country'] voyage.destination_city = request.form['destination_city'] voyage.departure_date = datetime.strptime(request.form['departure_date'], '%Y-%m-%d') voyage.arrival_date = datetime.strptime(request.form['arrival_date'], '%Y-%m-%d') voyage.trip_cost = request.form['trip_cost'] voyage.trip_duration = request.form['trip_duration'] try: db.session.commit() return redirect(url_for('voyages')) except Exception as e: return f"При изменении путешествия произошла ошибка: {str(e)}" else: return render_template("edit_voyage.html", voyage=voyage, form=form) @app.route('/voyages/<int:id>/delete') def voyage_delete(id): voyage = Voyage.query.get_or_404(id) try: db.session.delete(voyage) db.session.commit() return redirect(url_for('voyages')) except: return "При удалении путешествия произошла ошибка!!!" @app.route('/search', methods=['POST', 'GET']) def search(): if request.method == 'POST': search_term = request.form['search_term'] voyages = Voyage.query.filter(Voyage.destination_country.ilike(f"%{search_term}%")).all() return render_template('search_results.html', voyages=voyages, search_term=search_term) else: return render_template('search_form.html') if __name__ == '__main__': with app.app_context(): db.create_all() app.run(debug=True)
Пояснения по запуску программы
Для эффективной работы с приложением вам потребуется:
- редактор кода VS Code - скачать можно тут - https://code.visualstudio.com/download
- интерпретатор языка Python, скачать можно тут - https://www.python.org/downloads/
- После установки всего выше описанного, настройте VS Code для работы с Python установив необходимые расширения (см. инструкцию - https://youtu.be/j5e5gwZgMH8) .
- Запускаете приложение и пользуетесь. Также вы можете самостоятельно выложить проект на Heroku.
admin