So I have just started studying on flask and am just moving to database with flask. I have a database "testdatabase.db" with a table named "Students". What I want to do is. When i pass a username onto the url I need the details of the that specific row.
Here is my python code
from flask import Flask, render_template, request
import sqlite3
conn = sqlite3.connect('testdatabase.db')
c = conn.cursor()
app = Flask(__name__)
#app.route("/students/<name>")
def students(name):
return jam()
def jam():
c.execute("select * from students where name = '" + name + "'")
print(c.fetchall())
conn.close()
if __name__ == "__main__":
app.run(debug=True)
The error being shown is that name 'name' is not defined. How do I define the name to be passed to the url?
Name is being passed correctly to the url
#app.route("/students/<name>")
def students(name):
return jam()
Your only problem is that you are not passing it to the jam function
solution
#app.route("/students/<name>")
def students(name):
return jam(name)
def jam(name):
c.execute("select * from students where name = '" + name + "'")
print(c.fetchall())
conn.close()
# Return the data jsonfied.
There is no variable 'name' in jam, try:
from flask import Flask, render_template, request
import sqlite3
conn = sqlite3.connect('testdatabase.db')
c = conn.cursor()
app = Flask(__name__)
#app.route("/students/<name>")
def students(name):
return jam(name)
def jam(name):
c.execute("select * from students where name = '" + name + "'")
print(c.fetchall())
conn.close()
if __name__ == "__main__":
app.run(debug=True)
Related
This question already has answers here:
Flask view return error "View function did not return a response"
(3 answers)
Closed last year.
I inserted new record from the form, the data will be successfully added into database, but it will show an error page "INTERNAL SERVER ERROR", if I manually back to my form page and refresh i can see the inserted data, but i want it refresh it self and don't show the error page, how to do that?
from flask import Flask, render_template, request
import sqlite3
app = Flask(__name__)
db_name = 'crm.db'
#app.route('/')
def index():
title = "主页"
return render_template("index.html", title = title)
#app.route('/company', methods = ['POST','GET'])
def company():
if request.method == 'GET':
title = "公司"
company_db = query_company()
return render_template("company.html", title = title, company_db = company_db)
else:
insert_company()
def query_company():
connection = sqlite3.connect(db_name)
c = connection.cursor()
c.execute("""SELECT * FROM company""")
company_db = c.fetchall()
return company_db
def insert_company():
connection = sqlite3.connect(db_name)
c = connection.cursor()
query = 'INSERT INTO company(company_full_name, company_short_name) VALUES(?,?)'
cfn = request.form.get("cfn")
csn = request.form.get("csn")
company_info = (cfn,csn)
c.execute(query, company_info)
connection.commit()
connection.close()
if __name__ == '__main__':
app.run(debug = True)
Change the company function to ...
def company():
if request.method == 'POST':
insert_company()
title = "公司"
company_db = query_company()
return render_template("company.html", title = title, company_db = company_db)
This way the new data will first be inserted and then all rows will be automatically refreshed
I have a simple Flask app. The app connects with a database of movie reviews. I built a function to retrieve data which takes a max_count argument. but for some reason, I can only pass a number smaller than 10. The app works fine if I pass 3 or 9. Here is my code:
from flask import Flask, request
import requests
import psycopg2
from psycopg2.extras import RealDictCursor
import json
app = Flask(__name__)
#app.route('/')
def home():
return "Hello!"
#app.route('/get_total_data_count/<label>', methods=['GET'])
def get_total_data_count(label):
connection = psycopg2.connect(user="barmej", password="password", host="127.0.0.1", port="5432", database="labeling")
cursor = connection.cursor()
try:
if label == 'positive':
cursor.execute("SELECT * FROM data_labeling WHERE label_number = 0 limit 100;")
elif label == 'negative':
cursor.execute("SELECT * FROM data_labeling WHERE label_number = 1 limit 100;")
elif label == 'all':
cursor.execute("SELECT * FROM data_labeling;")
return "The count is " + str(cursor.rowcount)
except:
return "Error! type: positive, negative or all"
cursor.close()
connection.close()
#app.route('/get_data', methods=['GET'])
def get_data_test():
try:
connection = psycopg2.connect(user="barmej", password="password", host="127.0.0.1", port="5432", database="labeling")
cursor = connection.cursor()
max_count = request.args.get('max_count')
sort_order = request.args.get('sort_order')
if sort_order == 'ASC':
insert = "SELECT text FROM data_input ORDER BY ASC limit %s"
parameters = max_count
cursor.execute(insert, parameters)
result = cursor.fetchall()
elif sort_order == 'DESC':
insert = "SELECT text FROM data_input ORDER BY DESC limit %s "
parameters = max_count
cursor.execute(insert, (parameters))
result = cursor.fetchall()
dic = {}
dic['text'] = result
return dic
except:
return "Error!, make sure url include: a max count and either 'ASC' or 'DESC' Argument"
cursor.close()
connection.close()
if __name__ == "__main__":
app.run(debug=True, port=3000)
The call is done in python shell from the server:
>>> import requests
>>> param = {'max_count': 12, 'sort_order': 'ASC'}
>>> r = requests.get('http://127.0.0.1:3000/get_data', params=param)
>>> r.text
I tried the code without the exception and the error is:
psycopg2.errors.SyntaxError: syntax error at or near "%"\nLINE 1: SELECT text FROM data_input limit %s
The issue is how you're passing the parameter to .execute()
You need to pass a tuple like this:
cursor.execute(insert, (parameters,)) # a comma is necessary to make a tuple
Currently when there is multiple digits it thinks those are separate parameters.
I am using flask to build up an api but session in requests is NONE when i am running this from html files and sending data with jquery. When i am sending with Postman the api is running normally. I use first /signup method and after /map in this is None. Can you help me? Have you any idea
import pymysql
from pymysql import install_as_MySQLdb
from flask import Flask, request, jsonify, session, g
from flask_session import Session
from flask_cors import CORS, cross_origin
app = Flask(__name__)
app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'
app.config['SESSION_TYPE'] = 'filesystem'
cors = CORS(app,allow_headers='Content-Type')
app.config['PROPAGATE_EXCEPTIONS'] = False
Session(app)
db = pymysql.connect("localhost", "root", "", "thesis")
#app.route('/signUp', methods=['GET','POST'])
def signUp():
#session.pop('userId', None)
data = request.get_json()
print(data)
cursor = db.cursor()
email = data['email']
password = data['pass']
fname=data['firstName']
lname=data['lastName']
cid=data['type']
points="0"
print(email)
print(password)
query = "SELECT * FROM users WHERE email=%s;"
cursor.execute(query, email)
rows = cursor.fetchall()
print(len(rows))
# print(rows[0])
if len(rows) == 0:
query = "INSERT INTO users(email,password,fname,lname,cid,points)VALUES(%s,%s,%s,%s,%s,%s);"
cursor.execute(query, (email,password,fname,lname,int(cid),int(points)))
db.commit()
query = "SELECT * FROM users WHERE email=%s;"
a=cursor.execute(query, email)
print(a)
rows = cursor.fetchall()
print(rows[0])
if len(rows) == 1:
for results in rows:
session['userId']=str(results[0])
print(session['userId'])
return jsonify(fname=fname, lname=lname,cid=cid)
else:
return jsonify(fname="", lname="")
else:
return jsonify(fname="", lname="")
#app.route('/map', methods=['POST','GET'])
#cross_origin(origin='*',headers=['Content-Type','Authorization'])
def map():
print(session.get('userId'))
data = request.get_json()
print(data)
cursor = db.cursor()
lat= data['lat']
lon = data['lon']
query = "UPDATE users SET lon=%s, lat=%s WHERE uid=%s;"
cursor.execute(query,(lon,lat,session.get('userId')))
db.commit()
return "hello"
if __name__ == "__main__":
app.run(debug=True)
I have a file structure on python anywhere as :
flaskhost(folder) which contains :
app.py
books.db
app.py contains -:
import flask
from flask import request, jsonify
import sqlite3
app = flask.Flask(__name__)
app.config["DEBUG"] = True
def dict_factory(cursor, row):
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d
#app.route('/', methods=['GET'])
def home():
return '''<h1>Distant Reading Archive</h1>
<p>A prototype API for distant reading of science fiction novels.</p>'''
#app.route('/api/v1/resources/books/all', methods=['GET'])
def api_all():
conn = sqlite3.connect('books.db')
conn.row_factory = dict_factory
cur = conn.cursor()
all_books = cur.execute('SELECT * FROM books;').fetchall()
return jsonify(all_books)
#app.errorhandler(404)
def page_not_found(e):
return "<h1>404</h1><p>The resource could not be found.</p>", 404
#app.route('/api/v1/resources/books', methods=['GET'])
def api_filter():
query_parameters = request.args
id = query_parameters.get('id')
published = query_parameters.get('published')
author = query_parameters.get('author')
query = "SELECT * FROM books WHERE"
to_filter = []
if id:
query += ' id=? AND'
to_filter.append(id)
if published:
query += ' published=? AND'
to_filter.append(published)
if author:
query += ' author=? AND'
to_filter.append(author)
if not (id or published or author):
return page_not_found(404)
query = query[:-4] + ';'
conn = sqlite3.connect('books.db')
conn.row_factory = dict_factory
cur = conn.cursor()
results = cur.execute(query, to_filter).fetchall()
return jsonify(results)
if __name__ == '__main__':
app.run()
I am trying to follow this tutorial
https://programminghistorian.org/en/lessons/creating-apis-with-python-and-flask
my site is hosted at :
http://vivanks.pythonanywhere.com
But when I call api by
http://127.0.0.1:5000/api/v1/resources/books?author=Connie+Willis
It show me error :
sqlite3.OperationalError: no such table: books
Any help how to fix this and host app on pythonanywhere.com ?
P.S On my local machine it's working perfectly fine
On Pythonanywnere, When pointing to content other than templates or static files (stored in their own proper directories, accessible by flask), you have to provide the full path:
conn = sqlite3.connect('/home/your_username/flaskhost/books.db')
I've got a flask app that queries a sqlite database and returns a list to html via jsonify. It works fine on localhost, but I've uploaded to dreamhost and am getting 404s for the jsonified lists. I can't tell whether it is an issue with flask communicating with my sqlite database, flask, or with json.
Here is the flask app:
#!/usr/bin/python
import sqlite3 as sqlite
import json
from flask import Flask, g, jsonify, make_response, render_template
DEBUG = True
DATABASE = './whdt_combined.db'
#setup flask application
app = Flask(__name__)
app.config.from_object(__name__)
##########################
### DATABASE STUFF #######
##########################
#connect to the database
def connect_db():
rv = sqlite.connect(app.config['DATABASE'])
rv.row_factory = dict_factory
return rv
#function for making rows nice
def dict_factory(cursor, row):
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d
#open new db connection if ones hasn't been opened
def get_db():
if not hasattr(g, 'sqlite_db'):
g.sqlite_db = connect_db()
return g.sqlite_db
#when application stops, close db connection
#app.teardown_appcontext
def close_db(error):
if hasattr(g, 'sqlite_db'):
g.sqlite_db.close()
#easy function to nicely query the db
def query_db(query, args=(), one =False):
cur = get_db().execute(query, args)
rv = cur.fetchall()
cur.close()
return (rv[0] if rv else None) if one else rv
##########################
### APPLICATION ##########
##########################
#app.route('/')
def index():
return render_template('index.html')
#app.route('/<data1>/<data2>/<region>/<year>/1/')
def datafunction1(data1, data2, region, year):
data = []
for row in query_db('SELECT ccode, country, year, region, ' + data1 + ' FROM whdt WHERE year = ' + year + ' AND region = "' + region + '" AND ' + data1 + ' != "" AND ' + data1 + ' > 0 AND ' + data1 + ' < 100 ORDER BY ' + data1 + ' DESC'):
countrywhole = {
'country' :row['country'],
'ccode':row['ccode'],
'year':row['year'],
'region':row['region'],
data1:row[data1]
}
data.append(countrywhole)
return jsonify( { 'data': data } )
if __name__ == '__main__':
app.run()
And here is my folder setup:
/home/user/mydomain.com/myapp/whdt_combined.db
/home/user/mydomain.com/myapp/myapp.py
/home/user/mydomain.com/myapp/__init__.py
/home/user/mydomain.com/myapp/templates/index.html
/home/user/mydomain.com/myapp/static/a couple of css and js files
Flask is not having trouble rendering index.html. Part of the issue is I don't know how to debug through dreamhost. I'm fairly new to this stuff so I'm sorry if I am missing something obvious or otherwise clearly don't know what I'm talking about. Please let me know if I should be providing other important information here. And thanks in advance for your help!