I'm attempting to create an application to retrieve and analyse emails sent through gmail. I'm using an alteration on the tutorial found here;
http://www.voidynullness.net/blog/2013/07/25/gmail-email-with-python-via-imap/
readmail.py
EMAIL_ACCOUNT = "*****"
PASSWD = "*****"
def process_mailbox(M):
rv, data = M.search(None, "ALL")
resp, items = M.search(None, "ALL")
if rv != 'OK':
print("No messages found!")
return
for num in data[0].split():
rv, data, = M.fetch(num, '(RFC822)')
if rv != 'OK':
print("ERROR getting message", num)
return
msg = email.message_from_bytes(data[0][1])
hdr = email.header.make_header(email.header.decode_header(msg['Subject']))
if msg.is_multipart():
for part in msg.get_payload():
body = part.get_payload()
subject = str(hdr)
print('Message %s: %s' % (num, subject))
print('Body:', body)
M = imaplib.IMAP4_SSL('imap.gmail.com',993)
try:
rv, data = M.login(EMAIL_ACCOUNT, PASSWD)
except imaplib.IMAP4.error:
print ("LOGIN FAILED!!! ")
sys.exit(1)
print(rv, data)
rv, data = M.select("INBOX")
if rv == 'OK':
print("Processing mailbox...\n")
process_mailbox(M)
M.close()
else:
print("ERROR: Unable to open mailbox ", rv)
M.logout()
When I run this code through the command line the output is as expected, however when ran through a basic flask import the entire thing falls apart.
app.py
from flask import Flask, render_template, jsonify, request
from readmail import process_mailbox
import json
import imaplib
app = Flask(__name__)
#app.route('/')
def homepage():
return render_template('index.html')
#app.route('/test')
def test():
return json.dumps({'name': process_mailbox(imaplib.IMAP4_SSL('imap.gmail.com',993)).subject})
if __name__ == '__main__':
app.run(use_reloader=True, debug=True)
The error I receive is;
Traceback (most recent call last):
File "C:\Python34\lib\site-packages\flask\app.py", line 1997, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Python34\lib\site-packages\flask\app.py", line 1985, in wsgi_app
response = self.handle_exception(e)
File "C:\Python34\lib\site-packages\flask\app.py", line 1540, 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 1982, in wsgi_app
response = self.full_dispatch_request()
File "C:\Python34\lib\site-packages\flask\app.py", line 1614, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Python34\lib\site-packages\flask\app.py", line 1517, in handle_user_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 1612, in
full_dispatch_request
rv = self.dispatch_request()
File "C:\Python34\lib\site-packages\flask\app.py", line 1598, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\user\project\flask\venv\Project\app.py", line 13, in test
return json.dumps({'name':
process_mailbox(imaplib.IMAP4_SSL('imap.gmail.com',993)).subject})
File "C:\Users\user\project\flask\venv\Project\readmail.py", line 14, in process_mailbox
M.select('"[Gmail]/All Mail"')
File "C:\Python34\lib\imaplib.py", line 683, in select
typ, dat = self._simple_command(name, mailbox)
File "C:\Python34\lib\imaplib.py", line 1134, in _simple_command
return self._command_complete(name, self._command(name, *args))
File "C:\Python34\lib\imaplib.py", line 882, in _command
', '.join(Commands[name])))imaplib.error: command SELECT illegal in state NONAUTH, only allowed in
states AUTH, SELECTED
I've made several attempts this past week to find out ways to fix this error so any help would be appreciated.
Firstly, looking at the end of the traceback, you've got imaplib.error: command SELECT illegal in state NONAUTH, only allowed in states AUTH, SELECTED - and going back to the two lines in the traceback for your code:
app.py, test ... return json.dumps({'name': process_mailbox(imaplib.IMAP4_SSL('imap.gmail.com',993)).subject})
readmail.py process_mailbox ... M.select('"[Gmail]/All Mail"')
I've trimmed some excess here, but in test, you are only connecting to the Gmail IMAP server, but not logging in. The following code is what your ffirst file does:
M = imaplib.IMAP4_SSL('imap.gmail.com',993)
try:
rv, data = M.login(EMAIL_ACCOUNT, PASSWD)
except imaplib.IMAP4.error:
print ("LOGIN FAILED!!! ")
sys.exit(1)
Also, process_mailbox will only return null, it changes the object you've passed directly.
Related
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 have the following class that I am using to pool connections for my application.
import os
import psycopg2
import contextlib
from psycopg2 import pool
from contextlib import contextmanager
class DbHandler:
def __init__(self):
self.reconnect_pool()
def reconnect_pool(self):
self.pgPool = psycopg2.pool.SimpleConnectionPool(1, 128, user=os.getenv("PGUSER"), password=os.getenv("PGPASSWORD"), host=os.getenv("PGHOST"), port=os.getenv("PGPORT"), database=os.getenv("PGDATABASE"))
# Get Cursor
#contextmanager
def get_cursor(self):
if(self.pgPool):
conn = self.pgPool.getconn()
if(conn):
try:
yield conn.cursor()
conn.commit()
finally:
self.pgPool.putconn(conn)
else:
self.reconnect_pool()
# Get Cursor
#contextmanager
def get_connection(self):
if(self.pgPool):
conn = self.pgPool.getconn()
if(conn):
try:
yield conn
finally:
self.pgPool.putconn(conn)
else:
self.reconnect_pool()
# Helper function
def getRows(self, cursor):
rows=[]
row = cursor.fetchone()
while row is not None:
rows.append(row)
row = cursor.fetchone()
return rows
def getPoolSize(self):
if(self.pgPool):
return len(self.pgPool._used)
else:
return -1
I am executing the code in the following manner inside my code by instantiating and calling the cursor.
def Login(self,username,password):
with self.db.get_cursor() as psCursor:
psCursor.execute("select users.username, users.id, string_agg(coalesce(keys.service, ''), ',') from users left join keys on keys.user_id = users.id where users.username = '" + username + "' and users.password='" + password + "'" + "group by (users.username,users.id)")
rows = self.db.getRows(psCursor)
if len(rows) == 0:
return None
if len(rows) > 0:
return rows[0]
But once i stop using the application for a while and try to execute any sql query. I get the error below
2020-09-01T07:11:05.074414377Z File "/usr/local/lib/python3.7/site-packages/gunicorn/workers/gthread.py", line 284, in handle
2020-09-01T07:11:05.074428178Z keepalive = self.handle_request(req, conn)
2020-09-01T07:11:05.074432778Z File "/usr/local/lib/python3.7/site-packages/gunicorn/workers/gthread.py", line 333, in handle_request
2020-09-01T07:11:05.074438078Z respiter = self.wsgi(environ, resp.start_response)
2020-09-01T07:11:05.074442378Z File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 2463, in __call__
2020-09-01T07:11:05.074446678Z return self.wsgi_app(environ, start_response)
2020-09-01T07:11:05.074450879Z File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 2449, in wsgi_app
2020-09-01T07:11:05.074455079Z response = self.handle_exception(e)
2020-09-01T07:11:05.074459279Z File "/usr/local/lib/python3.7/site-packages/flask_cors/extension.py", line 161, in wrapped_function
2020-09-01T07:11:05.074463479Z return cors_after_request(app.make_response(f(*args, **kwargs)))
2020-09-01T07:11:05.074467779Z File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1866, in handle_exception
2020-09-01T07:11:05.074472080Z reraise(exc_type, exc_value, tb)
2020-09-01T07:11:05.074476280Z File "/usr/local/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
2020-09-01T07:11:05.074480580Z raise value
2020-09-01T07:11:05.074484580Z File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 2446, in wsgi_app
2020-09-01T07:11:05.074488780Z response = self.full_dispatch_request()
2020-09-01T07:11:05.074492880Z File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1951, in full_dispatch_request
2020-09-01T07:11:05.074497181Z rv = self.handle_user_exception(e)
2020-09-01T07:11:05.074501181Z File "/usr/local/lib/python3.7/site-packages/flask_cors/extension.py", line 161, in wrapped_function
2020-09-01T07:11:05.074505381Z return cors_after_request(app.make_response(f(*args, **kwargs)))
2020-09-01T07:11:05.074509581Z File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1820, in handle_user_exception
2020-09-01T07:11:05.074513781Z reraise(exc_type, exc_value, tb)
2020-09-01T07:11:05.074520082Z File "/usr/local/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
2020-09-01T07:11:05.074524382Z raise value
2020-09-01T07:11:05.074528382Z File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1949, in full_dispatch_request
2020-09-01T07:11:05.074532682Z rv = self.dispatch_request()
2020-09-01T07:11:05.074536682Z File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1935, in dispatch_request
2020-09-01T07:11:05.074541083Z return self.view_functions[rule.endpoint](**req.view_args)
2020-09-01T07:11:05.074545183Z File "/whaii/routes/index.py", line 126, in login
2020-09-01T07:11:05.074549383Z user = MatchFunc.Login(str(data.get('username')),str(data.get('password')))
2020-09-01T07:11:05.074556783Z File "/whaii/routes/Whaii_Engine.py", line 148, in Login
2020-09-01T07:11:05.074562384Z psCursor.execute("select users.username, users.id, string_agg(coalesce(keys.service, ''), ',') from users left join keys on keys.user_id = users.id where users.username = '" + username + "' and users.password='" + password + "'" + "group by (users.username,users.id)")
2020-09-01T07:11:05.074567584Z psycopg2.DatabaseError: SSL SYSCALL error: Connection timed out
I am guessing it is the way I am calling the cursor. It would be great if someone could point out how I can reuse the connection pool.
Also, I ran SELECT count(*) FROM pg_stat_activity; and I can see that there are about 26 connections that are active but I am confused as to why the query fails.
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]
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
I'm working with League of Legends API, and I'm trying to get Ranked Datas from JSON file. But, if the player is not Level 30, he doesn't have his file.
So here
def getRankedData(region, ID, APIkey):
URL = "https://" + region + ".api.pvp.net/api/lol/" + region + "/v2.5/league/by-summoner/" + ID + "/entry?api_key=" + APIkey
response = requests.get(URL)
return response.json()
It won't get JSON file, because it doesn't exist. How do i can do, that if the URL doesn't exist and doesn't have the JSON file, it returns the string.
Here, I'm returning the datas to HTML page. But this isn't work too.
region = request.form['region']
summonerName = request.form['summonerName']
APIkey = "45afde27-b628-473f-9a94-feec8eb86094"
types = request.form['types']
responseJSON = getData(region, summonerName, APIkey)
ID = responseJSON[summonerName]['id']
ID = str(ID)
responseJSON2 = getRankedData(region, ID, APIkey)
if not responseJSON2:
divisionName = "Unranked"
else:
divisionName = responseJSON2[ID][0]['name']
responseJSON3 = getChallengerPlayers(region, str(types), APIkey)
challengerPlayers = responseJSON3['entries'][0]['wins']
#print challengerPlayers
return render_template('form_action.html', ID = ID, divisionName = divisionName, challengerPlayers = challengerPlayers)
I'm getting this error:
Traceback (most recent call last)
File "C:\Python27\lib\site-packages\flask\app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Python27\lib\site-packages\flask\app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "C:\Python27\lib\site-packages\flask\app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Python27\lib\site-packages\flask\app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "C:\Python27\lib\site-packages\flask\app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Python27\lib\site-packages\flask\app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Python27\lib\site-packages\flask\app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Python27\lib\site-packages\flask\app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\Hanisek\Documents\Visual Studio 2015\Projects\FlaskWebProject2\FlaskWebProject2\FlaskWebProject2\views.py", line 53, in hello
responseJSON2 = getRankedData(region, ID, APIkey)
File "C:\Users\Hanisek\Documents\Visual Studio 2015\Projects\FlaskWebProject2\FlaskWebProject2\FlaskWebProject2\views.py", line 21, in getRankedData
Open an interactive python shell in this framereturn response.json()
File "C:\Python27\lib\requests\models.py", line 805, in json
return complexjson.loads(self.text, **kwargs)
File "C:\Python27\lib\json\__init__.py", line 338, in loads
return _default_decoder.decode(s)
File "C:\Python27\lib\json\decoder.py", line 366, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Python27\lib\json\decoder.py", line 384, in raw_decode
raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded
dont know a ton about LOL but is there a reason that you cant have your program use and if/then statement to check the level of the player and then only check for the json file if the player is a high enough level to have one?
You can try checking if the URL exists, JSON is proper format or if the page throws 40X status codes
try:
r = requests.get("URL")
assert r.status_code < 400
return r.json()
except (ValueError, ConnectionError, AssertionError):
return ''
It's always a good idea to check what the api url is returning by running it in your browser. I'm guessing that it's returning a 404 error because the information doesn't exist.
In that case, I recommend checking to see if there is a 404 error before proceeding with the JSON parsing.
Request has a function called status_code that will return the 404 error if there is one.
Example code:
r = request.get("API STRING")
if r.status_code != 404:
r.json()