在Heroku上运行python代码时出现键错误

时间:2017-01-01 12:48:37

标签: python heroku keyerror

当我尝试在Heroku上运行应用程序时出现“KeyError:'ticker'”错误。

017-01-01T12:38:39.454671+00:00 heroku[router]: at=info method=GET path="/" host=tdiquandlsticker.herokuapp.com request_id=f8649dd9-cf7d-4409-bf01-94159b509ec5 fwd="100.35.108.201" dyno=web.1 connect=0ms service=2ms status=302 bytes=438
2017-01-01T12:38:39.525219+00:00 heroku[router]: at=info method=GET path="/index" host=tdiquandlsticker.herokuapp.com request_id=341dea59-15b8-43c7-b7dc-c54bd44aa715 fwd="100.35.108.201" dyno=web.1 connect=0ms service=7ms status=200 bytes=772
2017-01-01T12:38:44.830618+00:00 app[web.1]: TSLA
2017-01-01T12:38:44.862686+00:00 heroku[router]: at=info method=POST path="/index" host=tdiquandlsticker.herokuapp.com request_id=af6d4c58-9988-437d-962d-87eeef0ba8f5 fwd="100.35.108.201" dyno=web.1 connect=0ms service=563ms status=302 bytes=438
2017-01-01T12:38:45.178563+00:00 heroku[router]: at=info method=GET path="/graph" host=tdiquandlsticker.herokuapp.com request_id=475d90ec-db4c-4b84-9efe-2485c3154d8c fwd="100.35.108.201" dyno=web.1 connect=0ms service=154ms status=200 bytes=46210
2017-01-01T12:39:07.518060+00:00 heroku[router]: at=info method=POST path="/graph" host=tdiquandlsticker.herokuapp.com request_id=e43270fa-fdde-4c7c-8c6f-be26043d7103 fwd="100.35.108.201" dyno=web.1 connect=0ms service=138ms status=200 bytes=59906
2017-01-01T12:39:30.557638+00:00 heroku[router]: at=info method=POST path="/graph" host=tdiquandlsticker.herokuapp.com request_id=05e844a4-3e7c-4649-8718-80e02936be37 fwd="100.35.108.201" dyno=web.1 connect=0ms service=133ms status=200 bytes=70237
2017-01-01T12:40:39.739658+00:00 app[web.1]: Exception on /graph [POST]
2017-01-01T12:40:39.739673+00:00 app[web.1]: Traceback (most recent call last):
2017-01-01T12:40:39.739675+00:00 app[web.1]:   File "/app/.heroku/python/lib/python2.7/site-packages/flask/app.py", line 1817, in wsgi_app
2017-01-01T12:40:39.739676+00:00 app[web.1]:     response = self.full_dispatch_request()
2017-01-01T12:40:39.739677+00:00 app[web.1]:   File "/app/.heroku/python/lib/python2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request
2017-01-01T12:40:39.739677+00:00 app[web.1]:     rv = self.handle_user_exception(e)
2017-01-01T12:40:39.739678+00:00 app[web.1]:   File "/app/.heroku/python/lib/python2.7/site-packages/flask/app.py", line 1381, in handle_user_exception
2017-01-01T12:40:39.739678+00:00 app[web.1]:     reraise(exc_type, exc_value, tb)
2017-01-01T12:40:39.739678+00:00 app[web.1]:   File "/app/.heroku/python/lib/python2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request
2017-01-01T12:40:39.739679+00:00 app[web.1]:     rv = self.dispatch_request()
2017-01-01T12:40:39.739679+00:00 app[web.1]:   File "/app/.heroku/python/lib/python2.7/site-packages/flask/app.py", line 1461, in dispatch_request
2017-01-01T12:40:39.739680+00:00 app[web.1]:     return self.view_functions[rule.endpoint](**req.view_args)
2017-01-01T12:40:39.739681+00:00 app[web.1]:   File "/app/app.py", line 48, in this_graph
2017-01-01T12:40:39.739681+00:00 app[web.1]:     ticker = app.vars['ticker']
2017-01-01T12:40:39.739682+00:00 app[web.1]: KeyError: 'ticker'
2017-01-01T12:40:39.745421+00:00 heroku[router]: at=info method=POST path="/graph" host=tdiquandlsticker.herokuapp.com request_id=a5c76fac-5cb3-4c9b-8c9b-f89af9884977 fwd="100.35.108.201" dyno=web.1 connect=0ms service=9ms status=500 bytes=456

我的python代码是

from flask import Flask, render_template, request, redirect
import requests
import pandas as pd
import numpy as np
import bokeh
from bokeh.embed import components
from bokeh.plotting import figure, show, output_server
from datetime import datetime
import sys
import logging

app = Flask(__name__)

app.logger.addHandler(logging.StreamHandler(sys.stdout))
app.logger.setLevel(logging.ERROR)

app.vars={}
app.df = pd.DataFrame()


@app.route('/')
def main():
  return redirect('/index')

@app.route('/index', methods=['GET', 'POST'])
def index():

    if request.method == 'GET':
        return render_template('/index.html')

    else:
        app.vars['ticker'] = request.form['ticker'].upper()
        url = 'https://www.quandl.com/api/v3/datasets/WIKI/%s.json?auth_token=3N24TTpyDxxw8wbazF6M' % (app.vars['ticker'])
        session = requests.Session()
        session.mount('http://', requests.adapters.HTTPAdapter(max_retries=3))
        sesh = session.get(url)
        injson=sesh.json()
        print (app.vars['ticker'])
        app.df=pd.DataFrame(injson['dataset']['data'])
        app.df.columns=injson['dataset']['column_names']
        return redirect('/graph')


@app.route('/graph', methods=['GET', 'POST'])
def this_graph():

    data = app.df
    ticker = app.vars['ticker']

    def makedate(x):
        return np.array(x, dtype=np.datetime64)

    if request.method == 'GET':
        thismax = max(data['Date'])
        thismin = min(data['Date'])
        app.maxdate = datetime.strptime(thismax, '%Y-%m-%d').strftime("%m/%d/%Y")
        app.mindate = datetime.strptime(thismin, '%Y-%m-%d').strftime("%m/%d/%Y")


        p1 = figure(x_axis_type = "datetime")
        p1.title.text = "Adjusted Closing Price"
        p1.grid.grid_line_alpha=0.3
        p1.xaxis.axis_label = 'Date'
        p1.yaxis.axis_label = 'Price'

        p1.line(makedate(data['Date']), data['Adj. Close'],  color='#A6CEE3', legend=ticker)

        show(p1)
    else:
        low = request.form['low']
        high = request.form['high']
        data['Date'] = makedate(data['Date'])
        toplot = data[(data['Date']<=high) & (data['Date']>=low)]
            #&data['Date']<high)]

        p1 = figure(x_axis_type = "datetime")
        p1.title.text = "Adjusted Closing Price"
        p1.grid.grid_line_alpha=0.3
        p1.xaxis.axis_label = 'Date'
        p1.yaxis.axis_label = 'Price'

        p1.line(toplot['Date'], toplot['Adj. Close'],  color='#A6CEE3', legend=ticker)

        show(p1)


    script, div = components(p1)
    return render_template('graph.html', thismin=app.mindate, thismax=app.maxdate, script=script, div=div, ticker=ticker)


  if __name__ == '__main__':
  app.debug = True
  app.run(port=33507)

我不太清楚为什么我会获得'ticker'的KeyError。我的html页面确实有'ticker'定义如下。

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>{{ticker}} data </title>
       <link rel="stylesheet" href="http://cdn.pydata.org/bokeh/release/bokeh-0.12.3.min.css" type="text/css" />
      <script type="text/javascript" src="http://cdn.pydata.org/bokeh/release/bokeh-0.12.3.min.js"></script>
       {{graphscript|safe}}
   </head>

    <body>
        <div>
            <h1>Input a Ticker Symbol</h1>
            <form id="input" method="post" action="index">
            <p>Input Ticker:
                <input type="text" name="ticker">
                <input type="submit" value="submit">
            </p>
            </form>
        </div>
    </body>
</html>

我的要求文件也提到了所有必要的组件。

numpy==1.7.0
scipy==0.18.1
dill==0.2.1
Flask==0.10.1
gunicorn==19.3.0
Jinja2==2.7.2
oauth==1.0.1
oauthlib==0.7.2
requests>=2.2.1
simplejson==3.8.0
quandl
bokeh==0.12.3
pandas==0.19.2

有人可以帮我弄清楚为什么会收到KeyError吗?

0 个答案:

没有答案