In path /getAll I want return a list of JSONs but I get list object is not callable. Why this happens and how I can return my list of Json? Previously myList was list and after read the definition I changed "list" to "myList" but the error persists.
TypeError: 'str' object is not callable
TypeError: 'list' object is not callable
These can occur when attempting to assign a value to variables with these names, or by mutating their values.
Code
from flask import Flask, render_template, Response
import pymongo
from bson.json_util import dumps
app = Flask(__name__)
#app.route('/')
def index():
return render_template('index.html')
#app.route('/getAll', methods=['GET'])
def getAll():
try:
conn = pymongo.MongoClient()
except pymongo.errors.ConnectionFailure, e:
print "Could not connect to MongoDB: %s" % e
db = conn['local']
collection = db.test
myList = []
for d in collection.find():
myList.append(dumps(d))
return myList
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8080, debug=True)
TrackTrace
127.0.0.1 - - [27/Mar/2016 16:51:44] "GET /getAll HTTP/1.1" 500 -
Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "/usr/lib/python2.7/site-packages/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/usr/lib/python2.7/site-packages/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "/usr/lib/python2.7/site-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/usr/lib/python2.7/site-packages/flask/app.py", line 1478, in full_dispatch_request
response = self.make_response(rv)
File "/usr/lib/python2.7/site-packages/flask/app.py", line 1577, in make_response
rv = self.response_class.force_type(rv, request.environ)
File "/usr/lib/python2.7/site-packages/werkzeug/wrappers.py", line 847, in force_type
response = BaseResponse(*_run_wsgi_app(response, environ))
File "/usr/lib/python2.7/site-packages/werkzeug/wrappers.py", line 57, in _run_wsgi_app
return _run_wsgi_app(*args)
File "/usr/lib/python2.7/site-packages/werkzeug/test.py", line 871, in run_wsgi_app
app_rv = app(environ, start_response)
TypeError: 'list' object is not callable
Related
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')
I'm currently using an environment variable to hide my API's key. My unit test that is testing the API route is now failing. However, when the key was hard-coded into the main file, the tests passed. Here is my code:
import os
import requests
key = os.environ.get('key')
def test_code(state, API_BASE_URL):
url = f'https://covid-19-testing.github.io/locations/{state.lower()}/complete.json'
res = requests.get(url)
testing_data = res.json()
latsLngs = {}
for obj in testing_data:
if obj["physical_address"]:
for o in obj["physical_address"]:
addy = o["address_1"]
city = o["city"]
phone = obj["phones"][0]["number"]
location = f'{addy} {city}'
location_coordinates = requests.get(API_BASE_URL,
params={'key': key, 'location': location}).json()
lat = location_coordinates["results"][0]["locations"][0]["latLng"]["lat"]
lng = location_coordinates["results"][0]["locations"][0]["latLng"]["lng"]
latsLngs[location] = {'lat': lat, 'lng': lng, 'place': location, 'phone': phone}
return latsLngs
Here is the unit test:
from unittest import TestCase, mock
from models import db, User
from sqlalchemy.exc import InvalidRequestError
class UserViewTestCase(TestCase):
"""Test views for users."""
def setUp(self):
"""Create test client, add sample data."""
db.drop_all()
db.create_all()
self.app = create_app('testing')
self.client = self.app.test_client()
self.testuser = User.signup('test',
'dummy',
'test123',
'dummytest#test.com',
'password',
None,
"Texas",
None,
None)
self.uid = 1111
self.testuser.id = self.uid
db.session.commit()
def test_map_locations(self):
"""Does the map show testing locations?"""
with self.client as c:
resp = c.get('/location?state=California')
html = resp.get_data(as_text=True)
self.assertEqual(resp.status_code, 200)
self.assertIn('San Francisco', html)
I also think it's important to note that the application runs fine in the browser. It's just that the unit tests are not passing anymore.
UPDATE
Here is the full traceback:
ERROR: test_map_locations (test_user_views.UserViewTestCase)
Does the map show testing locations?
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/travis/build/azaria-dedmon/covid-19/tests/test_user_views.py", line 157, in test_map_locations
resp = c.get('/location?state=California')
File "/home/travis/virtualenv/python3.7.1/lib/python3.7/site-packages/werkzeug/test.py", line 1006, in get
return self.open(*args, **kw)
File "/home/travis/virtualenv/python3.7.1/lib/python3.7/site-packages/flask/testing.py", line 227, in open
follow_redirects=follow_redirects,
File "/home/travis/virtualenv/python3.7.1/lib/python3.7/site-packages/werkzeug/test.py", line 970, in open
response = self.run_wsgi_app(environ.copy(), buffered=buffered)
File "/home/travis/virtualenv/python3.7.1/lib/python3.7/site-packages/werkzeug/test.py", line 861, in run_wsgi_app
rv = run_wsgi_app(self.application, environ, buffered=buffered)
File "/home/travis/virtualenv/python3.7.1/lib/python3.7/site-packages/werkzeug/test.py", line 1096, in run_wsgi_app
app_rv = app(environ, start_response)
File "/home/travis/virtualenv/python3.7.1/lib/python3.7/site-packages/flask/app.py", line 2464, in __call__
return self.wsgi_app(environ, start_response)
File "/home/travis/virtualenv/python3.7.1/lib/python3.7/site-packages/flask/app.py", line 2450, in wsgi_app
response = self.handle_exception(e)
File "/home/travis/virtualenv/python3.7.1/lib/python3.7/site-packages/flask/app.py", line 1867, in handle_exception
reraise(exc_type, exc_value, tb)
File "/home/travis/virtualenv/python3.7.1/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
raise value
File "/home/travis/virtualenv/python3.7.1/lib/python3.7/site-packages/flask/app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "/home/travis/virtualenv/python3.7.1/lib/python3.7/site-packages/flask/app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/travis/virtualenv/python3.7.1/lib/python3.7/site-packages/flask/app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/home/travis/virtualenv/python3.7.1/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
raise value
File "/home/travis/virtualenv/python3.7.1/lib/python3.7/site-packages/flask/app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "/home/travis/virtualenv/python3.7.1/lib/python3.7/site-packages/flask/app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/travis/build/azaria-dedmon/covid-19/app/__init__.py", line 111, in show_state_locations
latsLngs = test_code(state, API_BASE_URL)
File "/home/travis/build/azaria-dedmon/covid-19/app/refactor.py", line 22, in test_code
params={'key': key, 'location': location}).json()
File "/home/travis/virtualenv/python3.7.1/lib/python3.7/site-packages/requests/models.py", line 900, in json
return complexjson.loads(self.text, **kwargs)
File "/opt/python/3.7.1/lib/python3.7/json/__init__.py", line 348, in loads
return _default_decoder.decode(s)
File "/opt/python/3.7.1/lib/python3.7/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/opt/python/3.7.1/lib/python3.7/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
I think it's most likely that your test framework is loading just the test_code() function from your test file, and not the fact that key is set up in the main body of the code. Perhaps moving your key = os.environ.get("key") into test_code() will solve your issue.
The environment variable needs to be set in the project's repository in travis CI so that all files have access to it. Here is the documentation on how to achieve this https://docs.travis-ci.com/user/environment-variables/#defining-variables-in-repository-settings
I am having trouble in displaying output in JSON using Flask. I am calling a function that returns a list of lists which looks as:
[[["High", 0], ["Medium", 1], ["Low", 2], ["Unknown", 3]], ["test_data", [4155, 1, 25, 9.1, 2, "2.40"]], ["label", 1]]
However, in my flask application, I am unable to jsonify or json.dumps. I do like this:
def remotely_call_func(json_lol):
# print('inside remotely')
# abc =[]
# abc=ext.call_func(json_lol) # I tried to jsonify abc
# print(abc) # print the
return json.dumps(ext.call_func(json_lol)) # throws an exception
# return ext.call_func(json_lol)
#app.route('/api/v1/engine/label', methods=['POST'])
def labelJsonHandler():
if request.is_json:
# Parse the JSON into a Python dictionary
print('request is json')
content = request.get_json() # --works
app.logger.info("labelJsonHandler()..", content)
return access_data_api(content['orderId']), 200 # Return a string along with an HTTP status code
else:
return "Request was not JSON", 400
The exception that I get is:
INFO:werkzeug:127.0.0.1 - - [23/Apr/2020 05:20:34] "POST /api/v1/engine/label HTTP/1.1" 500 -
Traceback (most recent call last):
File "C:\Users\nma\Anaconda3\lib\site-packages\flask\app.py", line 2464, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Users\nma\Anaconda3\lib\site-packages\flask\app.py", line 2450, in wsgi_app
response = self.handle_exception(e)
File "C:\Users\nma\Anaconda3\lib\site-packages\flask\app.py", line 1867, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\nma\Anaconda3\lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "C:\Users\nma\Anaconda3\lib\site-packages\flask\app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\nma\Anaconda3\lib\site-packages\flask\app.py", line 1953, in full_dispatch_request
return self.finalize_request(rv)
File "C:\Users\nma\Anaconda3\lib\site-packages\flask\app.py", line 1968, in finalize_request
response = self.make_response(rv)
File "C:\Users\nma\Anaconda3\lib\site-packages\flask\app.py", line 2098, 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 am able to receive the exact list of lists in my flask application. How can render this as JSON to POST using my flask?
If I run this code, it will be correctly paged without any error builtins.IndexError
IndexError: single positional indexer out of bounds "error, I fully understand the intenettene resolution, do you help?
When I look at the relevant articles, I do not understand the solution of some of them, but some do not understand it because they are not Turkish, and can you help me?
from flask import Flask,render_template,flash,redirect,url_for,session,logging,request
from flask_mysqldb import MySQL
from wtforms import Form,StringField,TextAreaField,PasswordField,validators
from passlib.hash import sha256_crypt
from functools import wraps
import pandas as pd
import random
import time
import sys
app = Flask(__name__)
app.secret_key= "ybblog"
app.config["MYSQL_HOST"] = "localhost"
app.config["MYSQL_USER"] = "root"
app.config["MYSQL_PASSWORD"] = ""
app.config["MYSQL_DB"] = "ybblog"
app.config["MYSQL_CURSORCLASS"] = "DictCursor"
mysql = MySQL(app)
#app.route("/")
def index():
return render_template("site.html")
#app.route("/maps")
def about():
return render_template("maps.html")
#Atama Url
#app.route("/sonuc",methods=["GET","POST"])
def sonuc():
cursor = mysql.connection.cursor()
sorgu = "Select * From site"
result = cursor.execute(sorgu)
if result >0:
articles = cursor.fetchall()
cursor.execute("DELETE FROM site")
mysql.connection.commit()
cursor.close()
return render_template("sonuc.html",articles= articles)
else:
cursor.execute("DELETE FROM site")
mysql.connection.commit()
cursor.close()
return render_template("site.html")
cursor.execute("DELETE FROM site")
mysql.connection.commit()
cursor.close()
#app.route("/bilgi",methods=["GET","POST"])
def bilgi():
if request.method == "POST":
yer = pd.read_excel("yerler.xlsx")
keyword = request.form.get("keyword")
isimler = keyword.split(",")
time.sleep(1)
for isim in isimler:
rastgele = random.randint(1,999)
yeniYer = yer.iloc[rastgele]
cursor = mysql.connection.cursor()
sorgu = "Insert into site(yerler,bolge,teskilati,ACM,ili,isim) VALUES(%s,%s,%s,%s,%s,%s)"
cursor.execute(sorgu,(yeniYer["yerler"],yeniYer["bolge"],yeniYer["teskilati"],yeniYer["ACM"],yeniYer["ili"],isim))
mysql.connection.commit()
cursor.close()
flash("Başarılı...","success")
return redirect(url_for("sonuc")) #sonuca yönlendir
else:
flash("Olmadı ...","success")
return render_template("site.html")
if __name__ == "__main__":
app.run(debug=True)
builtins.IndexError
Traceback (most recent call last):
File "C:\Python35\lib\site-packages\flask\app.py", line 2309, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Python35\lib\site-packages\flask\app.py", line 2295, in wsgi_app
response = self.handle_exception(e)
File "C:\Python35\lib\site-packages\flask\app.py", line 1741, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Python35\lib\site-packages\flask\_compat.py", line 35, in reraise
raise value
File "C:\Python35\lib\site-packages\flask\app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "C:\Python35\lib\site-packages\flask\app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Python35\lib\site-packages\flask\app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Python35\lib\site-packages\flask\_compat.py", line 35, in reraise
raise value
File "C:\Python35\lib\site-packages\flask\app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Python35\lib\site-packages\flask\app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\WeLoo\Desktop\YBBLOG\site2.py", line 60, in bilgi
yeniYer = yer.iloc[rastgele]
File "C:\Python35\lib\site-packages\pandas\core\indexing.py", line 1478, in __getitem__
return self._getitem_axis(maybe_callable, axis=axis)
File "C:\Python35\lib\site-packages\pandas\core\indexing.py", line 2102, in _getitem_axis
self._validate_integer(key, axis)
File "C:\Python35\lib\site-packages\pandas\core\indexing.py", line 2009, in _validate_integer
raise IndexError("single positional indexer is out-of-bounds")
IndexError: single positional indexer is out-of-bounds
This part of the code seems to be the only part that has pandas related code and induces random behaviour because of random.randint(1, 999). File yerler.xsls probably doesn't have enough data and yeniYer = yer.iloc[rastgele] fails with that IndexError
yer = pd.read_excel("yerler.xlsx")
keyword = request.form.get("keyword")
isimler = keyword.split(",")
for isim in isimler:
rastgele = random.randint(1,999)
yeniYer = yer.iloc[rastgele]
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