I execute the following python script in VScode
can extract mysql data and pass to .html to show as webpage's contant
# get_sql_where_02.py
import mysql.connector
import webbrowser
import time
import pymysql
from flask import Flask,render_template,request
app = Flask(__name__)
mydb = mysql.connector.connect(
host="196.168.1.141",
user="Main_root",
password="password_123",
database="database_db",
auth_plugin='mysql_native_password'
)
mycursor = mydb.cursor()
# mycursor.execute("SELECT P_TITLE,P_DESC FROM webpage WHERE P_ID = 'en_1-01'")
mycursor.execute("SELECT P_TITLE,P_DESC FROM webpage WHERE P_ID = "+request.args["ProductID"])
myresult = mycursor.fetchall()
print(myresult) # does get the result I want
#app.route('/')
def index():
return render_template("index_test_0203.html", myresult = myresult)
if __name__ == "__main__":
app.run(debug=True)
index_test_0203.html
<!DOCTYPE html>
<html>
<body>
<p> this is {{myresult}}</p>
</body>
</html>
the error message
Traceback (most recent call last):
File "C:\Users\chuan\OneDrive\Desktop\custom_header_pra_1.12\test_showing_content_middle\get_sql_where_02.py", line 22, in <module>
mycursor.execute("SELECT P_TITLE,P_DESC FROM webpage WHERE P_ID = "+request.args["ProductID"])
File "C:\Users\chuan\AppData\Local\Programs\Python\Python310\lib\site-packages\werkzeug\local.py", line 316, in __get__
obj = instance._get_current_object() # type: ignore[misc]
File "C:\Users\chuan\AppData\Local\Programs\Python\Python310\lib\site-packages\werkzeug\local.py", line 513, in _get_current_object
raise RuntimeError(unbound_message) from None
RuntimeError: Working outside of request context.
This typically means that you attempted to use functionality that needed
an active HTTP request. Consult the documentation on testing for
information about how to avoid this problem.
I already read through the discussion and tutorial but don't know how to fix in my case
you can't use request there, because the line mycursor.execute("SELECT P_TITLE,P_DESC FROM webpage WHERE P_ID = "+request.args["ProductID"]) is executed in the script startup. But you cannot access the request there.
You can access request after any request received.
use like this
#app.route('/')
def index():
mycursor = mydb.cursor()
# mycursor.execute("SELECT P_TITLE,P_DESC FROM webpage WHERE P_ID = 'en_1-01'")
mycursor.execute("SELECT P_TITLE,P_DESC FROM webpage WHERE P_ID = "+request.args["ProductID"])
myresult = mycursor.fetchall()
print(myresult) # does get the result I want
return render_template("index_test_0203.html", myresult = myresult)
and remove these lines from the above place
Related
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)
Am a beginner to AWS services and python, i used below code in lambda to connect
RDS and invoke this in API gateway
After Successful execution of below code it is returning null.
#!/usr/bin/python
import sys
import logging
import pymysql
import json
rds_host="host"
name="name"
password="password"
db_name="DB"
port = 3306
def save_events(event):
"""
This function fetches content from mysql RDS instance
"""
result = []
conn = pymysql.connect(rds_host, user=name, passwd=password,
db=db_name,connect_timeout=30)
with conn.cursor() as cur:
cur.execute("SELECT * FROM exercise WHERE bid = '1'")
for row in cur:
result.append(list(row))
print ("Data from RDS...")
print (result)
cur.close()
print(json.dumps({'bodyParts':result}))
def lambda_handler(event, context):
save_events(event)
As pointed out in a comment by #John Gordon, you need to return something from your lambda_handler function.
It should be something like:
def lambda_handler(event, context):
save_events(event)
return {
"statusCode": 200,
"result": "Here is my result"
}
Additionally, I don't see any return statement from save_events either.
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().