Skip to content

Commit

Permalink
Python-MySQL-Integration:Implemented an HTML/CSS user registration fo…
Browse files Browse the repository at this point in the history
…rm and integrated it with a Flask backend. The form uses JavaScript to submit data via `fetch` with `application/x-www-form-urlencoded` encoding. The Flask backend processes and saves the user data to a MySQL database.
  • Loading branch information
charakamihiranga committed Sep 10, 2024
1 parent 615eb0b commit c2d72be
Show file tree
Hide file tree
Showing 21 changed files with 287 additions and 0 deletions.
8 changes: 8 additions & 0 deletions JWT/JWT-Frontend/.idea/.gitignore

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 9 additions & 0 deletions JWT/JWT-Frontend/.idea/JWT-Frontend.iml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions JWT/JWT-Frontend/.idea/misc.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions JWT/JWT-Frontend/.idea/modules.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions JWT/JWT-Frontend/.idea/vcs.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions Python-MySQL-Integration/.idea/.gitignore

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

21 changes: 21 additions & 0 deletions Python-MySQL-Integration/.idea/Python-MySQL-Integration.iml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 12 additions & 0 deletions Python-MySQL-Integration/.idea/dataSources.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 7 additions & 0 deletions Python-MySQL-Integration/.idea/misc.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions Python-MySQL-Integration/.idea/modules.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions Python-MySQL-Integration/.idea/vcs.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Binary file not shown.
29 changes: 29 additions & 0 deletions Python-MySQL-Integration/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
from flask import Flask, render_template, request
from sqlalchemy import null

from entity.User import User
from model.UserModel import UserModel

app = Flask(__name__)


@app.route('/')
def home(): # put application's code here
return render_template('index.html')

@app.route('/register', methods=['POST'])
def register():
name = request.form.get('name')
email = request.form.get('email')
password = request.form.get('password')

# Save the user details to the database
user = User(
name = name,
email = email,
password = User.hash_password(password)
)
return UserModel.save_user(user)

if __name__ == '__main__':
app.run()
34 changes: 34 additions & 0 deletions Python-MySQL-Integration/entity/User.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import uuid
from sqlalchemy import Column, String, create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import validates, sessionmaker
import bcrypt

DATABASE_URL = 'mysql+pymysql://root:1234@localhost/se10sessions'
engine = create_engine(DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()

class User(Base):
__tablename__ = 'user'

# Use String type for the ID to store UUIDs
id = Column(String(36), primary_key=True, default=lambda: str(uuid.uuid4()))
name = Column(String(255), index=True)
email = Column(String(255), unique=True, index=True)
password = Column(String(255))

@staticmethod
def hash_password(password):
# Hash password before storing it
if password:
hashed = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
return hashed.decode('utf-8')
return password

def check_password(self, password):
# Verify password
return bcrypt.checkpw(password.encode('utf-8'), self.password.encode('utf-8'))

# Create tables
Base.metadata.create_all(bind=engine)
Binary file not shown.
16 changes: 16 additions & 0 deletions Python-MySQL-Integration/model/UserModel.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
from entity.User import SessionLocal


class UserModel:
@staticmethod
def save_user(user):
db = SessionLocal()
try:
db.add(user)
db.commit()
return "User saved successfully"
except Exception as e:
print(f"Failed to save user. Rolling back. Error: {e}")
db.rollback()
finally:
db.close()
Binary file not shown.
29 changes: 29 additions & 0 deletions Python-MySQL-Integration/static/js/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
function userRegistration() {
// Get form values
const name = document.getElementById('name').value;
const email = document.getElementById('email').value;
const password = document.getElementById('password').value;

// Prepare the data to be sent
const data = new URLSearchParams();
data.append('name', name);
data.append('email', email);
data.append('password', password);

// Send POST request
fetch('http://127.0.0.1:5000/register', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: data.toString(),
})
.then(response => response.text())
.then(result => {
alert(result);
})
.catch(error => {
console.error('Error:', error);
alert('Failed to register user');
});
}
67 changes: 67 additions & 0 deletions Python-MySQL-Integration/templates/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
<!doctype html>
<html lang="en">

<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Python-MySQL Intergration</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<style>
body {
background-color: #f0f2f5;
}
.container {
max-width: 600px;
margin: 5% auto;
padding: 2rem;
background-color: #ffffff;
border-radius: 12px;
box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
}
h2 {
color: #007bff;
font-weight: bold;
}
.form-label {
font-weight: bold;
}
.btn-primary {
background-color: #007bff;
border: none;
}
.btn-primary:hover {
background-color: #0056b3;
}
.text-muted {
color: #6c757d;
}
</style>
</head>

<body>
<div class="container">
<h2 class="text-center mb-4">User Registration</h2>
<form>
<div class="mb-4">
<label for="name" class="form-label">Full Name</label>
<input type="text" class="form-control" id="name" required>
</div>
<div class="mb-4">
<label for="email" class="form-label">Email address</label>
<input type="email" class="form-control" id="email" required>
</div>
<div class="mb-4">
<label for="password" class="form-label">Password</label>
<input type="password" class="form-control" id="password" required>
</div>

<button type="button" class="btn btn-primary w-100" onclick="userRegistration()">Sign Up</button>
</form>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>
<script src="{{ url_for('static', filename='js/index.js') }}"></script>
</body>

</html>

0 comments on commit c2d72be

Please sign in to comment.