I am trying to do a GET request which should print a specific row from my database depending on what arguments are set. The argument should be a name of a course and I want it to get all data from the selected course. It might be a bit easier to explain this as a SQL query. The query could look like this "SELECT * FROM courselist WHERE course='D0024E';"
where "course".
I have managed to do a fetchall() and receive all rows from a specific table, but I have not managed to get the parameters working correctly so I can get information from a specific course.
from flask import Flask
from flask import render_template
import requests
from flask import request
from flask import jsonify
import mysql.connector
app = Flask(__name__)
mydb = mysql.connector.connect(user='Mille',
auth_plugin='mysql_native_password',
password='jagheter12',
host='localhost',
database='paraplyet')
#app.route('/')
def index():
return render_template("index2.html")
#app.route('/courses', methods= ["GET"])
def getStudentInCourse():
myCursor2 = mydb.cursor()
query2 = ("SELECT * FROM paraplyet.kursinfo")
myCursor2.execute(query2)
myresult2 = myCursor2.fetchall()
return jsonify(myresult2)
if __name__ == '__main__':
app.run()
You need to update your route url to receive parameters
#app.route('/courses/<course_code>', methods= ["GET"])
def getStudentInCourse(course_code):
Then you can use this course_code to filter result.
Actually there are several points where your code(s) can fail, because establishing a correct front-end back-end chain in Flask is a little tricky (but worth it at the end).
You have a counter part front-end HTML code where you start your request with the proper variable, like "course" in your example, which may looks like this:
<form action="/courses" method="post">
<input>
<button type="submit"></button>
</form>
Then Flask as back-end will get this variable(parameter) as part of your query string as part of the URL string. You can retrieve this parameter in the form:
course = request.form.get('course')
To achieve it you have to add "POST" the view's methods, as it handles only "GET"-s as default.
#app.route('/courses', methods=["GET", "POST"])
Then you can use this variable as you want to complete your back-end operations:
query2 = ("SELECT * FROM courseInfo where courseCode = '" + course + "';")
those results then you can pass it back to the front-end via:
return jsonify(myresult2)
Your python/flask code should be some like as follows:
from flask import Flask
from flask import render_template
import requests
from flask import request
from flask import jsonify
import mysql.connector
app = Flask(__name__)
mydb = mysql.connector.connect(user='Mille',
auth_plugin='mysql_native_password',
password='jagheter12',
host='localhost',
database='paraplyet')
#app.route('/')
def index():
return render_template("index2.html")
#app.route('/courses', methods= ["GET", "POST"])
def getStudentInCourse():
if request.method == "POST" and request.form.get('course') != '':
myCursor2 = mydb.cursor()
course = request.form.get('course')
query2 = ("SELECT * FROM courseInfo where courseCode = '" + course + "';")
myresult2 = myCursor2.execute(query2)
return jsonify(myresult2)
if __name__ == '__main__':
app.run()
Related
I have a app Flask. I want to use Rest api for insert data to Database. I have a app.pyfile and api.py file. I want to write a post method in api.py. I want to get information from client using add.html file and post it to api. then api this information add to Database. I use pyodbc for connect to SQL Server Database.in this Database, there is a table tbl_product with columns P_ID,title,count,price and active. I don't know, how do it. When I run python api.py on http://localhost:5000/add, I see { "message": "The method is not allowed for the requested URL."}. Also, When I run python app.py, on http://localhost:8080/addI see Method Not Allowed. The method is not allowed for the requested URL .
Can you help me?
my app.py file is:
from flask import Flask,render_template,url_for, request, redirect, flash, jsonify,json
import pyodbc
import requests
from api import ProductAdd
app = Flask(__name__)
app.secret_key= "flash_message"
# creating connection Object which will contain SQL Server Connection
conn = pyodbc.connect('Driver={SQL Server};'
'Server=TABRIZIYAN;'
'Database=market_DB;'
'Trusted_Connection=yes;')
cursor = conn.cursor()
#app.route('/add')
def add():
if request.method =='POST':
productDetails= request.form
title= productDetails['title']
count=productDetails['count']
price= productDetails['price']
active= productDetails['active']
create_row_data = { 'title':str(title), 'count':str(count),
'price':str(price), 'active':str(active) }
info = requests.post('http://localhost:5000/add', data= create_row_data)
return info.text #return(render_template('product.html'))
else:
return (render_template('add.html'))
if __name__=='__main__':
app.run(debug=True, port="8080")
my api.py file is:
from flask import Flask, request, render_template,url_for, redirect, flash
from flask_restplus import Api, Resource
from flask import jsonify
import pyodbc
import requests
flask_app = Flask(__name__)
api = Api(app=flask_app)
class ProductAdd(Resource):
def post(self):
productDetails= request.json
title= productDetails['title']
count=productDetails['count']
price= productDetails['price']
active= productDetails['active']
cursor = conn.cursor()
cursor.execute(" INSERT INTO Tbl_product(title, count, price, active) VALUES(?, ?, ?, ?)
",(title,count,price,active))
conn.commit()
resp = jsonify('User added successfully!')
resp.status_code = 200
return resp
api.add_resource(ProductAdd , '/add')
if __name__ == '__main__':
flask_app.run(debug=True)
Hi I am trying to create a customer feedback form; I have managed to create the pages I need, but I am having difficulty connecting my app to my SQLite3 database.
So in my code python code I am trying to collect the data from the customer feedback form and hold it in a database.
In the feedback form they will be prompted to input their name, choose some answers from a drop-box selection, and to write a comment at the end.
The answers will be housed in the database (for future reference - like reports etc) and the user will be redirected back to the home page where they will be able to see their name & comment (taken from the feedback form).
I have watched tutorials on sqlite3 which was kind of easy to understand & execute (a lot easier for me than MySQL) but I'm missing something because it won't connect to my database.
my python flask code:
from flask import Flask, render_template, redirect, url_for, request, session, flash, g
from functools import wraps
import sqlite3
app = Flask(__name__)
app.secret_key = "random_character_generator" # this would be random or anything the developer wants
app.database = "gymdatabase.db"
conn = sqlite3.connect(app.database)
c = conn.cursor()
def connect_db():
return sqlite3.connect(app.database)
#app.route('/')
def home():
g.db = connect_db()
cur = g.db.execute('select * from posts')
posts = [dict(name=row[0], welcome=row[1], equipment=row[2], cleanliness=row[3], interaction=row[4], comments=row[5], contact=row[6]) for row in cur.fetchall()]
g.db.close()
return render_template('gym_index.html', posts=posts)
#app.route('/feedback', methods=['POST'])
def feedback():
return render_template('gym_feedback.html')
#app.route('/process', methods=['GET', 'POST'])
def process():
g.db = connect_db()
name = request.form['name']
welcome = request.form['welcome']
equipment = request.form['equipment']
cleanliness = request.form['cleanliness']
interaction = request.form['interaction']
comment = request.form['comment']
contact = request.form['yes_no']
conn.commit()
cur = g.db.execute(select * from posts)
posts = [dict(name=row[0], welcome=row[1], equipment=row[2], cleanliness=row[3], interaction=row[4], comments=row[5], contact=row[6]) for row in cur.fetchall()]
g.db.close()
return redirect(url_for('home', posts=posts))
When I try to submit a feedback form I get:
sqlite3.ProgrammingError: SQLite objects created in a thread can only be used in that same thread.
I can upload the html file on request; I'm not too sure if I have space to do so along with my python file.
I think that this is due to your line conn.commit() in your process() function. You declare conn = sqlite3.connect(app.database) when Flask first starts, but each function defined with the #app.route(...) function decorator gets called in a different thread in response to HTTP requests (as defined in the aforementioned function decorator). You probably want to do something like this:
#app.route('/process', methods=['GET', 'POST'])
def process():
...
db = connect_db()
cur = db.cursor()
cur.execute("select * from posts")
results = cur.fetchall()
...
You can see this link for further documentation: https://docs.python.org/2/library/sqlite3.html
I can edit my answer if you provide more context regarding where your code is failing.
i need to do some manipulation with string which i get from WTForm, here is my code:
from app import app
from app.forms import InputTextForm, OutputTextForm
from flask import render_template, request
import re
def work_txt(text):
textlookfor = '[0-9]+\n\d+:\d+:\d+,\d+ --> \d+:\d+:\d+,\d+'
result = re.sub(textlookfor, '', text)
return result
#app.route('/elmucon', methods=['GET', 'POST'])
def elmucon():
form = InputTextForm()
if form.validate_on_submit():
t = request.form.to_dict()
text = t['text']
result = work_txt(text)
return render_template('elmucon_ready.html', form=form, text=result)
function work_txt() works fine outside the route, but with my code i recieve the same string which was inputted in Form. What sould i do to make this work? thanks!
I have a Flask website with a MySQL backend. I have a table called, users. It has two columns: username and name and one record:
name username
Jim testuser123
When a user clicks the button on the website, it updates the record to set the name to Bob then print all records where name = 'Bob'. Yet, it returns no results. If I refresh the connection before re-querying, then it does return one result as it should. Does the mdb.connect object cache data? How could it not be returning the correct results?
init.py:
import pandas as pd
import MySQLdb as mdb
from flask import Flask, render_template, request
def sql_con():
return mdb.connect(host='myhost', port=3306, user='root', passwd='root', db='db', use_unicode=True, charset="utf8")
app = Flask(__name__)
def update_record():
con = sql_con()
cur = con.cursor()
sql_string= "Update users set name = 'Bob' where username = 'testuser123'"
cur.execute(sql_string)
con.commit()
#app.route('/', methods=['GET', 'POST'])
def myroute():
con = sql_con()
if request.method == 'POST':
update_record()
print pd.read_sql("select * from users where name = 'Bob'", con=con)
return render_template('1.html')
app.run( debug=True, port=5050)
1.html
<html>
<body>
<form method="POST">
<button id="mybutton" name='btn' value="mybutton">Submit Data</button>
</form>
</body>
For this code to print one result, I must add con=sql_con() right after I call the update(), but before the print statement. Why is that?
In general it is a good practice to use an ORM binding (i.e. Falsk-SQLAlchemy) with web frameworks (manages connection pools, automates commit/rollback, ...) even if an ORM seems overkill for a simple application.
Otherwise, avoid using multiple connections to the same database in the same request if you prefer manage this at low level (database connections).
Try this instead:
import pandas as pd
import MySQLdb as mdb
from flask import Flask, render_template, request
def sql_con():
return mdb.connect(host='myhost', port=3306, user='root', passwd='root', db='db', use_unicode=True, charset="utf8")
app = Flask(__name__)
def update_record(con):
cur = con.cursor()
sql_string= "Update users set name = 'Bob' where username = 'testuser123'"
cur.execute(sql_string)
con.commit()
#app.route('/', methods=['GET', 'POST'])
def myroute():
con = sql_con()
if request.method == 'POST':
update_record(con)
print pd.read_sql("select * from users where name = 'Bob'", con=con)
return render_template('1.html')
app.run( debug=True, port=5050)
If you want to scale a real app based on such solution, you should consider pulling an opened connection from a global connections pool. Creating a new db connection (at each HTTP request) may be time expensive.
I'm trying to set up a flask server which adds data/users to a mongoDB database.
I set up the DB (using mongo shell) like so:
>use dbname
switched to dbname
>db.users.save( {username:"user", password:"pass"} )
WriteResult({ "nInserted" : 1 })
And confirm the data is written with db.users.find().
I added a mongo user like so:
>use admin
switched to db admin
>var w = { user:"user", roles:["readWriteAnyDatabase"], pwd:"password"}
>db.createUser(w)
My config.py looks like:
...
MONGO_URI = 'mongodb://user:password#localhost:27017/dbname'
and my python looks like this:
from flask import render_template, flash, redirect, Flask
from app import app
from flask_pymongo import PyMongo
from .forms import LoginForm
appp = Flask(__name__)
mongo = PyMongo(appp)
#app.route('/login', methods=['GET', 'POST'])
def login:
form = LoginForm()
if form.validate_on_submit():
user = {"username": form.username.data,
"password": form.password.data}
post_id = mongo.db.users.insert_one(user)
flash('Login req: u=%s, p=%s' % (form.username.data, str(form.remember_me.data)))
return redirect('/index')
I thought all was well but I got this when I tried it out:
It appears to say something about the config_prefix? The docs say config_prefix is set to 'MONGO' by default and in my config the prefix is mongo. I must be missing something SOS
Kostas was correct.
I changed:
appp = Flask(__name__)
mongo = PyMongo(appp)
to simply
mongo = PyMongo(app)
You have a typo in
#app.route('/login', methods=['GET', 'POST'])
PyMongo uses current_app variable from flask which refers to the application instance handling the request. In this case app handles the request but appp has the configuration. So this line should become
#appp.route('/login', methods=['GET', 'POST'])