Open In App

Pyramid User Registration Using SQLAlchemy

In this article, we'll talk about using Python Pyramid with SQLAlchemy. We're going to create a registration form that saves user information in a database and shows it on a webpage. We'll also add a cool feature to update the database from the backend.

To make things more user-friendly, we'll set some rules. For emails, we'll make sure they look right, and for phone numbers, we'll require 10 digits. It's all about making our Python Pyramid application with SQLAlchemy more efficient and user-focused.

Python Pyramid - Using SQLAlchemy

Python Pyramid with SQLAlchemy is a powerful combination for web development. It allows developers to effortlessly create web applications with a robust framework (Pyramid) and seamlessly integrate with databases using SQLAlchemy. This dynamic duo simplifies the process of building registration forms, saving data to databases, and displaying it on web pages. Moreover, the integration enables easy backend updates, enhancing the overall functionality of web applications.

Create a Registration Form with CRUD Operation

Here, we will guide into a step-by-step guide to creating a registration form by saving data in the database in Python Pyramid Using SQLAlchemy. Let's start

Create a Virtual Environment

To create the virtual environment, use the following commands:

python -m venv env
.\env\Scripts\activate.ps1



iop

Install Nessaccary Library

To install Python Pyramid, Pyramid_jinja2, SQLAlchemy, and flash for flashing messages, use the following commands

pip install "pyramid==2.0"
pip install SQLAlchemy
pip install pyramid_jinja2
pip install flash


Implement the Logic

In this example Python code sets up a web application using Pyramid and SQLAlchemy. It creates a registration form, validates user input, stores data in an SQLite database, and displays it on a dashboard. The code uses Pyramid's views and routes for different web pages. SQLAlchemy is employed for database operations, and Jinja2 templates handle HTML rendering. The application supports features like user registration, deletion, and updating of records. Overall, the code demonstrates the integration of Pyramid and SQLAlchemy to build a functional web application with user interaction and database management capabilities.

Python3
from wsgiref.simple_server import make_server
from pyramid.config import Configurator
from pyramid.renderers import render_to_response
from pyramid.view import view_config
from pyramid.session import SignedCookieSessionFactory

import sqlalchemy as db
from sqlalchemy.dialects.sqlite import *
from sqlalchemy.orm import sessionmaker, Session
from sqlalchemy.ext.declarative import declarative_base

import os
import re

# Database Engine
engine = db.create_engine("sqlite:///users.db", echo=True)
Base = declarative_base()

# Model Class
class Applicants(Base):
    __tablename__ = "applicant"
    id = db.Column(db.Integer, primary_key=True, nullable=False)
    name = db.Column(db.String(63), unique=False)
    email = db.Column(db.String(63), unique=True)
    mobile = db.Column(db.String(10), unique=True)

    # For Formatting the Output in JSON Format
    def to_dict(self):
        return {
            "id": self.id,
            "name": self.name,
            "email": self.email,
            "mobile": self.mobile,
        }

# Check if database exists
if os.path.exists("users.db"):
    print("Database already exists!")
else:
    # Create database
    Base.metadata.create_all(engine)

@view_config(route_name="register", renderer="index.html")
def registration(request):
    if request.method == "POST":
        name = request.POST["name"]
        email = request.POST["email"]
        mobile = request.POST["mobile"]

        # For Pattern Matching, Input Validation
        emailPattern = re.compile(r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$")
        mobilePattern = re.compile(r"^[0-9]{10}$")

        if name != "" and emailPattern.match(email) and mobilePattern.match(mobile):
            request.session["name"] = request.POST["name"]
            request.session["email"] = request.POST["email"]

            # Insert into database
            session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
            s = session()

            commonEmail = s.query(Applicants).filter_by(email=email).first()
            commonMobile = s.query(Applicants).filter_by(mobile=mobile).first()

            if commonEmail is not None or commonMobile is not None:
                request.session.flash("User is already registered!")
                return render_t

Creating User Interface

dashboard.html : This HTML code establishes a dashboard in a web app using Pyramid and SQLAlchemy. It showcases user data in a Bootstrap-styled table and includes forms for deleting or updating records. Flash messages provide user notifications for a streamlined experience.

HTML
<!DOCTYPE html>
{% include package="pyramid_jinja2" %}
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Dashboard</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" 
          rel="stylesheet" 
          integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" 
          crossorigin="anonymous">
</head>
<body>
    <div>
        {% if request.session.peek_flash() %}
            <div id="flash" class="container jumbotron">
                {% for message in request.session.pop_flash() %}
                    <center><h1>{{ message }}</h1></center>
                {% endfor %}
            </div>
        {% endif %}
    </div>

    <br><br>
    <div class="container jumbotron">
        <table class="table table-striped">
            <thead>
                <tr>
                    <th scope="col">S.No</th>
                    <th scope="col">Name</th>
                    <th scope="col">Email Id</th>
                    <th scope="col">Mobile Number</th>
                </tr>
            </thead>
            <tbody>
                {% for data in request.session.data %}
                    <tr>
                        <th scope="row">{{ loop.index }}</th>
                        <td>{{ data['name'] }}</td>
                        <td>{{ data['email'] }}</td>
                        <td>{{ data['mobile'] }}</td>
                    </tr>
                {% endfor %}
            </tbody>
        </table>
    </div>

    <br><br>
    <div class="container jumbotron">
        <form action="/dashboard.html" method="POST">
            <div class="form-group">
                <label for="emailForDelete">Email Id</label>
                <select class="form-control" id="emailForDelete" name="emailForDelete">
                    {% for data in request.session.data %}
                        <option>{{ data['email'] }}</option>
                    {% endfor %}
                </select>
            </div>
            <br>    
            <center>
                <button type="submit" class="btn btn-primary" name="button" 
                        id="button" value="delete">Delete</button>
            </center>
        </form>
    </div>

    <br><br>
    <div class="container jumbotron">
        <form action="/dashboard.html" method="POST">
            <div class="form-group">
                <label for="emailForUpdate">Email Id for Updation</label>
                <select class="form-control" id="emailForUpdate" name="emailForUpdate">
                    {% for data in request.session.data %}
                        <option>{{ data['email'] }}</option>
                    {% endfor %}
                </select>

                <label for="name">New Name</label>
                <input type="text" class="form-control" id="name" name="name" 
                       placeholder="Enter Name">
                <label for="email">New Email Id</label>
                <input type="email" class="form-control" id="email" name="email" 
                       placeholder="Enter Email Id">
                <label for="mobile">New Mobile Number</label>
                <input type="text" class="form-control" id="mobile" name="mobile" 
                       placeholder="Enter Mobile Number">
            </div>
            <br>    
            <center>
                <button type="submit" class="btn btn-pr

index.html : This HTML code creates a registration form for a web app using Pyramid and Jinja2. It includes Bootstrap styling and flash messages for user feedback. The form prompts users to enter their name, email, and mobile number with validation. Upon submission, flash messages convey success or error notifications for a user-friendly experience.

HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Registration Form</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
</head>
<body>
    <br>
    <div>
        {% if request.session.peek_flash() %}
            <div id="flash" class="container jumbotron">
                {% for message in request.session.pop_flash() %}
                    <center><h1>{{ message }}</h1></center>
                {% endfor %}
            </div>
        {% endif %}
    </div>
    <br>
    <div class="container jumbotron">
        <div class="row">
            <div class="col-md-6 offset-md-3 form-container">
                <h2>Registration Form</h2>
                <p>Fill up the form with correct values.</p>
                <form role="form" method="post" id="reused_form" action="">
                    <div class="row">
                        <div class="col-sm-12 form-group">
                            <label for="name">Name:</label>
                            <input type="text" class="form-control" id="name" name="name" maxlength="50">
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-sm-12 form-group">
                            <label for="email">Email:</label>
                            <input type="email" class="form-control" id="email" name="email" maxlength="50">
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-sm-12 form-group">
                            <label for="mobile">Mobile No.:</label>
                            <input type="tel" class="form-control" id="mobile" name="mobile" maxlength="50">
                        </div>
                    </div>
                    <br>
                    <div class="row">
                        <div class="col-sm-12 form-group">
                           <center>
                              <button type="submit" class="btn btn-lg btn-success btn-block" id="btnContactUs">Register</button>
                           </center>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</body>
</html>

proceed.html : This HTML code defines a success page with Bootstrap styling in a Pyramid web app. It displays flash messages and includes a "Back" button linking to the homepage for user navigation.

HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Success</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
</head>
<body>
    <br>
    <div>
        {% if request.session.peek_flash() %}
            <div id="flash" class="container jumbotron">
                {% for message in request.session.pop_flash() %}
                    <center><h1>{{ message }}</h1></center>
                {% endfor %}
                
                <center><a href="/"><button type="button" class="btn btn-lg btn-success btn-block" id="btnContactUs">Back</button></a></center>
            </div>
        {% endif %}
    </div>
</body>
</html>

Run the Server

python .\script_name.py
localhost:6543
localhost/dashboard.html





Output :

Python Pyramid SQLAlchemy

Python Pyramid - Using SQLAlchemy

Article Tags :