Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 CRUD performing but output not shown in table format in flask
#1
I am developing a basic crud operation type site. I am able to add the elements into DB by clicking submit in the form but the redirecting to the table format is not occurring. My code is at https://github.com/iamjhamukesh/Testing and every time I submit the form(localhost:5000/new_user), I get internal server error in the browser. The error in terminal is :
'dict' object has no attribute 'user_symbol'
[2018-10-23 18:06:20,557] ERROR in app: Exception on / [GET]
Traceback (most recent call last):
  File "/home/mukesh/.local/lib/python2.7/site-packages/flask/app.py", line 2292, in wsgi_app
    response = self.full_dispatch_request()
  File "/home/mukesh/.local/lib/python2.7/site-packages/flask/app.py", line 1816, in full_dispatch_request
    return self.finalize_request(rv)
  File "/home/mukesh/.local/lib/python2.7/site-packages/flask/app.py", line 1831, in finalize_request
    response = self.make_response(rv)
  File "/home/mukesh/.local/lib/python2.7/site-packages/flask/app.py", line 1957, in make_response
    'The view function did not return a valid response. The'
TypeError: The view function did not return a valid response. The function either returned None or ended without a return statement.
I think the problem is in tables.py and main.py. Can anyone please guide me where I am going wrong ?

tables.py:
from flask_table import Table, Col, LinkCol
 
class Results(Table):
    user_id = Col('Id', show=False)
    user_symbol = Col('Symbol')
    user_date = Col('Date')
    user_high = Col('High')
    user_low = Col('Low')
    user_volume = Col('Volume')
    user_open = Col('Open')
    user_close = Col('Close')
    #user_password = Col('Password', show=False)
    edit = LinkCol('Edit', 'edit_view', url_kwargs=dict(id='user_id'))
    delete = LinkCol('Delete', 'delete_user', url_kwargs=dict(id='user_id'))
main.py:
import pymysql
from app import app
from tables import Results
from db_config import mysql
from flask import flash, render_template, request, redirect
from werkzeug import generate_password_hash, check_password_hash
from contextlib import closing
'''
CREATE TABLE `bse` (
  `user_id` bigint(20) NOT NULL AUTO_INCREMENT,
   symbol varchar(50),date1 varchar(15),high varchar(10),low varchar(10),volume varchar(10),open varchar(10),close varchar(10),
   PRIMARY KEY (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
'''

@app.route('/new_user')
def add_user_view():
	return render_template('add.html')
		
@app.route('/add', methods=['POST'])
def add_user():
	try:		
		#_name = request.form['inputName']
		#_email = request.form['inputEmail']
		#_password = request.form['inputPassword']
		_symbol=request.form['inputsymbol']
		_date=request.form['inputdate']
		_high=request.form['inputhigh']
		_low=request.form['inputlow']
		_volume=request.form['inputvolume']
		_open=request.form['inputopen']
		_close=request.form['inputclose']

		# validate the received values
		if _symbol and _date and _high and _low and _volume and _open and _close and request.method == 'POST':
			#do not save password as a plain text
			#_hashed_password = generate_password_hash(_password)
			# save edits
			sql = "INSERT INTO bse(symbol,date1,high,low,volume,open,close) VALUES(%s, %s, %s, %s, %s, %s, %s)"
			#data = (_name, _email, _hashed_password,)
			data=(_symbol,_date,_high,_low,_volume,_open,_close)			
			conn = mysql.connect()
			cursor = conn.cursor()
			cursor.execute(sql, data)
			conn.commit()
			flash('Data added successfully!')
			return redirect('/')
		else:
			return 'Error while adding user'
	except Exception as e:
		print(e)
	finally:
		cursor.close() 
		conn.close()
		
@app.route('/')
def users():
	try:
	  #with closing(mysql.connect()) as conn:
	  #	with closing(conn.cursor()) as cursor:
			conn = mysql.connect()
			cursor = conn.cursor(pymysql.cursors.DictCursor)
			cursor.execute("SELECT * FROM bse")
			rows = cursor.fetchall()
			table = Results(rows)
			table.border = True
			return render_template('users.html', table=table)
	except Exception as e:
		print(e)
	finally:
		cursor.close() 
		conn.close()

@app.route('/edit/<int:id>')
def edit_view(id):
	try:
		conn = mysql.connect()
		cursor = conn.cursor(pymysql.cursors.DictCursor)
		cursor.execute("SELECT * FROM bse WHERE user_id=%s", id)
		row = cursor.fetchone()
		if row:
			return render_template('edit.html', row=row)
		else:
			return 'Error loading #{id}'.format(id=id)
	except Exception as e:
		print(e)
	finally:
		cursor.close()
		conn.close()

@app.route('/update', methods=['POST'])
def update_user():
	try:		
		#_name = request.form['inputName']
		#_email = request.form['inputEmail']
		#_password = request.form['inputPassword']
		_symbol=request.form['inputsymbol']
		_date=request.form['inputdate']
		_high=request.form['inputhigh']
		_low=request.form['inputlow']
		_volume=request.form['inputvolume']
		_open=request.form['inputopen']
		_close=request.form['inputclose']


		_id = request.form['id']


		# validate the received values
		if _symbol and _date and _high and _low and _volume and _open and _close and _id and request.method == 'POST':
			#do not save password as a plain text
			#_hashed_password = generate_password_hash(_password)
			# save edits
			sql = "UPDATE bse SET symbol=%s,date1=%s,high=%s,low=%s,volume=%s,open=%s,close=%s, WHERE user_id=%s"
			data = (_symbol,_date,_high,_low,_volume,_open,_close, _id,)
			conn = mysql.connect()
			cursor = conn.cursor()
			cursor.execute(sql, data)
			conn.commit()
			flash('BSE updated successfully!')
			#return json.dumps({'message':'BSE details updated successfully!'})#('BSE details updated successfully!')
			return redirect('/')
		else:
			return 'Error while updating user'
	except Exception as e:
		print(e)
		return 'Error'
	finally:
		cursor.close() 
		conn.close()
		
@app.route('/delete/<int:id>')
def delete_user(id):
	try:
		conn = mysql.connect()
		cursor = conn.cursor()
		cursor.execute("DELETE FROM bse WHERE user_id=%s", (id,))
		conn.commit()
		flash('BSE deleted successfully!')
		return redirect('/')
	except Exception as e:
		print(e)
	finally:
		cursor.close() 
		conn.close()
		
if __name__ == "__main__":
    app.run()
users.html:
<doctype html>
<title>List of BSE details</title> 

<p><a href="{{ url_for('.add_user_view') }}"> Add User </a></p>


<p>
	{% with messages = get_flashed_messages() %}
	  {% if messages %}
		<ul class=flashes>
		{% for message in messages %}
		  <li>{{ message }}</li>
		{% endfor %}
		</ul>
	  {% endif %}
	{% endwith %}
</p>
{{ table }}
I think the problem is in these 3 files but the other respective html files can be found on above mentioned github link (edit.html,add.html)
Quote
#2
(Oct-23-2018, 01:00 PM)lunchcook Wrote: 'dict' object has no attribute 'user_symbol'
Does your bse table have a user_symbol column? It looks like the flask_table is failing, because it's trying to display something which didn't exist in the rows. Maybe? I haven't used that package before, so I'm just going off what the error says.
Quote
#3
Yeah thanks it worked, I changed it according to DB. It had issues with conflicting names.
nilamo likes this post
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  Want to scrape a table data and export it into CSV format tahir1990 9 326 Oct-22-2019, 08:03 AM
Last Post: buran
  Using flask to add data to sqlite3 table with PRIMARY KEY catafest 1 1,494 Sep-09-2019, 07:00 AM
Last Post: buran
  sqlalchemy DataTables::"No data available in table" when using self-joined table Asma 0 592 Nov-22-2018, 02:46 PM
Last Post: Asma
  Flask: Error output to the browser instead of error_log nikos 1 602 Sep-28-2018, 12:49 PM
Last Post: thomasp

Forum Jump:


Users browsing this thread: 1 Guest(s)