So I'm trying get auto-complete to work with python-ldap and flask.
Here's a test script ldapA.py:
import ldap
#first you must open a connection to the server
def query():
try:
l = ldap.open("server.net")
## searching doesn't require a bind in LDAP V3. If you're using LDAP v2, set the next line appropriately
## and do a bind as shown in the above example.
# you can also set this to ldap.VERSION2 if you're using a v2 directory
# you should set the next option to ldap.VERSION2 if you're using a v2 directory
l.protocol_version = ldap.VERSION3
l.set_option(ldap.OPT_REFERRALS, 0)
username="CN=user user,OU=bbbgbg,OU=bdbfd,DC=dsffd,DC=net"
passw="adsada"
l.simple_bind_s(username,passw)
except ldap.LDAPError, e:
print e
# handle error however you like
## The next lines will also need to be changed to support your search requirements and directory
baseDN = "ou=xds, ou=sd, dc=sd, dc=net"
searchScope = ldap.SCOPE_SUBTREE
## retrieve all attributes - again adjust to your needs - see documentation for more options
retrieveAttributes = ['name']
searchFilter = "name=*jace*"
try:
ldap_result_id = l.search(baseDN, searchScope, searchFilter, retrieveAttributes)
result_set = []
while 1:
result_type, result_data = l.result(ldap_result_id, 0)
if (result_data == []):
break
else:
## here you don't have to append to a list
## you could do whatever you want with the individual entry
## The appending to list is just for illustration.
if result_type == ldap.RES_SEARCH_ENTRY:
result_set.append(result_data)
res = result_set[0]
res1 = res[0]
res2 = res1[1]
res3 = res2["name"]
print res3[0]
except ldap.LDAPError, e:
print e
query()
It works as intended when I run it. It gives me my name from the AD.
Now when I call it from flask like this:
from flask import render_template
from app import app
from flask import request
from ldapA import query
#app.route('/')
#app.route('/index')
def index():
return render_template("index.html")
#app.route('/autocomplete', methods=['GET'])
def autocomplete():
return query()
I get:
127.0.0.1 - - [19/Jul/2017 14:08:58] "GET /autocomplete HTTP/1.1" 500 -
Traceback (most recent call last):
File "/home/jgar/receptionsignin/flask/lib/python2.7/site-packages/flask/app.py", line 1997, in __call__
return self.wsgi_app(environ, start_response)
File "/home/jgar/receptionsignin/flask/lib/python2.7/site-packages/flask/app.py", line 1985, in wsgi_app
response = self.handle_exception(e)
File "/home/jgar/receptionsignin/flask/lib/python2.7/site-packages/flask/app.py", line 1540, in handle_exception
reraise(exc_type, exc_value, tb)
File "/home/jgar/receptionsignin/flask/lib/python2.7/site-packages/flask/app.py", line 1982, in wsgi_app
response = self.full_dispatch_request()
File "/home/jgar/receptionsignin/flask/lib/python2.7/site-packages/flask/app.py", line 1614, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/jgar/receptionsignin/flask/lib/python2.7/site-packages/flask/app.py", line 1517, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/home/jgar/receptionsignin/flask/lib/python2.7/site-packages/flask/app.py", line 1612, in full_dispatch_request
rv = self.dispatch_request()
File "/home/jgar/receptionsignin/flask/lib/python2.7/site-packages/flask/app.py", line 1598, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/jgar/receptionsignin/app/views.py", line 13, in autocomplete
return query()
File "/home/jgar/receptionsignin/ldapA.py", line 36, in query
result_type, result_data = l.result(ldap_result_id, 0)
File "/home/jgar/receptionsignin/flask/lib/python2.7/site-packages/ldap/ldapobject.py", line 703, in result
resp_type, resp_data, resp_msgid = self.result2(msgid,all,timeout)
File "/home/jgar/receptionsignin/flask/lib/python2.7/site-packages/ldap/ldapobject.py", line 707, in result2
resp_type, resp_data, resp_msgid, resp_ctrls = self.result3(msgid,all,timeout)
File "/home/jgar/receptionsignin/flask/lib/python2.7/site-packages/ldap/ldapobject.py", line 714, in result3
resp_ctrl_classes=resp_ctrl_classes
File "/home/jgar/receptionsignin/flask/lib/python2.7/site-packages/ldap/ldapobject.py", line 734, in result4
resp_data = self._bytesify_results(resp_data, with_ctrls=add_ctrls)
File "/home/jgar/receptionsignin/flask/lib/python2.7/site-packages/ldap/ldapobject.py", line 266, in _bytesify_results
for (dn, fields) in results
File "/home/jgar/receptionsignin/flask/lib/python2.7/site-packages/ldap/ldapobject.py", line 219, in _maybe_rebytesify_text
assert isinstance(value, text_type), "Should return text, got bytes instead (%r)" % (value,)
AssertionError: Should return text, got bytes instead ('CN=sdsddsc,OU=sds,OU=sds,DC=sdds,DC=net')
I know that this line causes the trouble:
ldap_result_id = l.search(baseDN, searchScope, searchFilter, retrieveAttributes)
But I'm stumped as to why it happens when called in flask and not when run with python ldapA.py.
It seems to be the ldap lib internal error, but why does it only happen in flask and how could I fix it?
Thanks guys!
Turns out it was a unicode problem, for anyone having the same error:
Go to ldpaobject.py(whererver you have python-ldap installed)
Change
if PY2:
text_type = unicode
else:
text_type = str
to just
text_type = str
python-ldap should now work in flask
Related
Hi i'm getting this error. TypeError: Object of type ColumnClause is not JSON serializable.
Whole thing:
[2020-10-26 22:17:58,448] ERROR in app: Exception on /all-user [GET]
Traceback (most recent call last):
File "c:\users\ryand\.virtualenvs\main-api-ucgvpon1\lib\site-packages\flask\app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "c:\users\ryand\.virtualenvs\main-api-ucgvpon1\lib\site-packages\flask\app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "c:\users\ryand\.virtualenvs\main-api-ucgvpon1\lib\site-packages\flask\app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "c:\users\ryand\.virtualenvs\main-api-ucgvpon1\lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "c:\users\ryand\.virtualenvs\main-api-ucgvpon1\lib\site-packages\flask\app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "c:\users\ryand\.virtualenvs\main-api-ucgvpon1\lib\site-packages\flask\app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\ryand\Desktop\mealplansfree\main-api\api.py", line 36, in decorated
return f(*args, **kwargs)
File "C:\Users\ryand\Desktop\mealplansfree\main-api\api.py", line 59, in get_all_users
return jsonify({'users' : output})
File "c:\users\ryand\.virtualenvs\main-api-ucgvpon1\lib\site-packages\flask\json\__init__.py", line 370, in jsonify
dumps(data, indent=indent, separators=separators) + "\n",
File "c:\users\ryand\.virtualenvs\main-api-ucgvpon1\lib\site-packages\flask\json\__init__.py", line 211, in dumps
rv = _json.dumps(obj, **kwargs)
File "c:\users\ryand\appdata\local\programs\python\python38-32\lib\json\__init__.py", line 234, in dumps
return cls(
File "c:\users\ryand\appdata\local\programs\python\python38-32\lib\json\encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "c:\users\ryand\appdata\local\programs\python\python38-32\lib\json\encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "c:\users\ryand\.virtualenvs\main-api-ucgvpon1\lib\site-packages\flask\json\__init__.py", line 100, in default
return _json.JSONEncoder.default(self, o)
File "c:\users\ryand\appdata\local\programs\python\python38-32\lib\json\encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type ColumnClause is not JSON serializable
Here is the code for the above.
#app.route('/all-user', methods=['GET'])
#application_required
def get_all_users():
users = User.query.all()
output = []
for user in users:
user_data = {}
user_data['user_id'] = user.user_id
user_data['full_name'] = user.full_name
user_data['username'] = user.username
user_data['password'] = user.password
user_data['admin'] = user.admin
output.append(user_data)
return jsonify({'users' : output})
here is the secret key check
def application_required(f):
#wraps(f)
def decorated(*args, **kwargs):
token = None
if 'x-access-key' in request.headers:
token = request.headers['x-access-key']
if not token:
return jsonify({'message' : 'ERROR x-access-key missing or incorrect.'}), 401
if token == app.config['SECRET_KEY']:
return f(*args, **kwargs)
else:
return jsonify({'message' : 'ERROR x-access-key missing or incorrect.'}), 401
return decorated
If anyone knows whats going on or could guide me through whats going on and how to debug these that would be great!
I found the answer here: SQLAlchemy warning: column won't be part of the declarative mapping
I had missed in my User model in the username it was a lowercase c and not upper case C. This fixed the error and is now working. Thanks!
The cause can be data type. You are using lot of data types. Try to reduce data type changes.
I'm getting this error even I am to render the template. I tried changing the function names also.
This is happening due to flask(error) I think
Traceback (most recent call last):
File "/Users/ayyagari/Documents/DeepNews/web_2/venv/lib/python3.7/site-packages/flask/app.py", line 2463, in call
return self.wsgi_app(environ, start_response)
File "/Users/ayyagari/Documents/DeepNews/web_2/venv/lib/python3.7/site-packages/flask/app.py", line 2449, in wsgi_app
response = self.handle_exception(e)
File "/Users/ayyagari/Documents/DeepNews/web_2/venv/lib/python3.7/site-packages/flask/app.py", line 1866, in handle_exception
reraise(exc_type, exc_value, tb)
File "/Users/ayyagari/Documents/DeepNews/web_2/venv/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
raise value
File "/Users/ayyagari/Documents/DeepNews/web_2/venv/lib/python3.7/site-packages/flask/app.py", line 2446, in wsgi_app
response = self.full_dispatch_request()
File "/Users/ayyagari/Documents/DeepNews/web_2/venv/lib/python3.7/site-packages/flask/app.py", line 1951, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Users/ayyagari/Documents/DeepNews/web_2/venv/lib/python3.7/site-packages/flask/app.py", line 1820, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/Users/ayyagari/Documents/DeepNews/web_2/venv/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
raise value
File "/Users/ayyagari/Documents/DeepNews/web_2/venv/lib/python3.7/site-packages/flask/app.py", line 1949, in full_dispatch_request
rv = self.dispatch_request()
File "/Users/ayyagari/Documents/DeepNews/web_2/venv/lib/python3.7/site-packages/flask/app.py", line 1935, in dispatch_request
return self.view_functionsrule.endpoint
File "/Users/ayyagari/Documents/DeepNews/web_2/website/main.py", line 57, in register_user
return render_template(url_for('main.register_form'))
File "/Users/ayyagari/Documents/DeepNews/web_2/venv/lib/python3.7/site-packages/flask/templating.py", line 138, in render_template
ctx.app.jinja_env.get_or_select_template(template_name_or_list),
File "/Users/ayyagari/Documents/DeepNews/web_2/venv/lib/python3.7/site-packages/jinja2/environment.py", line 869, in get_or_select_template
return self.get_template(template_name_or_list, parent, globals)
File "/Users/ayyagari/Documents/DeepNews/web_2/venv/lib/python3.7/site-packages/jinja2/environment.py", line 830, in get_template
return self._load_template(name, self.make_globals(globals))
File "/Users/ayyagari/Documents/DeepNews/web_2/venv/lib/python3.7/site-packages/jinja2/environment.py", line 804, in _load_template
template = self.loader.load(self, name, globals)
File "/Users/ayyagari/Documents/DeepNews/web_2/venv/lib/python3.7/site-packages/jinja2/loaders.py", line 113, in load
source, filename, uptodate = self.get_source(environment, name)
File "/Users/ayyagari/Documents/DeepNews/web_2/venv/lib/python3.7/site-packages/flask/templating.py", line 60, in get_source
return self._get_source_fast(environment, template)
File "/Users/ayyagari/Documents/DeepNews/web_2/venv/lib/python3.7/site-packages/flask/templating.py", line 89, in _get_source_fast
raise TemplateNotFound(template)
jinja2.exceptions.TemplateNotFound: /register
Here is my code
from flask import (
Blueprint, redirect, render_template, request, url_for,
flash)
from website.db import get_db
bp = Blueprint('main', __name__)
#bp.route('/home')
def index():
return render_template("index.html")
#bp.route('/register')
def register_form():
return render_template("form.html")
#bp.route('/success')
def success():
return render_template("response.html")
#bp.route('/register_user', methods=["POST"])
def register_user():
if request.method == 'POST':
email_id = request.form['reg-email']
company = request.form['reg-company']
type_of_business = request.form['industry_type']
checkbox = request.form['reg-check']
db = get_db()
error = None
if not email_id:
error = 'Email ID is required.'
elif not company:
error = 'Company is required.'
elif not type_of_business:
error = 'Type of Business is required.'
elif not checkbox:
error = 'Accept the Terms and Conditions'
elif db.execute(
'SELECT id FROM beta_users WHERE email_id = ?', (email_id,)
).fetchone() is not None:
error = 'User {} is already registered.'.format(email_id)
if error is None:
db.execute(
'INSERT INTO beta_users (email_id, company, type_of_org, checkbox) VALUES (?, ?, ?, ?)',
(email_id, company, type_of_business, checkbox)
)
db.commit()
return redirect(url_for('main.success'))
flash(error)
return render_template(url_for('main.register_form'))
#bp.route('/error')
def errors():
return render_template("404.html")
API is also showing a 500 Internal server error
The problem is here:
return render_template(url_for('main.register_form'))
url_for returns a url to access the route via the Internet, which isn't what render_template uses. render_template is expecting a html/text file.
So, either replace that either with:
return render_template('register.html')
Or redirect the user to the other route, to let it do it's work:
from flask import redirect
...
return redirect(url_for('main.register'))
I am trying to run a project but everytime I try loading a specific page it throws away the following stack of error:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1982, in wsgi_app
response = self.full_dispatch_request()
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1614, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/local/lib/python2.7/dist-packages/flask_restplus/api.py", line 536, in error_router
return original_handler(e)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1517, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1612, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1598, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/nitin/Desktop/open-event-orga-server/app/views/users/events.py", line 91, in create_view
current_timezone = get_current_timezone()
File "/home/nitin/Desktop/open-event-orga-server/app/helpers/wizard/helpers.py", line 17, in get_current_timezone
match = geolite2.lookup(get_real_ip(True) or '127.0.0.1')
File "/usr/local/lib/python2.7/dist-packages/geoip.py", line 364, in lookup
return self._get_actual_db().lookup(ip_addr)
File "/usr/local/lib/python2.7/dist-packages/geoip.py", line 204, in lookup
return self._lookup(ip_addr)
File "/usr/local/lib/python2.7/dist-packages/geoip.py", line 249, in _lookup
packed_addr = pack_ip(ip_addr)
File "/usr/local/lib/python2.7/dist-packages/geoip.py", line 37, in pack_ip
raise ValueError('Malformed IP address')
ValueError: Malformed IP address
[2017-01-22 00:34:24 +0000] [6835] [ERROR] Error handling request /socket.io/?EIO=3&transport=websocket&sid=8bed14818d4046edb35bbc87f27d5164
And I am unable to figure out what exactly is a malformed IP address and the reason behind this error.
Following is the get_current_timezone() function:
def get_current_timezone():
match = geolite2.lookup(get_real_ip(True) or '127.0.0.1')
if match is not None:
return match.timezone
else:
return 'UTC'
And following is the get_real_ip() method:
def get_real_ip(local_correct=False):
try:
if 'X-Forwarded-For' in request.headers:
ip = request.headers.getlist("X-Forwarded-For")[0].rpartition(' ')[-1]
else:
ip = request.remote_addr or None
if local_correct and (ip == '127.0.0.1' or ip == '0.0.0.0'):
ip = urlopen('http://ip.42.pl/raw').read() # On local test environments
except:
ip = None
return ip
And the following is the portion of create event view that is creating this problem.:
#events.route('/create/', defaults={'step': ''})
#events.route('/create/<step>')
def create_view(step):
if step != '':
return redirect(url_for('.create_view', step=''))
hash = get_random_hash()
if CallForPaper.query.filter_by(hash=hash).all():
hash = get_random_hash()
current_timezone = get_current_timezone()
return render_template(
'gentelella/admin/event/wizard/wizard.html',
current_date=datetime.datetime.now(),
event_types=DataGetter.get_event_types(),
event_licences=DataGetter.get_event_licences(),
event_topics=DataGetter.get_event_topics(),
event_sub_topics=DataGetter.get_event_subtopics(),
timezones=DataGetter.get_all_timezones(),
cfs_hash=hash,
current_timezone=current_timezone,
payment_countries=DataGetter.get_payment_countries(),
payment_currencies=DataGetter.get_payment_currencies(),
included_settings=get_module_settings())
I have a question about flask python.
I tried learning how to build a web using flask, and there is some error. In this case I am using mongoengine as database and JWT(Json Web Token) and the alert error is like this: "TypeError: Expecting a string- or bytes-formatted key"
192.168.100.26 - - [22/Nov/2016 22:50:08] "POST /auth HTTP/1.1" 500 -
Traceback (most recent call last):
File "/home/def/.local/lib/python2.7/site-packages/flask/app.py", line 2000, in __call__
return self.wsgi_app(environ, start_response)
File "/home/def/.local/lib/python2.7/site-packages/flask/app.py", line 1991, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/home/def/.local/lib/python2.7/site-packages/flask/app.py", line 1567, in handle_exception
reraise(exc_type, exc_value, tb)
File "/home/def/.local/lib/python2.7/site-packages/flask/app.py", line 1988, in wsgi_app
response = self.full_dispatch_request()
File "/home/def/.local/lib/python2.7/site-packages/flask/app.py", line 1641, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/def/.local/lib/python2.7/site-packages/flask/app.py", line 1544, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/home/def/.local/lib/python2.7/site-packages/flask/app.py", line 1639, in full_dispatch_request
rv = self.dispatch_request()
File "/home/def/.local/lib/python2.7/site-packages/flask/app.py", line 1625, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/def/pr/flask/flask_deeper/test/routes/auth.py", line 26, in auth
access_token = _jwt.jwt_encode_callback(identity)
File "/usr/local/lib/python2.7/dist-packages/flask_jwt/__init__.py", line 70, in _default_jwt_encode_handler
return jwt.encode(payload, secret, algorithm=algorithm, headers=headers)
File "/usr/local/lib/python2.7/dist-packages/jwt/api_jwt.py", line 56, in encode
json_payload, key, algorithm, headers, json_encoder
File "/usr/local/lib/python2.7/dist-packages/jwt/api_jws.py", line 98, in encode
key = alg_obj.prepare_key(key)
File "/usr/local/lib/python2.7/dist-packages/jwt/algorithms.py", line 116, in prepare_key
raise TypeError('Expecting a string- or bytes-formatted key.')
TypeError: Expecting a string- or bytes-formatted key.
I thought the error was at this.
models/user.py
#staticmethod
def jwt_handler(token):
if not User.objects(token=token):
raise JWTError("Bad bad bad bad")
secret = str(current_app.config["JWT_SECRET_KEY"])
algorithm = str(current_app.config["JWT_ALGORITHM"])
options = {
'verify_' + claim: True
for claim in verify_claims
}
options.update({
'require_' + claim: True
for claim in required_claims
})
decode = jwt.decode(token, secret, options=options, algorithms=[algorithm])
return decode
#staticmethod
def authenticate(username, password):
user = User.objects(username=username)
if len(user) == 0:
return None
user = user[0]
user["id"] = str(user["id"])
if crypt.verify(password, user.password):
return user
return user
routes/user.py
def auth():
username = request.form.get("username")
password = request.form.get("password")
if not username:
raise BadRequest("Userna doesn't exists")
user = user_ctrl.read(username)
identity = _jwt.authentication_callback(username, password)
if identity:
access_token = _jwt.jwt_encode_callback(identity)
identity.update(push__token=access.decode("utf8"))
return _jwt.auth_response_callback(access_token, identity)
else:
raise JWTError("Bad bad bad very bad")
config.py
import os
from test.models import db
class Config(object):
db_name = os.getenv('MONGODB_NAME', 'third')
db_host = os.getenv('MONGODB_HOST', '127.0.0.1')
db_port = os.getenv('MONGODB_PORT', '5000')
JWT_SECRET_KEY = 'test123'
JWT_ALGORITHM = 'SH256'
JWT_AUTH_ENDPOINT = 'jwt'
JWT_AUTH_USERNAME_KEY = 'username'
JWT_AUTH_PASSWORD_KEY = 'password'
http.py
import logging.config
import jwt
from flask_jwt import JWT
from flask import Flask
from test import routes
from test.models import db, User
_jwt = JWT(authentication_handler=User.authenticate, identity_handler=User.identity)
_jwt.jwt_decode_callback=User.jwt_handler
def create_app(config):
app = Flask(__name__.split(',')[0])
app.register_blueprint(routes.user.bp)
app.register_blueprint(routes.auth.bp)
db.init_app(app)
_jwt.init_app(app)
return app
You have defined the configuration is config.py but have not added the configuration object to your flask app. Therefore, keys such as JWT_SECRET_KEY are not in your app config.
Flask-JWT's default_handler expects those values (Copied in case source changes)
def _default_jwt_decode_handler(token):
secret = current_app.config['JWT_SECRET_KEY']
algorithm = current_app.config['JWT_ALGORITHM']
leeway = current_app.config['JWT_LEEWAY']
In your case as that is not set, it returns None and trips the algorithms.py (which expects a string key).
Therefore, during your app initialization in http.py, you must add a call to app.config.from_object. Maybe something like this
def create_app(config):
app = Flask(__name__.split(',')[0])
# Edit the following to point it to your Config class
app.config.from_object(config.Config)
app.register_blueprint(routes.user.bp)
app.register_blueprint(routes.auth.bp)
db.init_app(app)
_jwt.init_app(app)
return app
On a side note, the name of JWT_ALGORITHM should be HS256 rather than SH256 (Although it doesn't matter as HS256 is the default and will be chosen since SH256 is not a valid algorithm)
This question already has an answer here:
Flask view raises TypeError: 'bool' object is not callable
(1 answer)
Closed 8 years ago.
I'm new to Python and just learning it as I work on this project, and this issue is really confusing me. Here's my code:
from flask import Flask
from datetime import datetime
# Setup app
app = Flask(__name__)
# Initialize data dict
data = {}
# Pretty-formats a time difference
def formatdifference(delta):
seconds = delta.total_seconds()
if (seconds < 60):
return "{seconds} seconds ago" % {"seconds": seconds}
return "{minutes} minutes ago" % {"minutes": seconds/60}
# Sets a device battery level
#app.route("/set/<device>/<int:battery>")
def set(device, battery):
data[device] = (battery, datetime.now())
return "done"
# Get's a device battery level
#app.route("/get/<device>")
def get(device):
if not device in data:
return "No heartbeats"
devicedata = data[device]
delta = datetime.now() - devicedata[1]
if (delta.total_seconds() > 10):
return "Last heartbeat {diff}" % {"diff": formatdifference(delta)}
return devicedata[0]
if __name__ == "__main__":
app.run(debug=True, host='0.0.0.0')
I call /set/phone/40. All good so far. Then I call /get/phone. Not so good. Here's the traceback:
TypeError: 'int' object is not callable
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1478, in full_dispatch_request
response = self.make_response(rv)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1577, in make_response
rv = self.response_class.force_type(rv, request.environ)
File "/usr/local/lib/python2.7/dist-packages/werkzeug/wrappers.py", line 825, in force_type
response = BaseResponse(*_run_wsgi_app(response, environ))
File "/usr/local/lib/python2.7/dist-packages/werkzeug/test.py", line 855, in run_wsgi_app
app_iter = app(environ, start_response)
TypeError: 'int' object is not callable
Using flask's debugger, I can see that in the last frame, app appears to be 40!
How on earth did this happen, and how can I solve it?
You should return a string object, not an int object:
Replace the following line:
return devicedata[0]
with:
return str(devicedata[0])
Or, replace the following line:
data[device] = (battery, datetime.now())
with:
data[device] = (str(battery), datetime.now())