Why is there a KeyError when the dictionary has the key? - python

I am creating a simple flask application to store JSON files and read them. The application should return a JSON file I made as a test. Here's the url: http://IP:5000/?room=test&game=test. I got this error:
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/flask/app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "/usr/lib/python3/dist-packages/flask/app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/lib/python3/dist-packages/flask/app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/usr/lib/python3/dist-packages/flask/_compat.py", line 35, in reraise
raise value
File "/usr/lib/python3/dist-packages/flask/app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/lib/python3/dist-packages/flask/app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/pi/Desktop/python/universalgameserver.py", line 10, in api_set
return json.loads(readJSON(request.args['room'], request.args['game']))
File "/home/pi/Desktop/python/universalgameserver.py", line 17, in readJSON
f = open("~/saves/${room}_${game}.json".format(room, game), "r")
KeyError: 'room'
Printing out the dictionary, it looks like this:
{'room': 'test', 'game': 'test'}
My code looks like this:
from flask import Flask, request
import json
app = Flask(__name__)
#app.route("/", methods=["GET", "POST"])
def api_set():
if request.method == "POST":
writeJSON(request.form['room'], request.form['game'], request.form['json'])
else:
print(dict(request.args))
return json.loads(readJSON(request.args['room'], request.args['game']))
def writeJSON(room, game, json):
f = open("~/saves/${room}_${game}.json".format(room, game), "w")
f.write(json)
f.close()
def readJSON(room, game):
f = open("~/saves/${room}_${game}.json".format(room, game), "r")
contents = f.read()
f.close()
return contents
if __name__ == '__main__':
app.run(host='192.168.0.36')

The KeyError is raised in readJSON during the formatting of:
f = open("~/saves/${room}_${game}.json".format(room, game), "r")
Change it to:
If in Python 2:
f = open("~/saves/{0}_{1}.json".format(room, game), "r")
If in Python 3.6 or newer, using f-string which allows you to easy format:
f = open(f"~/saves/{room}_{game}.json", "r")
And it shall work like magic!
P.S.
Similarly, change in the writeJSON too.

Related

TypeError: unhashable type: 'set' in Flask Form

I am trying to fetch data from form in Flask:
app.py
#app.route('/newProjectCreation/', methods=['GET', 'POST'])
def newProjectCreation():
try:
if request.method == 'POST':
# Data Fetch from Models Form
name = request.form['modelName']
modelDescription = request.form['modelDescription']
inputType = request.form.getlist['inputType[]']
outputType = request.form.getlist['outputType[]']
model = request.files['model']
modelLanguage = request.form['modelLanguage']
HTML
It is a simple form (not Flask-WTF form) and the fields "inputType" and "outputType" are supposed to return array as they are dynamically input fields.
Error:
Traceback (most recent call last):
File "/home/adiagarwal/cad/flaskapp-docker/flaskapp/app.py", line 106, in newProjectCreation
inputType = request.form.getlist['inputType[]']
TypeError: 'method' object is not subscriptable
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/adiagarwal/cad/env/lib/python3.8/site-packages/flask/app.py", line 2464, in __call__
return self.wsgi_app(environ, start_response)
File "/home/adiagarwal/cad/env/lib/python3.8/site-packages/flask/app.py", line 2450, in wsgi_app
response = self.handle_exception(e)
File "/home/adiagarwal/cad/env/lib/python3.8/site-packages/flask/app.py", line 1867, in handle_exception
reraise(exc_type, exc_value, tb)
File "/home/adiagarwal/cad/env/lib/python3.8/site-packages/flask/_compat.py", line 39, in reraise
raise value
File "/home/adiagarwal/cad/env/lib/python3.8/site-packages/flask/app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "/home/adiagarwal/cad/env/lib/python3.8/site-packages/flask/app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/adiagarwal/cad/env/lib/python3.8/site-packages/flask/app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/home/adiagarwal/cad/env/lib/python3.8/site-packages/flask/_compat.py", line 39, in reraise
raise value
File "/home/adiagarwal/cad/env/lib/python3.8/site-packages/flask/app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "/home/adiagarwal/cad/env/lib/python3.8/site-packages/flask/app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/adiagarwal/cad/flaskapp-docker/flaskapp/app.py", line 129, in newProjectCreation
return {{e}}
TypeError: unhashable type: 'set'
I don't have prior experience in js and I am learning, if possible please simplify the response.
Thank You in advance.
Ok, I was focused on a big problem, but the problem is so simple that I did not realize it: Replace all [] with (). See below.
If you [] it assumes as dict and you are returting a list or set.
#app.route('/newProjectCreation/', methods=['GET', 'POST'])
def newProjectCreation():
try:
if request.method == 'POST':
# Data Fetch from Models Form
name = request.form('modelName')
modelDescription = request.form('modelDescription')
inputType = request.form.getlist('inputType[]')
outputType = request.form.getlist('outputType[]')
model = request.files('model')
modelLanguage = request.form('modelLanguage')

How to fix ValueError: DataFrame constructor not properly called on flask

I want to try to make a dataframe from pdfreader, with the column name is isi1. but why do I get an error ValueError: DataFrame constructor not properly called !. what should i do to fix this error. help from anyone when needed for this problem.
this is my code
if request.method == 'POST':
f = request.files['file']
f.save(f.filename)
pdfreader = PyPDF2.PdfFileReader(open('C:/Users/Novilia/PycharmProjects/tesaja/' + f.filename, 'rb'))
from pandas import DataFrame
df1 = DataFrame(pdfreader, columns=['isi1'])
#vect = count_vect.transform(['isi1']).toarray()
df1['label1'] = text_clf.predict(df1['isi1'])
df1.append(['label1'])
hasil = (df1.isi1[df1['label1'] == 'positif'])
len(hasil)
hasil_list = hasil.values.tolist()
stringList = ' '.join([str(item) for item in hasil_list])
hasil_ringkas = stringList
return render_template('result.html', ringkasan = hasil_ringkas)
the error is
ValueError
ValueError: DataFrame constructor not properly called!
Traceback (most recent call last)
File "C:\Users\Novilia\PycharmProjects\tesaja\venv\lib\site-packages\flask\app.py", line 2463, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Users\Novilia\PycharmProjects\tesaja\venv\lib\site-packages\flask\app.py", line 2449, in wsgi_app
response = self.handle_exception(e)
File "C:\Users\Novilia\PycharmProjects\tesaja\venv\lib\site-packages\flask\app.py", line 1866, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\Novilia\PycharmProjects\tesaja\venv\lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "C:\Users\Novilia\PycharmProjects\tesaja\venv\lib\site-packages\flask\app.py", line 2446, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\Novilia\PycharmProjects\tesaja\venv\lib\site-packages\flask\app.py", line 1951, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\Novilia\PycharmProjects\tesaja\venv\lib\site-packages\flask\app.py", line 1820, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\Novilia\PycharmProjects\tesaja\venv\lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "C:\Users\Novilia\PycharmProjects\tesaja\venv\lib\site-packages\flask\app.py", line 1949, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\Novilia\PycharmProjects\tesaja\venv\lib\site-packages\flask\app.py", line 1935, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\Novilia\PycharmProjects\tesaja\app.py", line 79, in summarize
df1 = DataFrame(pdfreader, columns=['isi1'])
File "C:\Users\Novilia\PycharmProjects\tesaja\venv\lib\site-packages\pandas\core\frame.py", line 509, in __init__
raise ValueError("DataFrame constructor not properly called!")
ValueError: DataFrame constructor not properly called!
From my understanding, I guess you need to iterate over the pages and get the text from each page. can you try the following:
import nltk
pdfreader = PyPDF2.PdfFileReader(open('C:/Users/Novilia/PycharmProjects/tesaja/' + f.filename, 'rb'))
page_contents = [sent for page_no in range(pdfreader.getNumPages())
for sent in nltk.sent_tokenize(pdfreader.getPage(page_no).extractText())]
df1 = DataFrame(page_contents, columns=['isi1'])
Kindly let me know if you find any problem with the code.

NameError: name 'marks' is not defined

Here I am trying to fetch data from cassandra with filter() where I need to fetch students with more than or equal to 65 marks but I am getting this error can't understand why am I getting this error. I am referring this link. I have also referred similar questions on this but didn't get any solution.
Here is my python code:
from flask import *
from flask_cqlalchemy import CQLAlchemy
app = Flask(__name__)
app.config['CASSANDRA_HOSTS'] = ['127.0.0.1']
app.config['CASSANDRA_KEYSPACE'] = "emp"
db = CQLAlchemy(app)
class Student(db.Model):
uid = db.columns.Integer(primary_key=True)
marks = db.columns.Integer(primary_key=True)
username = db.columns.Text(required=True)
password = db.columns.Text()
#app.route('/merit')
def show_merit_list():
ob = Student.objects.filter(marks >= 65)
return render_template('merit.html', ml = ob)
And this is the error log I am getting:
Traceback (most recent call last)
File "/home/sudarshan/.local/lib/python3.6/site-packages/flask/app.py", line 2463, in
__call__
return self.wsgi_app(environ, start_response)
File "/home/sudarshan/.local/lib/python3.6/site-packages/flask/app.py", line 2449, in
wsgi_app
response = self.handle_exception(e)
File "/home/sudarshan/.local/lib/python3.6/site-packages/flask/app.py", line 1866, in
handle_exception
reraise(exc_type, exc_value, tb)
File "/home/sudarshan/.local/lib/python3.6/site-packages/flask/_compat.py", line 39, in
reraise
raise value
File "/home/sudarshan/.local/lib/python3.6/site-packages/flask/app.py", line 2446, in
wsgi_app
response = self.full_dispatch_request()
File "/home/sudarshan/.local/lib/python3.6/site-packages/flask/app.py", line 1951, in
full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/sudarshan/.local/lib/python3.6/site-packages/flask/app.py", line 1820, in
handle_user_exception
reraise(exc_type, exc_value, tb)
File "/home/sudarshan/.local/lib/python3.6/site-packages/flask/_compat.py", line 39, in
reraise
raise value
File "/home/sudarshan/.local/lib/python3.6/site-packages/flask/app.py", line 1949, in
full_dispatch_request
rv = self.dispatch_request()
File "/home/sudarshan/.local/lib/python3.6/site-packages/flask/app.py", line 1935, in
dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/sudarshan/Downloads/PycharmProjects/try/try1.py", line 67, in show_merit_list
ob = Student.objects.filter(marks >= 65)
NameError: name 'marks' is not defined
Pass self object to your method, hence allowing it to access marks data member.
Change marks to self.marks.
#app.route('/merit')
def show_merit_list(self):
ob = Student.objects.filter(self.marks >= 65)
return render_template('merit.html', ml = ob)
Well finally I found the answer I was forgetting to use allow_filtering(). The code will look like following:
#app.route('/merit')
def show_merit_list():
ob = Student.objects().filter() #all()
ob = ob.filter(Student.marks >= 65).allow_filtering()
return render_template('merit.html', ml = ob)
You need to use Filtering Operators, try:
ob = Student.objects.filter(marks__gte=65)

Receiving AssertionError using Flask sqlalchemy and restful

I have been stumped and can't seem to figure out why I am receiving an AssertionError. I am currently working on a rest api using the flask_restful lib. I am querying by:
#staticmethod
def find_by_id(id, user_id):
f = File.query.filter_by(id=id).first() #Error is happening here
if f is not None:
if f.check_permission(user_id)>=4:
return f
print f.check_permission(user_id)
FileErrors.InsufficientFilePermission()
FileErrors.FileDoesNotExist()
The error message looks like this:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 2000, in __call__
return self.wsgi_app(environ, start_response)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1991, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/usr/local/lib/python2.7/dist-packages/flask_restful/__init__.py", line 271, in error_router
return original_handler(e)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1567, in handle_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python2.7/dist-packages/flask_restful/__init__.py", line 268, in error_router
return self.handle_error(e)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1988, in wsgi_app
response = self.full_dispatch_request()
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1641, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/local/lib/python2.7/dist-packages/flask_restful/__init__.py", line 271, in error_router
return original_handler(e)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1531, in handle_user_exception
assert exc_value is e
AssertionError
This is how my File model looks like:
class File(db.Model):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer)
parts = db.Column(db.Integer)
size = db.Column(db.Integer)
name = db.Column(db.String(100))
def __init__ (self, file_info):
self.user_id = file_info['user_id']
self.parts = file_info['parts']
self.size = file_info['size']
self.name = file_info['name']
#staticmethod
def create(file_info):
return add_to_db(File(file_info))
#staticmethod
def delete(file_id, user_id):
pass
def check_permission(self,user_id):
permission = 0
print 'self.user_id {}'.format(self.user_id)
print 'user_id {}'.format(user_id)
if self.user_id == user_id:
return 7
fs = FileShare.find_by_file_and_user_id(self.id, user_id)
if fs is not None:
permission = fs.permission
return permission
#staticmethod
def find_by_id(id, user_id):
f = File.query.filter_by(id=id).first() #Error is happening here
if f is not None:
if f.check_permission(user_id)>=4:
return f
print f.check_permission(user_id)
FileErrors.InsufficientFilePermission()
FileErrors.FileDoesNotExist()
Any help would be appreciated. Thanks in advance.
Are you sure you want to have an assignment operator instead of comparison in your filter. Try replacing = with == and see if it solves your problem.
f = File.query.filter_by(id == id).first()
Hannu
Although I couldn't figure out why the error occurs, I know how as well as how to prevent it. It is created because the query doesn't pull the live data right after the commit. The way to prevent it is by using db.session.query(). So in my example I would change:
f = File.query.filter_by(id=id).first()
to
f = db.session.query(File).filter_by(id=id).first()
For some reason that works. Although I don't know why.
EDIT: It seems to have to do with the class not receiving updated session. For the time being I recommending using queries within session.

'Area' object is not callable

I have database on Mysql and in project I use pony orm in Flask. I need to get row from database with index 1.
Here I have routes for routing in app
routes.py
from app import app
from pony.orm import *
from app.models import Area
#app.route("/")
#app.route("/user/")
#db_session
def user():
c = Area[1]
return c
Here I have models for my database
models.py
from pony.orm import *
import config
db = Database()
class Country(db.Entity):
id = PrimaryKey(int,auto=True)
name = Required(str,100)
area = Set("Area")
class Area(db.Entity):
id = PrimaryKey(int, auto=True)
name = Required(str, 100)
country = Required(Country)
When I open in browser address localhost:8888/ I get next error
Traceback (most recent call last):
File "C:\Python34\lib\site-packages\flask\app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Python34\lib\site-packages\flask\app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "C:\Python34\lib\site-packages\flask\app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Python34\lib\site-packages\flask\_compat.py", line 33, in reraise
raise value
File "C:\Python34\lib\site-packages\flask\app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "C:\Python34\lib\site-packages\flask\app.py", line 1478, in full_dispatch_request
response = self.make_response(rv)
File "C:\Python34\lib\site-packages\flask\app.py", line 1577, in make_response
rv = self.response_class.force_type(rv, request.environ)
File "C:\Python34\lib\site-packages\werkzeug\wrappers.py", line 841, in force_type
response = BaseResponse(*_run_wsgi_app(response, environ))
File "C:\Python34\lib\site-packages\werkzeug\wrappers.py", line 57, in _run_wsgi_app
return _run_wsgi_app(*args)
File "C:\Python34\lib\site-packages\werkzeug\test.py", line 867, in run_wsgi_app
app_iter = app(environ, start_response)
TypeError: 'Area' object is not callable
When I made error?
I'm stupid! Here solution:
def user():
c = Area[1]
name = c.name
return name

Categories

Resources