How to create a Python site from scratch?

онлайн тренажер по питону
Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Choosing Python for Web Development

Python is one of the most popular programming languages for building websites. Its advantages make development accessible even to beginner programmers.

Advantages of Python for Creating Websites

Python offers developers many opportunities for efficient web development:

  • Simple and readable syntax that is easy to learn
  • Large active developer community
  • Thousands of ready-made libraries and modules
  • Support for modern frameworks: Flask, Django, FastAPI
  • Easy integration with various databases
  • Versatility for MVP and scalable projects
  • Excellent documentation and training materials

Choosing a Framework for Website Development in Python

The right choice of framework determines the success of your project. Each tool has its own features and applications.

Comparison of Popular Python Frameworks

Flask is suitable for simple and medium projects. It is characterized by minimalism and high flexibility. The framework allows the developer to independently choose the necessary components.

Django is ideal for large websites with many features. Includes built-in modules for administration, authentication, and ORM for working with databases.

FastAPI is optimal for creating APIs and microservices. Provides high performance and automatic documentation generation.

Framework Selection Recommendations

For beginner developers, it is recommended to choose Flask. It will help to understand the basic principles of web development without unnecessary complexity.

Setting up the Development Environment

Before starting development, you need to configure all the required tools and dependencies.

Installing Python and Checking the Version

Make sure you have Python version 3.10 or higher installed. You can check the version with the command:

python --version

Installing the Flask Framework

To install Flask, use the pip package manager:

pip install flask

It is recommended to create a virtual environment to isolate project dependencies:

python -m venv mysite_env
source mysite_env/bin/activate  # for Linux/Mac
mysite_env\Scripts\activate     # for Windows

Creating Your First Web Application in Python

Developing a simple website starts with creating a basic application structure.

Writing a Basic Flask Application

Create a file app.py with a minimal web application:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
    return "Hello, world! Your first Python site is working!"

@app.route('/about')
def about():
    return "About page"

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5000)

Running and Testing the Application

To launch your first site, run the command:

python app.py

After starting, open a web browser and go to http://127.0.0.1:5000/. You will see a message about the successful operation of your first Python site.

Organizing the Structure of a Flask Project

The correct organization of files and folders is critical for project support and development.

Recommended Directory Structure

my_flask_app/
├── app.py
├── config.py
├── static/
│   ├── css/
│   │   └── style.css
│   ├── js/
│   │   └── script.js
│   └── images/
├── templates/
│   ├── base.html
│   ├── index.html
│   └── about.html
├── models/
│   └── database.py
├── routes/
│   └── main.py
└── requirements.txt

Description of Main Directories

  • static/ contains all static files: CSS styles, JavaScript scripts, images, and other media files.
  • templates/ stores HTML templates for displaying site pages.
  • models/ includes files for working with databases and data models.
  • routes/ contains routing logic and request processing.
  • requirements.txt lists all project dependencies for easy installation.

Using HTML Templates

Updated app.py file with template support:

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def home():
    user_data = {
        'title': 'Main page',
        'username': 'Guest',
        'current_year': 2024
    }
    return render_template('index.html', data=user_data)

@app.route('/about')
def about():
    return render_template('about.html')

if __name__ == '__main__':
    app.run(debug=True)

Create a basic template templates/base.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{% block title %}My Python Site{% endblock %}</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
</head>
<body>
    <header>
        <nav>
            <a href="{{ url_for('home') }}">Home</a>
            <a href="{{ url_for('about') }}">About</a>
        </nav>
    </header>
    
    <main>
        {% block content %}{% endblock %}
    </main>
    
    <footer>
        <p>&copy; {{ data.current_year if data else 2024 }} All rights reserved</p>
    </footer>
</body>
</html>

File templates/index.html:

{% extends "base.html" %}

{% block title %}{{ data.title }} - My Site{% endblock %}

{% block content %}
<h2>Welcome to my first Python site!</h2>
<p>Hello, {{ data.username }}!</p>
<p>This site was created using the Flask framework.</p>
{% endblock %}

Styling and Static Files

The appearance of the site plays an important role in the user experience.

Creating CSS Styles

Create a file static/css/style.css:

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    line-height: 1.6;
    color: #333;
    background-color: #f4f4f4;
}

header {
    background-color: #2c3e50;
    padding: 1rem 0;
}

nav a {
    color: white;
    text-decoration: none;
    margin: 0 15px;
    padding: 10px 15px;
    border-radius: 5px;
    transition: background-color 0.3s;
}

nav a:hover {
    background-color: #34495e;
}

main {
    max-width: 1200px;
    margin: 2rem auto;
    padding: 0 20px;
    background-color: white;
    border-radius: 10px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    padding: 2rem;
}

h2 {
    color: #2c3e50;
    margin-bottom: 1rem;
}

footer {
    text-align: center;
    padding: 1rem;
    background-color: #34495e;
    color: white;
    margin-top: 2rem;
}

Connecting JavaScript Files

Create a file static/js/script.js for interactivity:

document.addEventListener('DOMContentLoaded', function() {
    console.log('Python site loaded successfully!');
    
    // Animation of content appearance
    const main = document.querySelector('main');
    main.style.opacity = '0';
    main.style.transform = 'translateY(20px)';
    
    setTimeout(() => {
        main.style.transition = 'all 0.5s ease';
        main.style.opacity = '1';
        main.style.transform = 'translateY(0)';
    }, 100);
});

Working with Forms and User Input

Site interactivity is achieved through processing user data.

Creating a Feedback Form

Update app.py to handle forms:

from flask import Flask, render_template, request, flash, redirect, url_for

app = Flask(__name__)
app.secret_key = 'your_secret_key_here'

@app.route('/')
def home():
    return render_template('index.html')

@app.route('/contact', methods=['GET', 'POST'])
def contact():
    if request.method == 'POST':
        name = request.form.get('name')
        email = request.form.get('email')
        message = request.form.get('message')
        
        # Data validation
        if not name or not email or not message:
            flash('Please fill in all fields', 'error')
            return render_template('contact.html')
        
        if len(name) < 2:
            flash('Name must contain at least 2 characters', 'error')
            return render_template('contact.html')
        
        # You can save the data to the database or send an email here
        flash(f'Thank you, {name}! Your message has been sent.', 'success')
        return redirect(url_for('contact'))
    
    return render_template('contact.html')

if __name__ == '__main__':
    app.run(debug=True)

HTML Form for Contact

Create templates/contact.html:

{% extends "base.html" %}

{% block title %}Contacts - My Site{% endblock %}

{% block content %}
<h2>Contact Us</h2>

{% with messages = get_flashed_messages(with_categories=true) %}
    {% if messages %}
        {% for category, message in messages %}
            <div class="alert alert-{{ category }}">
                {{ message }}
            </div>
        {% endfor %}
    {% endif %}
{% endwith %}

<form method="POST" class="contact-form">
    <div class="form-group">
        <label for="name">Name:</label>
        <input type="text" id="name" name="name" required maxlength="50">
    </div>
    
    <div class="form-group">
        <label for="email">Email:</label>
        <input type="email" id="email" name="email" required>
    </div>
    
    <div class="form-group">
        <label for="message">Message:</label>
        <textarea id="message" name="message" rows="5" required maxlength="500"></textarea>
    </div>
    
    <button type="submit" class="btn-submit">Send Message</button>
</form>
{% endblock %}

SQLite Database Integration

A database is needed to store user information and site content.

Installing and Configuring SQLAlchemy

Install the necessary libraries:

pip install flask-sqlalchemy flask-migrate

Creating a Data Model

Create a file models/database.py:

from flask_sqlalchemy import SQLAlchemy
from datetime import datetime

db = SQLAlchemy()

class User(db.Model):
    __tablename__ = 'users'
    
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    
    def __repr__(self):
        return f'<User {self.name}>'

class ContactMessage(db.Model):
    __tablename__ = 'contact_messages'
    
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False)
    email = db.Column(db.String(120), nullable=False)
    message = db.Column(db.Text, nullable=False)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    is_read = db.Column(db.Boolean, default=False)
    
    def __repr__(self):
        return f'<ContactMessage from {self.name}>'

Integrating the Database into the Application

Updated app.py file with database support:

from flask import Flask, render_template, request, flash, redirect, url_for
from models.database import db, User, ContactMessage
import os

app = Flask(__name__)
app.config['SECRET_KEY'] = 'your_secret_key_here'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db.init_app(app)

@app.before_first_request
def create_tables():
    db.create_all()

@app.route('/')
def home():
    users_count = User.query.count()
    return render_template('index.html', users_count=users_count)

@app.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        name = request.form.get('name')
        email = request.form.get('email')
        
        # Check for existing user
        existing_user = User.query.filter_by(email=email).first()
        if existing_user:
            flash('User with this email already exists', 'error')
            return render_template('register.html')
        
        # Creating a new user
        new_user = User(name=name, email=email)
        db.session.add(new_user)
        db.session.commit()
        
        flash(f'Welcome, {name}! Registration successful.', 'success')
        return redirect(url_for('home'))
    
    return render_template('register.html')

@app.route('/contact', methods=['GET', 'POST'])
def contact():
    if request.method == 'POST':
        name = request.form.get('name')
        email = request.form.get('email')
        message = request.form.get('message')
        
        # Saving the message to the database
        new_message = ContactMessage(name=name, email=email, message=message)
        db.session.add(new_message)
        db.session.commit()
        
        flash(f'Thank you, {name}! Your message has been saved.', 'success')
        return redirect(url_for('contact'))
    
    return render_template('contact.html')

@app.route('/messages')
def view_messages():
    messages = ContactMessage.query.order_by(ContactMessage.created_at.desc()).all()
    return render_template('messages.html', messages=messages)

if __name__ == '__main__':
    app.run(debug=True)

Deploying the Site on Hosting

After development, the site needs to be placed on the Internet for users to access.

Preparing for Deployment

Create a requirements.txt file with all dependencies:

Flask==2.3.3
Flask-SQLAlchemy==3.0.5
Flask-Migrate==4.0.5
Gunicorn==21.2.0

Create a Procfile file for Heroku:

web: gunicorn app:app

Popular Hosting Platforms

  • Heroku provides a free plan with limitations. Supports automatic deployment from a Git repository.
  • PythonAnywhere specializes in Python applications. Offers a simple control panel and built-in code editor.
  • Render is a modern alternative to Heroku with more generous free limits.
  • DigitalOcean App Platform provides scalability and performance for commercial projects.

Production Configuration

Create a separate config.py file:

import os

class Config:
    SECRET_KEY = os.environ.get('SECRET_KEY') or 'dev-secret-key'
    SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or 'sqlite:///site.db'
    SQLALCHEMY_TRACK_MODIFICATIONS = False

class ProductionConfig(Config):
    DEBUG = False
    TESTING = False

class DevelopmentConfig(Config):
    DEBUG = True
    TESTING = True

Frequently Asked Questions

Can I create a full-fledged commercial site on Flask?

Flask is great for creating small to medium-sized commercial websites. Many successful companies use Flask for their products. For large enterprise projects with many features, it is recommended to consider Django.

What is better to choose for a beginner: Django or Flask?

Flask is recommended for beginner developers. It allows you to quickly understand the basics of web development without unnecessary complexity. Django requires more in-depth study but provides ready-made solutions for typical tasks.

Which web server should I use in a production environment?

For production, use specialized WSGI servers:

  • Gunicorn for simple projects
  • uWSGI for high-load systems
  • NGINX as a reverse proxy

The built-in Flask server is only intended for development.

How to implement a user authentication system?

To create a login and registration system, use the Flask-Login library. It provides ready-made functions for managing user sessions and protecting pages.

Does Flask support REST API development?

Flask is perfect for creating RESTful APIs. Use additional Flask-RESTful or Flask-RESTX extensions to simplify the development of API endpoints.

What are the alternatives to Flask?

The main alternatives for web development in Python:

  • Django - a full-featured framework with many built-in features
  • FastAPI - a modern framework for high-performance APIs
  • Pyramid - a flexible framework for projects of any size
  • Tornado - an asynchronous web framework for realtime applications

Conclusion

Creating a website in Python using Flask is accessible even to beginner developers. The framework provides all the necessary tools for developing modern web applications.

Flask is ideal for rapid prototyping and creating small to medium-sized projects. For complex enterprise systems with many integrated functions, Django should be considered.

Learning web development in Python opens up great opportunities for career growth. Continue to experiment with different libraries and extensions to create more functional and interesting projects.

News