Python:Flask返回两个路由的内部服务器错误

时间:2017-03-09 03:05:00

标签: python mysql flask

我需要两个输入,可以使用Stock和Stockcode访问同一个数据库。 但是,它返回内部服务器错误

我的代码如下:

@app.route('/NYSE/<Stock>', methods=['GET'])
@app.route('/NYSE/<Stockcode>', methods=['GET'])
def NYSEstock(Stock,Stockcode):
    try:
        call = db.session.execute("SELECT * FROM NYSE WHERE (Stockcode LIKE :param or Stock LIKE :param1)",{"param":Stockcode,"param1":Stock})
        c = call.fetchall()
        c1 = [OrderedDict(zip(col,t)) for t in c]
    except Exception:
        return 'Error: unable to fetch items'
    #return "hihi"
    return jsonify({'Stock': c1})

MySQL中的数据如下:

{
  "Stock": [
    {
      "index": 189,
      "Stock": "IBM",
      "Stockcode": "4350",
      "MACD": "No",
      "STOCH": "No",
      "RSI": "No",
}]

我希望路线/NYSE/IBM/NYSE/4350都能够访问数据。 /纽约证券交易所将包含许多股票,但/NYSE/<Stock>/NYSE/<Stockcode&gt;,我们将能够找到特定股票。

将它分成两个就能解决问题,但我更喜欢只有一个def

@app.route('/NYSE/<Stock>', methods=['GET'])
def NYSEstock(Stock):
    try:
        call = db.session.execute("SELECT * FROM NYSE WHERE (Stock LIKE :param )",{"param":Stock})
        c = call.fetchall()
        c1 = [OrderedDict(zip(col,t)) for t in c]
    except Exception:
        return 'Error: unable to fetch items'
    #return "hihi"
    return jsonify({'Stock': c1})

@app.route('/NYSEstockcode/<Stockcode>', methods=['GET'])
def NYSEstockcode(Stock):
    try:
        call = db.session.execute("SELECT * FROM NYSE WHERE (Stockcode LIKE :param )",{"param":Stockcode})
        c = call.fetchall()
        c1 = [OrderedDict(zip(col,t)) for t in c]
    except Exception:
        return 'Error: unable to fetch items'
    #return "hihi"
    return jsonify({'Stock': c1})

1 个答案:

答案 0 :(得分:0)

问题是NYSEstock功能,必须接受一个参数。因为app.route装饰器只添加一个规则,路由器只有一个参数,你可以参考下面的代码:

@app.route('/NYSE/<stock_or_id>', methods=['GET'])
@app.route('/NYSE/<stock_or_id>', methods=['GET'])
def NYSEstock(stock_or_id):
    try:
        call = db.session.execute("SELECT * FROM NYSE WHERE (Stockcode LIKE :param or Stock LIKE :param1)",{"param":stock_or_id,"param1":stock_or_id})
        c = call.fetchall()
        c1 = [OrderedDict(zip(col,t)) for t in c]
    except Exception:
       return 'Error: unable to fetch items'
   #return "hihi"
   return jsonify({'Stock': c1})