This works but..
views.py
from django.http import HttpResponse
from django.db import connection
def query():
with connection.cursor() as cursor:
cursor.execute('SELECT some, stuff FROM here;')
row = cursor.fetchall()
return row
def index(request):
return HttpResponse(query())
What if I want to get a filtered response that is restricted to a user or group from the admin?
For example, if the user is in the BAIT group they could filter results WHERE email LIKE 'bob#bait.com';
I did it like this...
/opt/my_project/my_app/templates/my_app/generate_html.html
<html>
<h1>Generate HTML</h1>
<form method="POST" action="">
{% csrf_token %}
{{ form }}
<button type="submit">Submit Query</button>
</form>
</html>
/opt/my_project/my_project/settings.py
'DIRS': ['/opt/my_project/my_app/templates/my_app'],
/opt/my_project/my_app/urls.py
path('generate_html/', generate_html, name = "generate_html"),
/opt/my_project/my_app/forms.py
from django import forms
class InputForm(forms.Form):
email = forms.EmailField(max_length = 100)
/opt/my_project/my_app/views.py
def query(email):
with connection.cursor() as cursor:
query = '''SELECT some, stuff
FROM here
WHERE email = %s
ORDER BY stuff;
'''
values = (email,)
cursor.execute(query, values)
select = cursor.fetchall()
return select
def generate_html(request):
if request.method == 'POST':
email = request.POST.get('email', None)
try:
html = '<!DOCTYPE html><html><body>'
for row in query(email):
some, stuff = row
html += 'Row: ' + some + ' ' + stuff + '<br>'
html += '<br><br>' + 'Search Again!' + '</body></html>'
return HttpResponse(html)
except Exception as e:
return HttpResponse(str(e))
else:
context ={}
context['form']= InputForm()
return render(request, "generate_html.html", context)
I am new in build python api. I want to get the data depend on date.
https://programminghistorian.org/en/lessons/creating-apis-with-python-and-flask#what-is-an-api
I am following this link to code my api but I don't know what can I do in execute.
This is my python code:
# -*- coding: utf-8 -*-
from flask import Flask, render_template, request
from flask_mysqldb import MySQL
app = Flask(__name__)
app.config["DEBUG"] = True
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = 'root'
app.config['MYSQL_DB'] = 'MyDB'
app.config['MYSQL_charset'] ='utf8'
mysql = MySQL(app)
#app.route('/',methods = ['GET','POST'])
def index():
if request.method == "POST":
details = request.form
firstday = details['firstday']
lastday = details['lastday']
cur = mysql.connection.cursor()
cur.execute("select * from transaction join transaction_item on transaction.id = transaction_item.transaction_id join customer on customer.id = transaction.customer_id where transaction_datetime <= lastday and transaction_datetime >= firstday VALUES (%s, %s)", (firstday, lastday))
mysql.connection.commit()
cur.close()
return 'success'
return render_template('index.html')
if __name__ == '__main__':
app.run()
This is my HTML code:
<HTML>
<BODY bgcolor="cyan">
<form method="POST" action="">
<center>
<H1>Enter your details </H1> <br>
first_transaction_datetime <input type = "text" name= "firstday" /> <br>
last_transaction_datetime <input type = "text" name= "lastday" /> <br>
<input type = "submit">
</center>
</form>
</BODY>
</HTML>
When you are sending requests to a back-end it does not fill out the form an easy way to do it would be to add the query values in the URL
http://127.0.0.1:5000/?firstName=<firstName>&lastName=<lastName>
then your python code would look something like this.
#app.route('/',methods = ['GET','POST'])
def index():
firstName = request.args.get('firstName')
lastName = request.args.get('lastName')
if request.method == "POST":
# Do stuff here
I just copied an application from my local dev env to prod env, and my data is not loading for my flask app instead its showing no blog posts right now...
I've verified the following:
db user has permission to table.
mysql is running
verified query again (works fine)
tried messing with MYSQL_DATABASE_HOST set to localhost and xx.xxx.xxx.xxx to no avail.
verified my import (from flask_mysqldb import MySQL is working fine for mysql) - it is
app.py:
from flask_mysqldb import MySQL
app = Flask(__name__)
app.secret_key = 'mysecret'
# mail server config
app.config['MAIL_SERVER'] = 'mailserver.net'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USE_SSL'] = True
app.config['MAIL_USERNAME'] = 'contact#mysite.com'
app.config['MAIL_PASSWORD'] = 'mypass'
# mysql config
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_PORT'] = '3306'
app.config['MYSQL_DB'] = 'mydb'
app.config['MYSQL_USER'] = 'myusr'
app.config['MYSQL_PASSWORD'] = 'mypass'
mysql = MySQL()
mysql.init_app(app)
c = mysql.connect().cursor()
#app.route('/', methods=('GET', 'POST'))
def email():
form = EmailForm()
c.execute("SELECT post_title, post_name, YEAR(post_date) as YEAR, MONTH(post_date) as MONTH FROM mydb.wp_posts WHERE post_status='publish' ORDER BY RAND() LIMIT 3")
blogposts = c.fetchall()
print(blogposts)
if request.method == 'POST':
if form.validate() == False:
return 'Please fill in all fields <p>Try Again</p>'
else:
msg = Message("Message from your visitor",
sender='contact#mysite.com',
recipients=['contact#mysite.com'])
msg.body = """
From: %s
""" % (form.email.data)
mail.send(msg)
return render_template('email_submit_thankyou.html')
elif request.method == 'GET':
return render_template('index.html', form=form, blogposts=blogposts)
if __name__ == '__main__':
app.run()
templates/index.html contains:
<ul>
{% for blogpost in blogposts %}
<li>{{blogpost[0]}}</li>
{% else %}
<li>no blog posts right now...</li>
{% endfor %}
<div class="clearL"> </div>
</ul>
I found a "slow" query in /var/log/mysql/mysql-slow.log:
# Time: 170101 16:34:32
# User#Host: myuser[myuser] # localhost [127.0.0.1]
# Query_time: 0.004649 Lock_time: 0.001712 Rows_sent: 3 Rows_examined: 53
SET timestamp=1483306472;
SELECT
post_title, post_name, YEAR(post_date) as YEAR, MONTH(post_date) as MONTH
FROM mydb.wp_posts WHERE post_status='publish' ORDER BY RAND() LIMIT 3;
Thus, What is going wrong here?
I'm quite new to python and flask. Basically I'm building a very basic web app that allows an admin to add/edit/delete a list of users. The list is display at the main menu and the admin can add/edit/delete first time around. However when I try to add/edit/delete a second time it doesn't work, also it fails if I redirect back to the main menu (where the list of users are) after an add/edit/delete. Any idea's what could be the issue?
from flask import Flask, url_for, request, render_template, redirect;
from app import app;
import pypyodbc;
myConnection = pypyodbc.connect('Driver={SQL Server};'
'Server=local'
'Database=All;'
'uid=sa;pwd=23232')
myCursor = myConnection.cursor()
myCursor.execute('SELECT * FROM Users')
rows = myCursor.fetchall();
for r in rows:
print(r)
#app.route('/')
def home():
"""Renders a sample page."""
createLink = "<a href='" + url_for("display") + "'>Admin</a>";
createLink2 = "<a href='" + url_for("user") + "'>User login</a>";
createLink3 = "<a href='" + url_for("delete") + "'>Delete</a>";
createLink4 = "<a href='" + url_for("edit") + "'>Edit</a>";
return """<html>
<head>
<title>First page</title>
</head>
<body>
<h1>Menu</h1>
<div>
""" + createLink + """
</div>
<div>
""" + createLink2 + """
</div>
<div>
""" + createLink3 + """
</div>
<div>
""" + createLink4 + """
</div>
</body>
</html>"""
#app.route('/display', methods=['GET', 'POST'])
def display():
if request.method == 'GET':
myCursor = myConnection.cursor()
myCursor.execute('SELECT * FROM Users')
rows = [dict(id=row[0], name=row[1], email=row[2], password=row[3]) for row in myCursor.fetchall()]
return render_template('DisplayAll.html', rows = rows)
else:
return"<h2>Error</h2>"
#app.route('/add', methods=['GET', 'POST'])
def add():
if request.method == 'GET':
return render_template('Add.html');
elif request.method == 'POST':
name = request.form['AddName'];
email = request.form['AddEmail'];
password = request.form['AddPassword'];
SQLCommand = ("INSERT INTO Users "
"(Name, Email, Pword) "
"VALUES (?,?,?)")
values = [name, email, password]
myCursor.execute(SQLCommand,values)
myConnection.commit();
#print("works")
#myCursor.execute('SELECT * FROM Users')
#rows = [dict(id=row[0], name=row[1], email=row[2], password=row[3]) for row in myCursor.fetchall()]
myConnection.close();
return ridirect(url_for('display'));
else:
return "<h2>Error</h2>";
#app.route('/delete', methods=['GET', 'POST'])
def delete():
if request.method == 'GET':
return render_template('Delete.html');
elif request.method == 'POST':
try:
DeleteId = request.form['DeleteId'];
SQLCommand = ("DELETE FROM Users "
"WHERE UsererId = "
+ DeleteId)
myCursor.execute(SQLCommand)
myConnection.commit();
#myCursor.execute('SELECT * FROM Users')
#rows = [dict(id=row[0], name=row[1], email=row[2], password=row[3]) for row in myCursor.fetchall()]
myConnection.close();
#return render_template("DisplayAll.html", rows = rows);
return redirect(url_for('display'));
except:
return "<h2>Doesn't work</h2>"
else:
return "<h2>Error</h2>";
#app.route('/edit', methods=['GET', 'POST'])
def edit():
if request.method == 'GET':
return render_template('Edit.html');
elif request.method == 'POST':
try:
Name = request.form['EditName'];
Email = request.form['EditEmail'];
Password = request.form['EditPassword'];
EditId = request.form['EditId'];
SQLCommand = ("UPDATE Users "
"SET Name = '" + Name +
"', Email = '" + Email +
"', Pword = '" + Password +
"' WHERE UsererId = "
+ EditId)
myCursor.execute(SQLCommand)
myConnection.commit();
#print("works")
#myCursor.execute('SELECT * FROM Users')
#rows = [dict(id=row[0], name=row[1], email=row[2], password=row[3]) for row in myCursor.fetchall()]
myConnection.close();
#return render_template("DisplayAll.html", rows = rows);
return redirect(url_for('display'));
except:
return "<h2>Doesn't work</h2>"
else:
return "<h2>Error</h2>";
First off, you have a typo in add() function.
This line:
return ridirect(url_for('display'));
should be
return redirect(url_for('display'));
Next, in display() you define myCursor and then you work with it. That is ok
myCursor = myConnection.cursor()
However, in functions add, delete and edit you are missing this definition, but you are still using it. You can not omit this definition, since the first one is valid only inside display() due to variable scope.
Try adding this definition to other functions as well.
If that does not work, it might be because you also need to make a new connection for every request, not just at the beginning of the file. Then, each function would begin with
myConnection = pypyodbc.connect('Driver={SQL Server};'
'Server=local'
'Database=All;'
'uid=sa;pwd=23232')
myCursor = myConnection.cursor()
Please, let us know if this works for you.
Note: I have just noticed you are actually closing the connection after adding/removing/editing with myConnection.close(). Therefore, you definitely need to reopen the connection upon each request with the code above.
I am getting an internal server error (500) when I try to access https://127.0.0.1:5000/deliveries_awaiting_pickup. When I try to access it, the terminal running the Flask server looks like this (after multiple attempts of trying to access it):
$ python minitwitLocal.py
table user already exists
* Running on https://127.0.0.1:5000/ (Press CTRL+C to quit)
hello
[]
127.0.0.1 - - [13/Apr/2015 21:26:57] "GET /deliveries_awaiting_pickup HTTP/1.1" 500 -
hello
[]
127.0.0.1 - - [13/Apr/2015 21:26:59] "GET /deliveries_awaiting_pickup HTTP/1.1" 500 -
I tried deleting the database and restarting the server, and it doesn't work. Also, the table is empty, but I expected it to render a blank page.
How do I get it to render the template? Thanks!
Most relevant part of minitwitLocal.py:
#app.route('/deliveries_awaiting_pickup')
def deliveries_awaiting_pickup():
if not g.user:
return redirect(url_for('public_timeline'))
print "hello"
orders=query_db('''select * from deliveries_awaiting_pickup''')
print orders
return render_template('deliveries_awaiting_pickup.html', orders)
deliveries_awaiting_pickup.html:
{% extends "layout.html" %}
{% block title %}
Deliveries Awaiting Pickup
{% endblock %}
{% block body %}
<h2>{{ self.title() }}</h2>
Deliveries Awaiting Pickup go here<br><br>
{% if orders %}
{% for order in orders %}
{% endfor %}
{% endif %}
{% endblock %}
minitwitLocal.py: (Mostly the "minitwit" example that Flask provides, with a few modifications)
# -*- coding: utf-8 -*-
"""
MiniTwit
~~~~~~~~
A microblogging application written with Flask and sqlite3.
:copyright: (c) 2010 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
import time
from sqlite3 import dbapi2 as sqlite3
from hashlib import md5
from datetime import datetime
from flask import Flask, request, session, url_for, redirect, \
render_template, abort, g, flash, _app_ctx_stack
from werkzeug import check_password_hash, generate_password_hash
import requests
import json
# configuration
DATABASE = 'minitwit.db'
PER_PAGE = 30
DEBUG = True
SECRET_KEY = 'development key'
#FOURSQUARE OAUTH2
FOURSQUARE_CLIENT_ID = 'XXXXXXX'
FOURSQUARE_CLIENT_SECRET = 'XXXXXX'
FOURSQUARE_REDIRECT_URI = "https://127.0.0.1:5000/authenticated"
FOURSQUARE_API_BASE = "https://api.foursquare.com/v2/"
# create our little application :)
app = Flask(__name__)
app.config.from_object(__name__)
app.config.from_envvar('MINITWIT_SETTINGS', silent=True)
def get_db():
"""Opens a new database connection if there is none yet for the
current application context.
"""
top = _app_ctx_stack.top
if not hasattr(top, 'sqlite_db'):
top.sqlite_db = sqlite3.connect(app.config['DATABASE'])
top.sqlite_db.row_factory = sqlite3.Row
return top.sqlite_db
#app.teardown_appcontext
def close_database(exception):
"""Closes the database again at the end of the request."""
top = _app_ctx_stack.top
if hasattr(top, 'sqlite_db'):
top.sqlite_db.close()
def init_db():
"""Creates the database tables."""
with app.app_context():
db = get_db()
with app.open_resource('schema.sql', mode='r') as f:
try:
db.cursor().executescript(f.read())
except sqlite3.OperationalError, msg:
print msg
db.commit()
def query_db(query, args=(), one=False):
"""Queries the database and returns a list of dictionaries."""
cur = get_db().execute(query, args)
rv = cur.fetchall()
return (rv[0] if rv else None) if one else rv
def get_user_id(username):
"""Convenience method to look up the id for a username."""
rv = query_db('select user_id from user where username = ?',
[username], one=True)
return rv[0] if rv else None
def format_datetime(timestamp):
"""Format a timestamp for display."""
return datetime.utcfromtimestamp(timestamp).strftime('%Y-%m-%d # %H:%M')
def gravatar_url(email, size=80):
"""Return the gravatar image for the given email address."""
return 'http://www.gravatar.com/avatar/%s?d=identicon&s=%d' % \
(md5(email.strip().lower().encode('utf-8')).hexdigest(), size)
#app.before_request
def before_request():
g.user = None
if 'user_id' in session:
g.user = query_db('select * from user where user_id = ?',
[session['user_id']], one=True)
#app.route('/add_new_delivery_order')
def add_new_delivery_order():
if not g.user:
return redirect(url_for('public_timeline'))
return render_template('add_new_delivery_order.html')
#app.route('/deliveries_awaiting_pickup')
def deliveries_awaiting_pickup():
if not g.user:
return redirect(url_for('public_timeline'))
print "hello"
orders=query_db('''select * from deliveries_awaiting_pickup''')
print orders
return render_template('deliveries_awaiting_pickup.html', orders)
#app.route('/')
def deliveries_in_progress():
if not g.user:
return redirect(url_for('public_timeline'))
return render_template('deliveries_in_progress.html')
#app.route('/completed_deliveries')
def completed_deliveries():
if not g.user:
return redirect(url_for('public_timeline'))
return render_template('completed_deliveries.html')
#app.route('/deliveries_waiting_for_bids')
def deliveries_waiting_for_bids():
if not g.user:
return redirect(url_for('public_timeline'))
return render_template('deliveries_waiting_for_bids.html')
#app.route('/authenticated')
def authenticated():
db = get_db()
CODE = request.args.get('code', '')
response = requests.get("https://foursquare.com/oauth2/access_token?client_id=" + FOURSQUARE_CLIENT_ID
+ "&client_secret=" + FOURSQUARE_CLIENT_SECRET + "&grant_type=authorization_code&redirect_uri="
+ FOURSQUARE_REDIRECT_URI +"&code=" + CODE + "&sort=newestfirst")
dict = json.loads(response.text)
db.execute('insert into access_token (user_id, access_token_text) values (?, ?)',
[session['user_id'], dict['access_token']])
db.commit()
return redirect(url_for('foursquare'), code=302)
#app.route('/foursquare')
def foursquare():
"""Shows your foursquare info. Or, if you have not authorized this app to connect to
foursquare, then it will redirect you to foursquare.
"""
if not g.user:
return redirect(url_for('public_timeline'))
result = query_db('select access_token_text from access_token where user_id = ?',
[session['user_id']], one=True)
if not result:
return redirect("https://foursquare.com/oauth2/authenticate?response_type=code&client_id=" + FOURSQUARE_CLIENT_ID + "&redirect_uri=" + FOURSQUARE_REDIRECT_URI,code=302)
else:
#Get info from foursquare
token = result['access_token_text']
response = requests.get(FOURSQUARE_API_BASE + "users/self/checkins?oauth_token=" + token +
"&v=20150326&m=foursquare")
dict = json.loads(response.text)
list = dict['response']['checkins']['items']
return render_template('foursquare.html', listOfCheckins=list)
#app.route('/')
def timeline():
"""Shows a users timeline or if no user is logged in it will
redirect to the public timeline. This timeline shows the user's
messages as well as all the messages of followed users.
"""
if not g.user:
return redirect(url_for('public_timeline'))
#Get info from foursquare
result = query_db('select access_token_text from access_token where user_id = ?',
[session['user_id']], one=True)
if result:
token = result['access_token_text']
response = requests.get(FOURSQUARE_API_BASE + "users/self/checkins?oauth_token=" + token +
"&v=20150326&m=foursquare")
dict = json.loads(response.text)
item = dict['response']['checkins']['items'][0]
return render_template('timeline.html',messages=query_db('''
select message.*, user.* from message, user
where message.author_id = user.user_id and (
user.user_id = ? or
user.user_id in (select whom_id from follower
where who_id = ?))
order by message.pub_date desc limit ?''',
[session['user_id'], session['user_id'], PER_PAGE]),checkin=item)
return render_template('timeline.html',messages=query_db('''
select message.*, user.* from message, user
where message.author_id = user.user_id and (
user.user_id = ? or
user.user_id in (select whom_id from follower
where who_id = ?))
order by message.pub_date desc limit ?''',
[session['user_id'], session['user_id'], PER_PAGE]),checkin=None)
#app.route('/public')
def public_timeline():
"""Displays the latest messages of all users."""
return render_template('timeline.html', messages=query_db('''
select message.*, user.* from message, user
where message.author_id = user.user_id
order by message.pub_date desc limit ?''', [PER_PAGE]))
#app.route('/<username>')
def user_timeline(username):
"""Display's a users tweets."""
profile_user = query_db('select * from user where username = ?',
[username], one=True)
if profile_user is None:
abort(404)
followed = False
if g.user:
followed = query_db('''select 1 from follower where
follower.who_id = ? and follower.whom_id = ?''',
[session['user_id'], profile_user['user_id']],
one=True) is not None
#Get info from foursquare
result = query_db('select access_token_text from access_token where user_id = ?',
[profile_user['user_id']], one=True)
if result:
token = result['access_token_text']
response = requests.get(FOURSQUARE_API_BASE + "users/self/checkins?oauth_token=" + token +
"&v=20150326&m=foursquare")
dict = json.loads(response.text)
item = dict['response']['checkins']['items'][0]
return render_template('timeline.html', messages=query_db('''
select message.*, user.* from message, user where
user.user_id = message.author_id and user.user_id = ?
order by message.pub_date desc limit ?''',
[profile_user['user_id'], PER_PAGE]), followed=followed,
profile_user=profile_user, checkin=item)
#app.route('/<username>/follow')
def follow_user(username):
"""Adds the current user as follower of the given user."""
if not g.user:
abort(401)
whom_id = get_user_id(username)
if whom_id is None:
abort(404)
db = get_db()
db.execute('insert into follower (who_id, whom_id) values (?, ?)',
[session['user_id'], whom_id])
db.commit()
flash('You are now following "%s"' % username)
return redirect(url_for('user_timeline', username=username))
#app.route('/<username>/unfollow')
def unfollow_user(username):
"""Removes the current user as follower of the given user."""
if not g.user:
abort(401)
whom_id = get_user_id(username)
if whom_id is None:
abort(404)
db = get_db()
db.execute('delete from follower where who_id=? and whom_id=?',
[session['user_id'], whom_id])
db.commit()
flash('You are no longer following "%s"' % username)
return redirect(url_for('user_timeline', username=username))
#app.route('/add_message', methods=['POST'])
def add_message():
"""Registers a new message for the user."""
if 'user_id' not in session:
abort(401)
if request.form['text']:
db = get_db()
db.execute('''insert into message (author_id, text, pub_date)
values (?, ?, ?)''', (session['user_id'], request.form['text'],
int(time.time())))
db.commit()
flash('Your message was recorded')
return redirect(url_for('timeline'))
#app.route('/login', methods=['GET', 'POST'])
def login():
"""Logs the user in."""
if g.user:
return redirect(url_for('timeline'))
error = None
if request.method == 'POST':
user = query_db('''select * from user where
username = ?''', [request.form['username']], one=True)
if user is None:
error = 'Invalid username'
elif not check_password_hash(user['pw_hash'],
request.form['password']):
error = 'Invalid password'
else:
flash('You were logged in')
session['user_id'] = user['user_id']
return redirect(url_for('timeline'))
return render_template('login.html', error=error)
#app.route('/register', methods=['GET', 'POST'])
def register():
"""Registers the user."""
if g.user:
return redirect(url_for('timeline'))
error = None
if request.method == 'POST':
if not request.form['username']:
error = 'You have to enter a username'
elif not request.form['email'] or \
'#' not in request.form['email']:
error = 'You have to enter a valid email address'
elif not request.form['password']:
error = 'You have to enter a password'
elif request.form['password'] != request.form['password2']:
error = 'The two passwords do not match'
elif get_user_id(request.form['username']) is not None:
error = 'The username is already taken'
else:
db = get_db()
db.execute('''insert into user (
username, email, pw_hash) values (?, ?, ?)''',
[request.form['username'], request.form['email'],
generate_password_hash(request.form['password'])])
db.commit()
flash('You were successfully registered and can login now')
return redirect(url_for('login'))
return render_template('register.html', error=error)
#app.route('/api/receive_text', methods=['GET', 'POST'])
def receive_text():
"""receive a text message from Twilio."""
return
#app.route('/logout')
def logout():
"""Logs the user out."""
flash('You were logged out')
session.pop('user_id', None)
return redirect(url_for('public_timeline'))
# add some filters to jinja
app.jinja_env.filters['datetimeformat'] = format_datetime
app.jinja_env.filters['gravatar'] = gravatar_url
if __name__ == '__main__':
init_db()
app.run(host='127.0.0.1', debug=False, port=5000, ssl_context=('/Users/l/Development/Certificates/server.crt', '/Users/l/Development/Certificates/server.key'))
schema.sql:
create table user (
user_id integer primary key autoincrement,
username text not null,
email text not null,
pw_hash text not null
);
create table follower (
who_id integer,
whom_id integer
);
create table message (
message_id integer primary key autoincrement,
author_id integer not null,
text text not null,
pub_date integer
);
create table access_token (
user_id integer not null,
access_token_text text not null
);
create table completed_deliveries (
flower_order text not null,
shipping_address text not null,
total_cost real not null,
driver_name text not null,
estimated_delivery_time integer not null,
reputation text not null,
charge real not null,
arrival_estimation text not null,
picked_up_time text not null,
actual_arrival_time text not null
);
create table deliveries_in_progress (
flower_order text not null,
shipping_address text not null,
total_cost real not null,
driver_name text not null,
estimated_delivery_time integer not null,
reputation text not null,
charge real not null,
arrival_estimation text not null,
picked_up_time text not null
);
create table deliveries_awaiting_pickup (
flower_order text not null,
shipping_address text not null,
total_cost real not null,
driver_name text not null,
estimated_delivery_time integer not null,
reputation text not null,
charge real not null,
arrival_estimation text not null
);
create table deliveries_waiting_for_bids (
flower_order text not null,
shipping_address text not null,
total_cost real not null
);
On this line of deliveries_awaiting_pickup():
return render_template('deliveries_awaiting_pickup.html', orders)
I was supposed to name each variable explicitly, like this:
return render_template('deliveries_awaiting_pickup.html', orders=orders)
Then it worked.
Also, I noticed my debug was set to false accidentally. I set it to true like below. Since it was false, it was only giving "internal server error" and not a detailed debug report.
app.run(host='127.0.0.1', debug=True, port=5000, ssl_context=('/Users/l/Development/Certificates/server.crt', '/Users/l/Development/Certificates/server.key'))