I am trying to make webpage with flask which displays data from mysql table. My code is:
#app.route("/")
def index():
cursor = db.cursor()
cursor.execute('SELECT * from private')
privateDB = cursor.fetchall()
cursor.close()
return render_template('index.html', t=privateDB)
However whenever I refresh the page I get old data, it doesn't fetch new updated data. How to fix? Thank you.
Try it with this code
#app.route("/")
def index():
connection = mysql.connect()
cursor = connection.cursor()
cursor.execute("SELECT * from private")
data = cursor.fetchall()
return render_template('index.html', data=data)
Related
Is there a way I can display a SQL table in HTML and CSS using flask? If so please leave the code down below, or make a GitHub directory so I can have a look!
Here is what I used in my older projects while using Microsoft SQL.
###### IMPORTED LIBRARIES ######
from flask import render_template, Flask
import pyodbc
###### SQL CONNECTION ######
connection = pyodbc.connect('Driver={SQL Server};'
'Server=DESKTOP-NP0I4J5\SQLEXPRESS;'
'Database=REPLICATED_STORAGE;'
'Trusted_Connection=yes;')
cursor = connection.cursor()
cursor.execute("SELECT * FROM FRUITS")
data = cursor.fetchall()
###### FLASK SERVER ######
headings = ("COLOR", "TYPE", "NAME", "WEIGHT")
id = 80809915
app = Flask(__name__)
#app.route('/')
def index():
return render_template("table.html", headings=headings, data=data)
if (__name__ == '__main__'):
app.run()
Please help:
I am trying to create a webservice in flask (this is my first time) that takes a str, queries an external mysql database and returns 1 row as json.
I am sure there are other of issues with the code below (all suggestions much appreciated), but I cannot even see them yet, because when I try to access example.com/webservice/vin/ I get "Internal Server Error
The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application." from nginx.
PLease can someone guide me where I am going wrong?
example.com return Hello from app_name running in docker...yayy. Its the other route that isnt working.
from flask.ext.mysqldb import MySQL
import json
app.config['MYSQL_HOST'] = 'xxx'
app.config['MYSQL_USER'] = 'xxx'
app.config['MYSQL_PASSWORD'] = 'xxx'
app.config['MYSQL_DB'] = 'xxx'
mysql = MySQL(app)
#app.route("/")
def index():
# Use os.getenv("key") to get environment variables
app_name = os.getenv("APP_NAME")
if app_name:
return f"Hello from {app_name} running in a Docker container behind Nginx!"
return "Hello from Flask"
#app.route('/webservice/vin/<vin>', methods=['GET'])
def get_vehicle(vin):
sql = "SELECT * FROM `table` where column = '(%s )';" %(vin)
cur = mysql.connection.cursor()
cur.execute(sql)
row_headers=[x[0] for x in cur.description] #this will extract row headers
rv = cur.fetchall()
json_data=[]
for result in rv:
json_data.append(dict(zip(row_headers,result)))
return json.dumps(json_data)
from flask import make_response
#app.errorhandler(404)
def not_found(error):
return make_response(jsonify({'error': 'Not found'}), 404)
I'm trying to use Bottle framework in python with sqlite3. Then I made a Todo List application but when I tried to post a data at the first time the error happened differently from above. The second time 'database is locked' happened.
Can anyone help?
#_*_ coding:utf-8- _*_
import os, sqlite3
from bottle import route, run, get, post, request, template
#sqlite from here----------------
dbname = "todo.db"
connection = sqlite3.connect(dbname)
dbcontrol = connection.cursor()
#Making table from here--------------------
create_table = '''create table todo_list (todo text)'''
#route("/")
def index():
todo_list = get_todo()
return template("index", todo_list=todo_list)
I think I need more specific code here.
#route("/enter", method=["POST"])
def enter():
conn = sqlite3.connect("todo.db")
todo=request.POST.getunicode("todo_list")
save_todo(todo)
return redirect("/")
def save_todo(todo):
connection = sqlite3.connect('todo.db')
dbcontrol = connection.cursor()
insert="insert into todo_list(todo) values('{0}')".format(todo)
dbcontrol.execute(insert)
connection.commit()
def get_todo():
connection=sqlite3.connect('todo.db')
dbcontrol = connection.cursor()
select = "select * from todo_list"
dbcontrol.execute(select)
row = dbcontrol.fetchall()
return row
run(host="localhost", port=8080, debug=True)
Install the bottle-sqlite with:
$ pip install bottle-sqlite
An example from the plugin
import bottle
app = bottle.Bottle()
plugin = bottle.ext.sqlite.Plugin(dbfile='/tmp/test.db')
app.install(plugin)
#app.route('/show/:item')
def show(item, db):
row = db.execute('SELECT * from items where name=?', item).fetchone()
if row:
return template('showitem', page=row)
return HTTPError(404, "Page not found")
Important notes from the plugin
Routes that do not expect a db keyword argument are not affected.
The connection handle is configured so that sqlite3.Row objects can be
accessed both by index (like tuples) and case-insensitively by name.
At the end of the request cycle, outstanding transactions are
committed and the connection is closed automatically. If an error
occurs, any changes to the database since the last commit are rolled
back to keep the database in a consistent state.
Also take a look at Configuration section.
First, I understand the value of using ORM solutions, and will use SQL-Alchemy later.
I have installed Flask and am using flask-mysql.
I do not know how to get the results for a SQL "desc " command.
Here is the code I'm working with:
from flask import Flask, render_template, request, redirect, jsonify
import requests
from flaskext.mysql import MySQL
app = Flask(__name__)
#app.route("/")
def main():
return render_template('login.html')
#app.route("/login", methods=['POST'])
def login():
#username = request.form['username'] #not using the form fields yet
#password = request.form['password']
mysql = MySQL()
app.config['MYSQL_DATABASE_USER'] = '<my user here>'
app.config['MYSQL_DATABASE_PASSWORD'] = '<password here>'
app.config['MYSQL_DATABASE_DB'] = '<database name here>'
app.config['MYSQL_DATABASE_HOST'] = '<database server IP address here>'
mysql.init_app(app)
conn = mysql.connect()
cursor = conn.cursor()
#cursor = mysql.connection.cursor() #invalid code, at least for this version of flask-mysql
cursor.execute("desc user;")
result = jsonify(cursor.fetchall())
#row = cursor.fetchone()
return "<!DOCTYPE html><html><body>" + str(result)+ "</body></html>"
if __name__ == "__main__":
app.run()
It appears to be connecting to the database, logging in, and sending the desc command OK because result's contents are "Response 268 bytes [200 OK]" (can see that by looking at the page source code after getting the response in the browser).
Is there any way to get the results (table description) and not just an "OK I ran this command"?
Thank you.
I suppose you would like to get all records and sort them in desc order. You may try this.
from flask_mysqldb import MySQL
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] =
app.config['MYSQL_DB'] =
app.config['MYSQL_CURSORCLASS'] = 'DictCursor'
# initialize mysql
mysql = MySQL(app)
...
#app.route('/posts')
def posts():
cur = mysql.connection.cursor()
result = cur.execute('SELECT * FROM posts ORDER BY postdate DESC ')
posts = cur.fetchall()
if result > 0:
return render_template('posts.html', posts=posts)
else:
message = 'I shouldn't find any post'
return render_template('posts.html', message=message)
cur.close
I am trying to test by mocking a database query, but receiving an error:
Asssertion error:AssertionError: Expected call: execute()
Not called
and create_table() not defined.
I want to execute() to be called and use create_table() to return response for asserting against pre-defined values.
app.py
from flask import Flask,g
#app.before_request
def before_request():
g.db = mysql.connector.connect(user='root', password='root', database='mysql')
def create_table():
try:
cur = g.db.cursor() #here g is imported form Flask module
cursor.execute ('CREATE TABLE IF NOT EXISTS Man (id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, name VARCHAR(40)')
data = dict(Table='Man is created')
resp = jsonify(data)
cursor.close()
return resp
test.py
import unittest
from app import *
from mock import patch
class Test(unittest.TestCase):
def test_create(self):
with patch("app.g") as mock_g:
mock_g.db.cursor()
mock_g.execute.assert_called_with()
resp = create_table()
assertEqual(json, '{"Table":"Testmysql is created","Columns": ["id","name","email"]}')
What am I doing wrong?Can someone please tell me how to fix it
I believe you need to add your changes before closing the cursor, or the execute won't occur. Try adding cursor.commit() before (or instead of) cursor.close().