This commit is contained in:
Sayed Abubaker Hashimi 2025-03-18 12:53:39 +01:00
commit 14402085f5
16 changed files with 409 additions and 0 deletions

20
z1/Dockerfile Normal file
View File

@ -0,0 +1,20 @@
FROM python:3.8
COPY requirements.txt /
WORKDIR /
RUN pip3 install -r ./requirements.txt --no-cache-dir
COPY . /app/
WORKDIR /app
ENV FLASK_APP=app.py
# RUN python manage.py create_db
CMD flask run -h 0.0.0.0 -p 1602

21
z1/LICENSE Normal file
View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2021 NOMANSAEEDSOOMRO
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

1
z1/Procfile Normal file
View File

@ -0,0 +1 @@
web: gunicorn app:app

62
z1/README.md Normal file
View File

@ -0,0 +1,62 @@
# Flask-App-with-PostgreSQL-DB
This Website is build on the Python Flask with PostgreSQL Database. Data Insertion and Fetching.
**For Running on Local System Follow the below insturction**
Comment the below Code in the app.py File
'uri = os.getenv("DATABASE_URL") # or other relevant config var
if uri.startswith("postgres://"):
uri = uri.replace("postgres://", "postgresql://", 1)'
UnComment the Below code in the app.py file
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///User.sqlite3"
Run the app.py file and in the Terminal run the below commands
pyhton
from app import db
db.create_all()
**If you are Using libraries then run the pip freeze command and for the deployment on heroku follow the below commands**
UnComment the below Code in the app.py File
'uri = os.getenv("DATABASE_URL") # or other relevant config var
if uri.startswith("postgres://"):
uri = uri.replace("postgres://", "postgresql://", 1)'
Comment the Below code in the app.py file
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///User.sqlite3"
pip install gunicorn
pip install psycopg2
pip freeze > requirements.txt
Create runtime.txt and write your python version i.e python-3.7.10
echo web: gunicorn app:app > Procfile #creating procfile
Create an account on heroku and also download the heroku cli
##Write Following commands in pycharm/vscode
1. heroku login
2. heroku create "project name"
3. heroku addons:create heroku-postgresql:hobby-dev --app "project name"
4. git init
5. git add .
6. git commit -m "first commit"
7. heroku git:remote -a "project name"
8. git push heroku master
9. heroku run python
10. from app import db
11. db.create_all()

Binary file not shown.

73
z1/app.py Normal file
View File

@ -0,0 +1,73 @@
from flask import Flask, render_template, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
import os
uri = os.getenv("DATABASE_URL") # or other relevant config var
uri ="postgresql://postgres:postgres@db_postgres:5432/postgres"
if uri.startswith("postgres://"):
uri = uri.replace("postgres://", "postgresql://", 1)
# rest of connection code using the connection string `uri`
app = Flask(__name__)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config["SQLALCHEMY_DATABASE_URI"] = uri
#app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///User.sqlite3"
db = SQLAlchemy(app)
class User(db.Model):
__tablename__ = "user"
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
name = db.Column(db.String(100), nullable=False)
email = db.Column(db.String(100), nullable=False)
gender = db.Column(db.String(100), nullable=False)
password = db.Column(db.String(100), nullable=False)
def __init__(self, name, email, gender, password):
self.name = name
self.email = email
self.gender = gender
self.password = password
db.create_all()
@app.route("/")
def home():
db.create_all()
return redirect(url_for('index'))
@app.route("/index", methods=["GET", "POST"])
def index():
if request.method == 'POST': # When a user clicks submit button it will come here.
data = request.form # request the data from the form in index.html file
name = data["name"]
email = data["email"]
gender = data["Gender"]
password = data["password"]
new_data = User(name, email, gender, password)
db.session.add(new_data)
db.session.commit()
user_data = User.query.all()
#print(user_data)
#return render_template("index.html" , user_data=user_data) # passes user_data variable into the index.html file.
return render_template("usersdata.html")
@app.route("/usersdata")
def usersdata():
return render_template("usersdata.html" , user_data = User.query.all())
if __name__ == '__main__':
app.run(debug=True, port=1602)

View File

@ -0,0 +1,25 @@
version: '3.9'
services:
postgres:
container_name: db_postgres
image: postgres
hostname: postgres
ports:
- "5432:5432"
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: postgres
volumes:
- postgres-volume:/var/lib/postgresql/data
restart: unless-stopped
networks:
- test-net
volumes:
postgres-volume:
networks:
test-net:
external: true

25
z1/docker-compose.yml Normal file
View File

@ -0,0 +1,25 @@
version: '3.9'
services:
flask:
build:
dockerfile: Dockerfile
context: .
environment:
# DATABASE DETAILS
- DBNAME=test_db
- DBUSER=postgres
- DBPASS=postgres
- DBPORT=5450
- DBHOST=0.0.0.0
ports:
- "8050:1602"
networks:
- test-net
networks:
test-net:
external: true

16
z1/manage.py Normal file
View File

@ -0,0 +1,16 @@
from flask.cli import FlaskGroup
from app import db
import app
cli = FlaskGroup(app)
@cli.command("create_db")
def create_db():
db.drop_all()
db.create_all()
db.session.commit()
from exc
execute_from_command_line(sys.argv)
if __name__ == "__main__":
cli()

1
z1/remove app.sh Normal file
View File

@ -0,0 +1 @@
echo "Docker Container, Network, Volume removed "

15
z1/requirements.txt Normal file
View File

@ -0,0 +1,15 @@
click==8.0.1
colorama==0.4.4
Flask==2.0.1
Flask-SQLAlchemy==2.5.1
greenlet==1.1.0
gunicorn==20.1.0
importlib-metadata==4.0.1
itsdangerous==2.0.1
Jinja2==3.0.1
MarkupSafe==2.0.1
psycopg2-binary==2.9.1
SQLAlchemy==1.4.15
typing-extensions==3.10.0.0
Werkzeug==2.0.1
zipp==3.4.1

1
z1/runtime.txt Normal file
View File

@ -0,0 +1 @@
python-3.7.10

2
z1/start.app.sh Normal file
View File

@ -0,0 +1,2 @@
docker compose stop
echo "Docker containers start "

2
z1/stop.app.sh Normal file
View File

@ -0,0 +1,2 @@
docker compose stop
echo "Docker containers stopped SSS"

103
z1/templates/index.html Normal file
View File

@ -0,0 +1,103 @@
<!DOCTYPE html>
<html lang="en">
<head>
<title>Register Page</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<style >
body {
height: 100%;
background-image: linear-gradient(to right , #37B9E9 , #63C4C9 ,#E3F2FD );
}
</style>
</head>
<body>
<header>
<div class="container-fluid mt-2 ">
<marquee> <p class="text-capitalize text-white mx-3 mt-3" style="font-size: 25px">Flask App with DataBase</p> </marquee>
</div>
</header>
<div class="container text-capitalize">
<div class="row">
<div class="col-md-12">
<h1 class="text-center mt-4 text-white">Create Account </h1>
<hr class="w-25 mx-auto mt-auto" style="border: 04px solid #003D51; border-radius: 5px">
<div class="row">
<div class="col-md-6 mx-auto">
<div class="card border-secondary">
<div class="card-header" style="background-color: #557D8B">
<h3 class="mb-0 my-2 text-white" >User Data Form</h3>
</div>
<div class="card-body" style="background-color: #e3f2fd">
<form class="form text-capitalize" role="form" autocomplete="off"
action="" method="POST">
<div class="form-group">
<label for="inputName" >Full Name</label>
<input type="text" class="form-control" placeholder="Enter your Full Name"required="" name="name">
</div>
<div class="form-group">
<label for="inputEmail3" >Email</label>
<input type="email" class="form-control" placeholder="Email@gmail.com" required="" name="email">
</div>
<div class="form-group">
<label for="gender" >Gender</label>
<select class="custom-select form-inline" name="Gender">
<option selected>Choose...</option>
<option value="male" name="Gender" >Male</option>
<option value="female" name="Gender"> Female</option>
</select>
</div>
<div class="form-group">
<label for="inputPassword3" >Password</label>
<input type="password" class="form-control" placeholder="Enter your Password" title="At least 6 characters with letters and numbers" required="" name="password">
</div>
<div class="form-group">
<button type="submit" class="btn btn-lg float-right text-white" style="background-color: #003D51" name="Reg">Register</button>
</div>
<div class="form-group">
<div class="form-check">
<input class="form-check-input" type="checkbox" value="" id="invalidCheck2" required>
<label class="form-check-label" for="invalidCheck2">
I Agree to the terms and conditions.
</label>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<!--/row-->
</div>
<!--/col-->
</div>
<!--/row-->
</div>
</div>
<footer id="sticky-footer" class="py-3 text-dark-90 mt-5" style="background-color: #E3F2FD" >
<div class="container text-center">
<small>Copyright &copy; NSA Website</small>
</div>
</footer>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
</body>
</html>

View File

@ -0,0 +1,42 @@
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container mt-5" >
<h2>User's Data</h2>
<p>Fetching data from database </p>
<table class="table">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
<th>Gender</th>
</tr>
</thead>
<tbody>
<!-- The user_data is a variable containing all the user data from the DB. -->
{% for user in user_data %}
<tr>
<td>{{user.id}}</td>
<td>{{user.name}}</td>
<td>{{user.email}}</td>
<td>{{user.gender}}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</body>
</html>