internal server error after submitting a form flask,sqlite3 [duplicate] - python

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

Related

How to get back a value based by parameter input using Flask Python API

I keep recieving the following error when I try to curl this or go to the URL directly i.e. 127.0.0.1:5000/api/v1/currentuserid/3/ .. cannot see what is wrong with my code:
TypeError: 'NoneType' object is not callable
#app.route('/api/v1/currentuserid/<userid>/', methods=['GET'])
def api_retrieve_useridd(userid):
try:
mycursor = mydb.cursor()
_json = request.get_json()
userid = _json('userid')
if userid and request.method == 'GET':
sqlQuery = "SELECT username FROM tblUser WHERE user_id=%s"
bindData = (userid,)
mycursor.execute(sqlQuery, bindData)
row_headers=[x[0] for x in mycursor.description] #this will extract row headers
rv = mycursor.fetchone()
json_data=[]
json_data.append(dict(zip(row_headers,rv)))
return jsonify(json_data[0])
else:
return not_found()
finally:
mycursor.close()
userid parameter is already passed to the function via Flask route you defined. So you no need to get the value from request.get_json(). You may try below code. By the way, you can enforce the user_id type as int by doing <int:userid> in the route definition.
#app.route('/api/v1/currentuserid/<int:userid>/', methods=['GET'])
def api_retrieve_useridd(userid):
try:
mycursor = mydb.cursor()
if userid and request.method == 'GET':
sqlQuery = "SELECT username FROM tblUser WHERE user_id=%s"
bindData = (userid,)
mycursor.execute(sqlQuery, bindData)
row_headers=[x[0] for x in mycursor.description] #this will extract row headers
rv = mycursor.fetchone()
json_data=[]
json_data.append(dict(zip(row_headers,rv)))
return jsonify(json_data[0])
else:
return not_found()
finally:
mycursor.close()

Im trying to test my forms in my flask app using unittest, Am I doing the right way?

I wanna test my app using the unittest package. specifically I'm trying to test my forms. I'm having a hard time testing the post request on how to get the data from my forms and posting it
my reference:
https://realpython.com/python-testing/#more-advanced-testing-scenarios
my test.py code
from app import app
import unittest
class FlaskTestCase(unittest.TestCase):
def test_add(self):
tester = app.test_client(self)
response = tester.post('/Search/add', data=dict(fn =
"Emmanuel Ever", ln = "Telewik", email =
"everlopeztelewik#gmail.com", phone = 0912312311,
address = "ILIGAN"),
follow_redirect = True
)
self.assertEqual(response.status_code, 200)
if __name__ == '__main__':
unittest.main()
the function I'm going to test in app.py
#app.route("/Search/add", methods=['POST'])
def new():
if request.method == 'POST':
fn = request.form['fn']
ln = request.form['ln']
email = request.form['email']
phone = request.form['phone']
address = request.form['address']
conn = psycopg2.connect("dbname = 'test_db3' user = 'postgres'
password = 'shizzle7' host = 'localhost' port = '5432'")
cur = conn.cursor()
cur.execute("INSERT into user2 values(Default, %s, %s, %s, %s,
%s)",(fn,ln,email,phone,address))
conn.commit()
conn.close()
return redirect('/Search')
return render_template('index.html')

OperationalError: no such table: books on python anywhere

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')

Perform psycopg2 db search based on user input using python function [duplicate]

This question already has an answer here:
psycopg2 how deal with TypeError: not all arguments converted during string formatting
(1 answer)
Closed 5 years ago.
I'm trying to perform a database search, based on user input. The DBresults function in the below code is intended to catch the input stored in the "ranumber" and perform an SQL search on that specific record. I can't seem to get this working. I've tried a number of things which have generated various errors, but the latest error I'm getting says "TypeError: not all arguments converted during string formatting".
What am I missing here?
def connectToDB():
psycopg2.connect('dbname=reportingdb user=rai_gui password=Rad1oInd host=10.100.51.42')
def DBresults(ranumber):
conn = psycopg2.connect('dbname=reporting user=rai_user password=Rad1odsfdInd host=10.100.47.42')
cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
cur.execute("SELECT * FROM radio_archive_index_gui.radio_archive_index_gui WHERE rai_number= %s", (ranumber))
searchresults = cur.fetchall()
print (searchresults)
####Index Page
#app.route('/', methods=['GET', 'POST'])
#app.route('/index', methods=['GET', 'POST'])
def index():
exception = ""
try:
connectToDB
except:
exception = 'Failure to connect to db'
form = StaffNames()
if not exception:
if form.validate_on_submit():
query = {
'staff': dict(staff_choices).get(form.staff.data),
'ranumber': form.ranumber.data
}
return redirect(url_for('results', **query))
return render_template(
'index.html', title='Search Page', exception=exception, form=form
)
#####Results Page
#app.route('/results')
def results():
ranumber = request.args.get('ranumber', None)
staff = request.args.get('staff', None)
DBresults()
return render_template(
'results.html', title='Results', staff=staff, ranumber=ranumber
)
Here's my form.py file if it helps:
staff_choices=[("", ""), ('1', 'John Jones'), ('2', 'Chris Hughes'), (' 3', 'Lyn bear')]
class StaffNames(Form):
ranumber = StringField('ranumber', validators=[DataRequired()])
staff = SelectField('staff',choices=staff_choices,validators=[DataRequired()])
Try editing
cur.execute("SELECT * FROM radio_archive_index_gui.radio_archive_index_gui WHERE rai_number= %s", (ranumber))
to
cur.execute("SELECT * FROM radio_archive_index_gui.radio_archive_index_gui WHERE rai_number= %s", (ranumber,))
(ranumber) needs to be in tuple format for string formatting to work properly.

FLASK-python ValueError: View function did not return a response [duplicate]

This question already has answers here:
Flask view return error "View function did not return a response"
(3 answers)
Closed 2 years ago.
I am trying to run an sql function that inserts data into a table. I am following the example explained here but whenever i run the script i get the error "ValueError: View function did not return a response"
My code looks like this:
from flask import render_template, flash, redirect, request
from app import app
from .forms import LoginForm
from .forms import RegistrationForm
import sqlite3 as sql
#app.route('/')
#app.route('/index')
#app.route('/registration', methods = ['GET','POST'])
def registration():
form = RegistrationForm()
if request.method == 'POST':
try:
card_id = request.form['card_id']
pin = request.form['pin']
account_id = request.form['account_id']
with sql.connect("testDB.db") as con:
cur = con.cursor()
cur.execute("INSERT INTO atm_card (card_id,pin,account_id) VALUES (?,?,?,?)",(card_id,pin,account_id) )
con.commit()
msg = "Record successfully added"
except:
con.rollback()
msg = "error in insert operation"
finally:
return render_template("index.html",msg = msg)
con.close()
what can i be possibly be doing wrong?
What would be returned if request method is GET? you are rendering template only on POST request. correct it.
#app.route('/registration', methods = ['GET','POST'])
def registration():
form = RegistrationForm()
if request.method == 'POST':
try:
card_id = request.form['card_id']
pin = request.form['pin']
account_id = request.form['account_id']
with sql.connect("testDB.db") as con:
cur = con.cursor()
cur.execute("INSERT INTO atm_card (card_id,pin,account_id) VALUES (?,?,?,?)",(card_id,pin,account_id) )
con.commit()
msg = "Record successfully added"
except:
con.rollback()
msg = "error in insert operation"
finally:
return render_template("index.html",msg = msg)
con.close()
else:
return render_template('index.html', form=form)

Categories