how to add time to html from python method - python

this is part of a flask application. I would like to get the current time to output anywhere in the form of the html file.
I would like to add the method current_time() in flaskr.py to the anywhere in the from in the attached html file. Thanks!
flaskr.py
import os
import sqlite3
from flask import Flask, request, session, g, redirect, url_for, abort, \
render_template, flash
from datetime import date
import time
app = Flask(__name__)
app.config.from_object(__name__)
app.config.update(dict(
DATABASE = os.path.join(app.root_path, 'flaskr.db'), ##in real world apps use instance folders for databases instead
SECRET_KEY = 'development key',
USERNAME = 'admin',
PASSWORD = 'default'
))
app.config.from_envvar('FLASKR_SETTINGS', silent=True)
def connect_db():
rv = sqlite3.connect(app.config['DATABASE'])
rv.row_factory = sqlite3.Row
return rv
def get_db():
if not hasattr(g, 'sqlite_db'):
g.sqlite_db = connect_db()
return g.sqlite_db
#app.teardown_appcontext
def close_db(error):
if hasattr(g, 'sqlite_db'):
g.sqlite_db.close()
def init_db():
db = get_db()
with app.open_resource('schema.sql', mode = 'r') as f:
db.cursor().executescript(f.read())
db.commit()
#app.cli.command('initdb')
def initdb_command():
init_db()
print('initialized the database.')
#app.route('/')
def show_entries():
db = get_db()
cur = db.execute('select title, text from entries order by id desc')
entries = cur.fetchall()
return render_template('show_entries.html', entries=entries)
#app.route('/add', methods=['POST'])
def add_entry():
if not session.get('logged_in'):
abort(401)
db = get_db()
db.execute('insert into entries (title, text) values (?, ?)',
[request.form['title'], request.form['text']])
db.commit()
flash('New entry was successfully posted')
return redirect(url_for('show_entries'))
#app.route('/login', methods=['POST', 'GET'])
def login():
error = None
if request.method == 'POST':
if request.form['username'] != app.config['USERNAME']:
error = 'Invalid username'
elif request.form['password'] != app.config['PASSWORD']:
error = 'Invalid password'
else:
session['logged_in'] = True
flash('You were logged in')
return redirect(url_for('show_entries'))
return render_template('login.html', error = error)
#app.route('/logout')
def logout():
session.pop('logged_in', None)
flash('You were logged out')
return redirect(url_for('show_entries'))
def current_time():
return date.today()
show_entries.html
{% extends "layout.html" %}
{% block body %}
{% if session.logged_in %}
<form action="{{ url_for('add_entry') }}" method=post class=add-entry>
<dl>
<dt>Title:
<dd><input type=text size=30 name=title>
<dt>Text:
<dd><textarea name=text rows=5 cols=40></textarea>
<dd><input type=submit value=Share>
</dl>
</form>
{% endif %}
<ul class=entries>
{% for entry in entries %}
<li><h2>{{ entry.title }}</h2>{{ entry.text|safe }}
{% else %}
<li><em> No entries so far</em>
{% endfor %}
</ul>
{% endblock %}

You can just use datetime.now() method:
from datetime import datetime
...
return render_template(... current_time = datetime.now())
...

Related

Flask: For Loop not working in HTML template

I am trying to display certain information on a template. Everything in the python code works perfectly but anything and everything inside the for loop is not getting displayed inside the template. I believe that I have passed everything correctly. Could someone please help me to display the tutor info in my 'display.html'? I also want to mention that whatever I am trying to display should be available for all users to see and not just me. The file will keep getting updated as more and more users register as a tutor. This should update and show everyone who has signed up to all the users. Code will be below. Thanks in advance!
main.py
#main.py
from flask import Flask, request, session, render_template, redirect, url_for, flash, get_flashed_messages
from flask.globals import current_app
from flask_login import LoginManager, login_user, login_required, logout_user, current_user, UserMixin
from datetime import timedelta, datetime
from werkzeug.security import generate_password_hash, check_password_hash
import sqlite3
from os import error, path
from flask_sqlalchemy import SQLAlchemy
from flask_mail import Mail, Message
app = Flask(__name__)
DB_NAME = "spark.db"
app.config["SECRET_KEY"] = "1986319249872139865432"
app.config['SQLALCHEMY_DATABASE_URI'] = f"sqlite:///{DB_NAME}"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db = SQLAlchemy(app)
db.init_app(app)
def create_database(app):
if not path.exists(DB_NAME):
db.create_all(app=app)
print("Created Database!")
class Tutor(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
tremail = db.Column(db.String(10000))
trusername = db.Column(db.String(1200))
subjects = db.Column(db.String(1200))
session_length = db.Column(db.String(1200))
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(150), unique=True)
username = db.Column(db.String(150))
password = db.Column(db.String(150))
tutors = db.relationship('Tutor')
create_database(app)
login_manager = LoginManager()
login_manager.login_view = 'login'
login_manager.init_app(app)
#login_manager.user_loader
def load_user(id):
return User.query.get(int(id))
#app.route("/")
#login_required
def home():
return render_template("index.html")
#app.route("/login", methods=["GET", 'POST'])
def login():
if request.method == "POST":
email = request.form.get('email')
password = request.form.get('password')
user = User.query.filter_by(email=email).first()
if user:
if check_password_hash(user.password, password):
flash('Login successful!', category="success")
login_user(user, remember=True)
return redirect(url_for("home"))
else:
flash('Incorrect password! Please try again.', category="error")
else:
flash("Account does not exist. Please register to continue.", category="error")
return render_template("login.html", user=current_user)
#app.route("/register", methods=["GET", "POST"])
def register():
if request.method == 'POST':
email = request.form.get('email')
username = request.form.get('username')
password1 = request.form.get('password1')
password2 = request.form.get('password2')
user = User.query.filter_by(email=email).first()
if user:
flash("Email already exists.", category="error")
elif len(email) < 4:
flash("Email must be greater than 3 characters.", category="error")
elif len(username) < 2:
flash("Username must be greater than 1 character.", category="error")
elif password1 != password2:
flash("Passwords do not match! Please try again.", category="error")
elif len(password1) < 8:
flash("Password must be greater than 7 characters.", category="error")
else:
new_user = User(email=email, username=username, password=generate_password_hash(password1, method='sha256'))
db.session.add(new_user)
db.session.commit()
login_user(new_user, remember=True)
flash("Account successfully created!", category="success")
return redirect(url_for('home'))
return render_template("register.html", user=current_user)
#app.route("/logout")
#login_required
def logout():
logout_user()
flash("Logged out succcessfully!", category="success")
return redirect(url_for('login'))
#app.route("/selection")
#login_required
def selection():
return render_template("selection.html")
#app.route("/tutorform", methods=['GET', 'POST'])
#login_required
def tutorform():
if request.method == 'POST':
tremail = request.form.get('tremail')
trusername = request.form.get('trusername')
subjects = request.form.get('subjects')
session_length = request.form.get('session_length')
new_tutor = Tutor(user_id=current_user.id, tremail=tremail, trusername=trusername, subjects=subjects, session_length=session_length)
db.session.add(new_tutor)
db.session.commit()
flash('Entry has been saved!', category='success')
return redirect(url_for("display"))
return render_template("tutorform.html", user=current_user)
#app.route("/tutoreeform", methods=['GET', 'POST'])
#login_required
def tutoreeform():
if request.method == 'POST':
flash("Tutoree Entry Successful!", category='success')
return redirect(url_for("display"))
return render_template("tutoreeform.html")
#app.route("/display")
#login_required
def display():
users = Tutor.query.all()
for user in users:
print(user.tremail)
print(user.trusername)
print(user.subjects)
print(user.session_length)
return render_template("display.html", users=users)
if __name__ == '__main__':
db.create_all()
app.run(debug=True)
display.html
{% extends "base.html" %}
{% block title %}SparkWIT | | Available Tutors{% endblock %}
{% block content %}
<center><h1 style="color: beige; background-color: rgba(54, 65, 165, 0.466);"><b><i>Available Tutors</i></b></h1></center>
<table class="table">
<thead>
<tr>
<th scope="col" style="color: beige;"> Tutor Emails</th>
<th scope="col" style="color: beige;">Username</th>
<th scope="col" style="color: beige;">Subjects</th>
<th scope="col" style="color: beige;">Session Length</th>
</tr>
</thead>
{% for user in users.tutors %}
<tbody>
<tr>
<td style="color: beige;">{{ user.tremail }}</td>
<td style="color: beige;">{{ user.trusername }}</td>
<td style="color: beige;">{{ user.subjects }}</td>
<td style="color: beige;">{{ user.session_length }}</td>
</tr>
</tbody>
{% endfor %}
</table>
{% endblock %}
tutorform.html
{% extends "base.html" %}
{% block title %}SparkWIT | | Tutor Registration{% endblock %}
{% block content %}
<form method="POST">
<center><h3 style="color: beige; background-color: rgba(54, 65, 165, 0.466);"><i><u>Tutor Entry</u></i></h3></center>
<div class="form-group">
<label for="tremail" style="color: azure;"><b>Email</b></label>
<input
type="email"
class="form-control"
id="tremail"
name="tremail"
placeholder="example#example.com"
required />
</div>
<div class="form-group">
<label for="trusername" style="color: azure;"><b>Username</b></label>
<input
type="text"
class="form-control"
id="trusername"
name="trusername"
placeholder="Username"
required />
</div>
<div class="form-group">
<label for="subjects" style="color: azure;"><b>Subject</b></label>
<input
type="text"
class="form-control"
id="subjects"
name="subjects"
placeholder="Ex. AP Physics"
required />
</div>
<div class="form-group">
<label for="session_length" style="color: azure;"><b>Session Length</b></label>
<input
type="text"
class="form-control"
id="session_length"
name="session_length"
placeholder="Ex. 1.5 hours"
required />
</div>
<div class="form-group form-check">
<input type="checkbox" class="form-check-input" id="agree" name="agree" required>
<label class="form-check-label" for="agree" required><mark>I agree to conduct all sessions virtually for the tutoree's and my safety</mark></label>
</div>
<br>
<button type="submit" class="btn btn-dark">Submit</button>
</form>
{% endblock %}
In the HTML file, the for loop should be like {% for user in users %} because to display the user details, we need to loop on the data item we are passing in the render_template function as parameter.

Display username in base.html in Flask

I want to add current username in base.html, but I can't understand how make it.
I have got username, which takes from MySQL database
#app/routes
#app.route('/auth', methods=['GET', 'POST'])
def auth():
msg = ''
if request.method == 'POST' and 'username' in request.form and 'password' in request.form:
username = request.form['username']
hash = request.form['password']
salt = b'$2b$12$Mw/92Q0HkYKTR.0.ghNQs.'
password = bytes(hash, encoding='utf-8')
hash_1 = bcrypt.hashpw(password,salt)
cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cursor.execute('SELECT * FROM user WHERE username = % s AND password = % s', (username, hash_1,))
account = cursor.fetchone()
if account:
session['loggedin'] = True
session['id'] = account['id']
session['username'] = account['username']
msg = 'Logged in successfully !'
return render_template('index.html', msg=msg)
else:
msg = 'Неверное имя пользователя/пароль !'
return render_template('auth.html', msg=msg)
How can I take the username field and get it to the base.html, when user is Loggined in? I tryed to make it with using documentation, but it doesn`t work.
#base.html
{% if g.username %}
<li><span>{{ g.user['username'] }}</span>
{% else %}
<a class="p-2 text-dark" href="/auth">Авторизация</a>
{% endif %}
I make it
{% if session.loggedin %}
<a class="p-2 text-dark" href="/auth">Привет,{{session.username}} </a>
{% else %}
<a class="p-2 text-dark" href="/auth">Авторизация</a>

variable is undefined flask mysql

I need to greet user on the page. F.ex: Hello {{ name }}, but I get the error UnboundLocalError: local variable 'account' referenced before assignment. What is the problem in the code below?
python:
app = Flask(__name__)
mysql = MySQL(app)
#app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
name = request.form['name']
email = request.form['email']
cur = mysql.connection.cursor()
cur.execute('INSERT INTO users(name, email) VALUES(%s, %s)', (name, email))
mysql.connection.commit()
cur.close()
return redirect('profile')
return render_template('index.html')
#app.route('/profile', methods=['GET'])
def profile():
if request.method == 'POST':
name = request.form['name']
email = request.form['email']
cur = mysql.connection.cursor()
cur.execute('SELECT * FROM users')
account = cur.fetchone()
return render_template('profile.html', account=account)
index.html:
<form action="" method="POST">
<span style="color: #fff;">Firstname:</span><input type="text" name="name" placeholder="Type your firstname"><br><br>
<input type="submit" name="submit" value="submit">
</form>
profile.html
<h4 style="color: #fff;">Your firstname: is {{ account['name'] }}</h4>
<h4 style="color: #fff;">Your email: is {{ account['email'] }}</h4>
I can connect to database and fetch users data, but on the profile.html page I get the error
How to solve it? Please help.
You haven't passed the account to the template.
Instead of ,
return render_template('profile.html')
you need to write as,
return render_template('profile.html', account=account)
EDIT:
#app.route('/profile', methods=['GET','POST'])
def profile():
if request.method == 'POST':
name = request.form['name']
email = request.form['email']
cur = mysql.connection.cursor()
cur.execute('SELECT * FROM users')
account = cur.fetchone()
return render_template('profile.html', account=account)
Or if you wanted the profile to be a get request you can do this
#app.route('/profile', methods=['GET','POST'])
def profile():
if request.method == 'POST':
name = request.form['name']
email = request.form['email']
cur = mysql.connection.cursor()
cur.execute('SELECT * FROM users')
account = cur.fetchone()
return render_template('profile.html', account=account)

form disappearing after clicking on submit button on HTML

im doing this project which requires me to submit some forms and then return the value. However when i press the submit button the form disappear like as if the page got refreshed. Can any one help me? the code is in HTML
<div id="b2" class="containerTab" style="display:none;background:white">
<span onclick="this.parentElement.style.display='none'" class="closebtn">x</span>
<form method="POST">
<span style="float: left"><b>BTC amt >=: </b></span><center><b> Depth: <input type="range" name="rangeInput" min="0" max="20" onchange="updateTextInput2(this.value);"><input style="font-size:15px;" type="text" id="textInput2" value=""></b></center>
<input style="font-size:15px;" type="text" name=BTC amt><br>
<b>And <= :</b><br>
<input style="font-size:15px;" type="text" name="mdA">
 
<input style="font-size:20px;" name="BTCamt" type="submit" value="Submit"><br><br><br><br>
</form>
<div>
{{outBTC}}
</div>
</div>
This is the function im trying to run in this HTML
from flask import Flask, render_template, url_for, request
app = Flask(name)
#app.route("/")
def home():
return render_template('home.html')
#app.route("/", methods=['POST'])
def index():
# if form.validate_on_submit():
if 'transactionid' in request.form:
transactionaddr = request.form['transactionid']
newresult = runCypher(transactionaddr)
return render_template('home.html', outputresult=newresult)
elif 'BTCamt' in request.form:
transactionaddr = request.form['BTCamt']
newresult = runCypher(transactionaddr)
return render_template('home.html', outBTC=newresult)
def runCypher(transactionaddr):
from neo4j import GraphDatabase
uri = "bolt://localhost:7687"
user = "neo4j"
password = "123"
graphdb = GraphDatabase.driver(uri, auth=(user, password))
session = graphdb.session()
q1 = 'MATCH g=(n:out {addr: "'+transactionaddr+'"})-[*..3]-(m) RETURN g'
nodes = session.run(q1)
out = ""
for node in nodes:
out += str(node)
return out
if __name__ == '__main__':
app.run(debug=True)
The / route was declared twice. This should point you in the right direction..
#app.route("/", methods=['GET','POST'])
def index():
# if form.validate_on_submit():
if request.method == 'POST':
if 'transactionid' in request.form:
transactionaddr = request.form['transactionid']
newresult = runCypher(transactionaddr)
return render_template('home.html', outputresult=newresult)
elif 'BTCamt' in request.form:
transactionaddr = request.form['BTCamt']
newresult = runCypher(transactionaddr)
return render_template('home.html', outBTC=newresult)
return render_template('home.html')

SQL database not showing enteries

Im trying to develop a simple blog app. With base that for now only has user_name field and text (besedilo). After i run it it shows no errors. But data is not stored in database and does not display later on.
app.py
from flask import Flask, render_template, request
from flask_mysqldb import MySQL
import yaml
from flask_bootstrap import Bootstrap
app=Flask(__name__)
bootstrap = Bootstrap(app)
db = yaml.load(open('db.yaml'))
app.config['MYSQL_HOST'] = db['mysql_host']
app.config['MYSQL_USER'] = db['mysql_user']
app.config['MYSQL_PASSWORD'] = db['mysql_password']
app.config['MYSQL_DB'] = db['mysql_db']
mysql = MySQL(app)
#app.route('/', methods=['GET','POST'])
def index():
if request.method == 'POST':
form = request.form
user_name = form['user_name']
besedilo = form['besedilo']
cur = mysql.connect.cursor()
cur.execute("INSERT INTO post(user_name, besedilo) VALUES(%s, %s)", (user_name, besedilo))
mysql.connection.commit()
return render_template('index.html')
#app.route('/post')
def post():
cur = mysql.connection.cursor()
result_value = cur.execute("SELECT * FROM post")
if result_value > 0:
post = cur.fetchall()
return render_template('post.html', post=post)
if __name__ == '__main__':
app.run(debug=True)
index.html
{% extends 'base.html' %}
{% block content %}
<h1>Hello</h1>
<form method="post">
NAME:<input type="name" name="user_name">
BESEDILO:<input type="text" name="besedilo">
<input type="submit">
</form>
{% endblock %}
</body>
</html>
post.html
{% extends 'base.html' %}
{% block sub_content %}
<table border = 1>
{% for post in posts %}
<tr>
<td>{{post.user_name}}</td>
<td>{{post.besedilo}}</td>
</tr>
{% endfor %}
</table>
{% endblock %}
db.yaml
mysql_host: 'localhost'
mysql_user: 'root'
mysql_password: 'xxxxxxxx'
mysql_db: 'my_blog'
What have i missed. I have installed all packages, field names are matching.
Database that i set up (with the following commands):
CREATE DATABASE my_blog;
CREATE TABLE post(user_name varchar(30), besedilo varchar(150));
and inserts for fine: with
INSERT INTO post(user_name, besedilo) VALUES ('Alex', 'i have a job to do');
mysql> SELECT * FROM post;
+-----------+----------------+
| user_name | besedilo |
+-----------+----------------+
| Peter | some text |
| Alex | i have a job |
+-----------+----------------+
1.) UPDATE :
#app.route('/', methods=['GET','POST'])
def index():
if request.method == 'POST':
form = request.form
user_name = form['user_name']
besedilo = form['besedilo']
conn = mysql.connect()
cur = conn.cursor()
cur.execute("INSERT INTO post(user_name, besedilo) VALUES(%s, %s)", (user_name, besedilo))
conn.commit()
return render_template('index.html')
I have strong suspicion that culprit is if result_value>0.
I suppose it's always returns 0 for SELECT * FROM post not matter if rows exists in table.
Excerpts from MySQL Documentation:
The use of mysql_num_rows() depends on whether you use mysql_store_result() or mysql_use_result() to return the result set. If you use mysql_store_result(), mysql_num_rows() may be called immediately. If you use mysql_use_result(), mysql_num_rows() does not return the correct value until all the rows in the result set have been retrieved.
Try to exclude your result_value check and see results:
#app.route('/post')
def post():
cur = mysql.connection.cursor()
cur.execute("SELECT * FROM post")
# if result_value > 0: ## I suppose that line always returns 0
post = cur.fetchall()
return render_template('post.html', post=post)
As for def index() - I'm not sure there is a problem there.
Inform about your progress.

Categories

Resources