Skip to content

Commit 17c8e3f

Browse files
authored
Add files via upload
1 parent fdb8a78 commit 17c8e3f

File tree

1 file changed

+103
-0
lines changed

1 file changed

+103
-0
lines changed

PythonProject/app2.py

Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
from flask import Flask, request, render_template, redirect, url_for
2+
# import mysql.connector as ms
3+
#pip install pymysql
4+
import pymysql as ms
5+
6+
7+
app = Flask(__name__)
8+
9+
# Create a connection to the database
10+
def get_db_connection():
11+
print('to be Connected....')
12+
try:
13+
conn = ms.connect(user='root',password='mysql@123',host='localhost',database='python01')
14+
print('Connected....')
15+
return conn
16+
except ms.Error as err:
17+
print('Error:',err)
18+
return None
19+
20+
21+
22+
# Initialize the database
23+
def init_db():
24+
conn = get_db_connection()
25+
mycursor = conn.cursor()
26+
mycursor.execute('select * from users;')
27+
res=mycursor.fetchall()
28+
for user in res:
29+
print(user)
30+
31+
conn.close()
32+
33+
init_db()
34+
35+
# Route for the home page with the form
36+
@app.route('/', methods=('GET', 'POST'))
37+
def index():
38+
print("esfawsf",request.form)
39+
print("method", request.method)
40+
if request.method == 'POST':
41+
name = request.form['name']
42+
email = request.form['email']
43+
#dob = request.form['dateofbirth']
44+
dob='2024-10-16'
45+
46+
47+
48+
49+
50+
# Insert the data into the database
51+
conn = get_db_connection()
52+
mycursor = conn.cursor()
53+
54+
55+
mycursor.execute("SELECT count(username) from users where username='"+name+"'")
56+
x=mycursor.fetchone()
57+
58+
print("count=",x[0])
59+
if(x[0]>=1):
60+
print("user already exists")
61+
return redirect(url_for('already'))
62+
63+
64+
65+
66+
mycursor.execute("INSERT INTO users(username, email,dob,status) VALUES (%s,%s, %s,'Active')", (name, email,dob))
67+
conn.commit()
68+
mycursor.close()
69+
# conn.commit()
70+
conn.close()
71+
72+
return redirect(url_for('userlist'))
73+
else:
74+
return render_template('index.html')
75+
76+
77+
# Route to display success message
78+
@app.route('/success')
79+
def success():
80+
return 'Data successfully submitted!'
81+
82+
83+
84+
@app.route('/already')
85+
def already():
86+
return 'user already exists!'
87+
88+
89+
# Route to display success message
90+
@app.route('/userlist')
91+
def userlist():
92+
conn = get_db_connection()
93+
mycursor = conn.cursor()
94+
mycursor.execute('select * from users;')
95+
users = mycursor.fetchall()
96+
97+
mycursor.close()
98+
# conn.commit()
99+
conn.close()
100+
return render_template('userlist.html',users=users)
101+
102+
if __name__ == '__main__':
103+
app.run()

0 commit comments

Comments
 (0)