I don't know how to create a login and sign up page with only name and save it in a database and in a session I am trying to create a webpage for my family to ask me for help with anything and I want to add a login system to it.I am using Twilio to send messages and I am good with the core functionality but I can't make the login. Here is my python code:
from twilio.rest import Client
from flask import Flask,render_template,request, redirect, url_for, session, flash
from datetime import timedelta
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
account_sid = 'ACCOUNT SID'
auth_token = 'AUTH-TOKEN'
my_number='PHONE NUMBER'
twillio_number = 'TWILIO NUMBER'
client = Client(account_sid, auth_token)
app.secret_key = "secret key"
app.permanent_session_lifetime = timedelta(minutes=30)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.sqlite3'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
class Users(db.Model):
_id = db.Column("id", db.Integer, primary_key=True)
name = db.Column(db.String(100))
def __init__(self, name):
self.name = name
@app.route("/")
def index():
return redirect(url_for("login"))
@app.route("/login", methods=['POST', 'GET'])
def login():
if request.method == "POST":
username = request.form.get('username')
usr = Users(name=username)
session['user'] = usr
return redirect(url_for('msg'))
return render_template('indextwo.html')
@app.route("/msg", methods=['POST', 'GET'])
def home():
if 'user' in session:
user = session['user']
message = ()
if request.method == "POST":
msgval = request.form.get('msg')
if msgval:
message = client.messages.create(
body = msgval,
from_ = twillio_number,
to = my_number
)
else:
msgvall = request.form.get('exa')
if msgvall:
message = client.messages.create(
body = msgvall,
from_ = twillio_number,
to = my_number
)
return render_template('index.html', username=user, content=message)
if __name__ == "__main__":
app.run(debug=True, host='0.0.0.0', port=80)
And my HTML LOGIN code(indextwo.html):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Log in</title>
</head>
<body>
<form action="#" methods="POST">
<input type="text" name="username">
<input type="submit" value="LOG IN">
</form>
</body>
</html>
And my Home HTML code(index.html):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HelperMessage📧</title>
<style>
hr{
border-color:rgb(151, 144, 144);
width:75%;
}
form{
text-align: center;
margin-bottom: 20px;
}
.askforhelp{
margin-top: 20px;
}
.f2{
margin-top: 20px;
}
</style>
</head>
<body>
<div class="askforhelp">
<form action="#" method="post">
<select name="exa">
<option>Select one if you don't want to type</option>
<option>Need help with tech</option>
<option>Need to watch Zara</option>
<option>Need to lift something heavy</option>
<option>Need me to go buy something</option>
</select>
<input type="submit" value="Send"/>
</form>
<hr>
<form action="#" method="post" class="f2">
<input type="text" name="msg" />
<input type="submit" value="Send"/>
</form>
</div>
</body>
</html>
And trust me I know my code isn't one of the greatest I am just trying to improve my coding skill with project-based learning.
I recommend installing flask-login to make your work easier.
The following example shows you how to create a login for users who are stored in the database. If a user is not logged in, he is automatically forwarded to the login. If he enters his username there, he will be redirected to the main page, where you can implement sending the messages via twilio.
If the user is inactive for 30 minutes, he is automatically logged out.
Your template for the HTML code stays the same. But inside the form is a typo. You should change the attribute methods="POST"
to method="POST"
.
from datetime import timedelta
from flask import (
Flask,
redirect,
render_template,
request,
session,
url_for
)
from flask_login import (
LoginManager,
UserMixin,
current_user,
login_required,
login_user,
)
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config.from_mapping(
SECRET_KEY='your secret here',
SQLALCHEMY_DATABASE_URI='sqlite:///users.db'
)
app.permanent_session_lifetime = timedelta(minutes=30)
db = SQLAlchemy(app)
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'
class User(UserMixin, db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(100))
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
with app.app_context():
# Delete all tables and their contents.
db.drop_all()
# Create the database tables and add users.
db.create_all()
# If you want to add more users, add them here.
user1 = User(username='Haris')
db.session.add(user1)
db.session.commit()
@app.before_request
def before_request():
session.permanent = True
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
# Search user by username and log in.
username = request.form.get('username')
# Return the first user that matches the username.
# If no matching username is found, return None.
user = User.query.filter_by(username=username).first()
if user:
# The user was found and will be logged in.
login_user(user)
# A forwarding takes place.
return redirect(url_for('index'))
return render_template('login.html')
@app.route('/', methods=['GET', 'POST'])
@login_required
def index():
print(f'{current_user.username} is logged in.')
if request.method == 'POST':
# Your code to send messages here.
pass
return render_template('index.html', **locals())