NameError: name 'marks' is not defined - python

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)

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.

Flask models .save() raises TypeError: _validate() missing 1 required positional argument: 'value'

I tried to add a list to an attribute but when I tried to save the db it raises the exception below. Is there something wrong with my code? I previously modified the models to add new attribute saved_jadwal_ids. I thought it caused no problem as I've tried to set value to it before doing jadwal.save() and I could print the value. Do I actually need to make migrations or something? Thank you.
jadwal = Jadwal.objects(id=jadwal_id).first()
eventIds = []
# courses = data['jadwals']
courses = getCourses()
for course in courses:
id = insert_event(calendar, course)
eventIds.append(id)
jadwal.saved_jadwal_ids = eventIds
jadwal.save()
Jadwal.py:
class Jadwal(Document):
user_id = ReferenceField('User')
jadwals = ListField(EmbeddedDocumentField(JadwalData))
created_at = DateTimeField(default=datetime.now)
saved_jadwal_ids = ListField(StringField)
Error:
Traceback (most recent call last):
File "c:\users\anisha\appdata\local\programs\python\python37\lib\site-packages\flask\app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "c:\users\anisha\appdata\local\programs\python\python37\lib\site-packages\flask\app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "c:\users\anisha\appdata\local\programs\python\python37\lib\site-packages\flask_cors\extension.py", line 161, in wrapped_function
return cors_after_request(app.make_response(f(*args, **kwargs)))
File "c:\users\anisha\appdata\local\programs\python\python37\lib\site-packages\flask\app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "c:\users\anisha\appdata\local\programs\python\python37\lib\site-packages\flask\_compat.py", line 35, in reraise
raise value
File "c:\users\anisha\appdata\local\programs\python\python37\lib\site-packages\flask\app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "c:\users\anisha\appdata\local\programs\python\python37\lib\site-packages\flask\app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\Anisha\RISTEK BISMILLAH\sunjadv2-server\app.py", line 631, in add_jadwal_to_calendar
jadwal.save()
File "c:\users\anisha\appdata\local\programs\python\python37\lib\site-packages\mongoengine\document.py", line 362, in save
self.validate(clean=clean)
File "c:\users\anisha\appdata\local\programs\python\python37\lib\site-packages\mongoengine\base\document.py", line 377, in validate
field._validate(value)
File "c:\users\anisha\appdata\local\programs\python\python37\lib\site-packages\mongoengine\base\fields.py", line 234, in _validate
self.validate(value, **kwargs)
File "c:\users\anisha\appdata\local\programs\python\python37\lib\site-packages\mongoengine\fields.py", line 857, in validate
super(ListField, self).validate(value)
File "c:\users\anisha\appdata\local\programs\python\python37\lib\site-packages\mongoengine\base\fields.py", line 431, in validate
self.field._validate(v)
TypeError: _validate() missing 1 required positional argument: 'value'
Try replacing:
saved_jadwal_ids = ListField(StringField)
with:
saved_jadwal_ids = ListField(StringField())
I could reproduce and fix the error with this snippet:
from mongoengine import Document, StringField, ListField
class Example(Document):
meta = {'collection': 'examples'}
saved_jadwal_ids = ListField(StringField) # should be StringField()
e = Example()
e.saved_jadwal_ids = ['not','ok']
e.save()
TypeError: _validate() missing 1 required positional argument: 'value'

'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

For an SQLAlchemy query, how to combine ilike search operator with in_ operator?

I am writing SQLAlchemy code that takes a search bar's input and runs a query against my PostgreSQL database. To allow for misspellings and name fragments, I had this code that did the trick:
q = session.query(Detail).filter((Detail.sellers.ilike("%%%s%%" % (name_input)))).all()
Now I am trying to do the same thing, but to check against a list names that has multiple input values. I've accomplished that like so:
q = session.query(Detail).filter((Detail.sellers.in_(names))
That requires exact matches, however. I would like to combine the ilike operator and the in_ operator. Is this possible? I've tried:
q = session.query(Detail).filter((Detail.sellers.ilike.in_(names))
That gives the following traceback and error:
File "/Users/Tom/projects/land-records/lib/python2.7/site-packages/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "/Users/Tom/projects/land-records/lib/python2.7/site-packages/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/Users/Tom/projects/land-records/lib/python2.7/site-packages/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "/Users/Tom/projects/land-records/lib/python2.7/site-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/Users/Tom/projects/land-records/lib/python2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Users/Tom/projects/land-records/lib/python2.7/site-packages/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/Users/Tom/projects/land-records/lib/python2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "/Users/Tom/projects/land-records/lib/python2.7/site-packages/flask/app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/Users/Tom/projects/land-records/repo/scripts/app.py", line 162, in search
return query_db(names)
File "/Users/Tom/projects/land-records/lib/python2.7/site-packages/flask_cache/__init__.py", line 537, in decorated_function
rv = f(*args, **kwargs)
File "/Users/Tom/projects/land-records/repo/scripts/app.py", line 106, in query_db
q = session.query(Detail).filter((Detail.sellers.ilike.in_(names))).all()
AttributeError: 'function' object has no attribute 'in_'
If it's just about the case insensitive 'in_' statement:
from sqlalchemy import func
q = session.query(Detail).filter(
func.lower(Detail.sellers).in_(map(str.lower, names))
)
Otherwise, if you wanted to have multiple 'ilike' statements,
from sqlalchemy import or_
conditions = []
for name in names:
conditions.append(Detail.sellers.ilike('%{}%'.format(name)))
q = session.query(Detail).filter(
or_(*conditions)
)
I haven't tested it, in case it didn't work, I can edit it.

Categories

Resources