如何使用Python/Flask在heroku中显示index.html页面

How to show index.html page in heroku using Python/Flask

本文关键字:显示 index html 页面 heroku 何使用 Python Flask      更新时间:2023-09-26

我已经将我的第一个Python/Flask应用程序部署到heroku。该应用程序包含一个html页面,比如index.html,其中有一个javascript函数,该函数可以创建对运行在"url"上的python应用程序的查询

function getDistance(position) {
                         url = 'http://127.0.0.1:5000/geodesicDistance';
                         query = position.coords.latitude.toString()+','+position.coords.longitude.toString();
                         $.get(url, {'q': query},function(data) {
                         $('#results .distance')[0].innerHTML = Math.round(data['result']['distance']*1000)/1000;
                         })
}

python应用程序接受查询并返回结果

该应用程序实际运行于http://geodesicdistance.herokuapp.com/但是我无法显示根文件夹

中的index.html页面

在点击index.html之前,您必须在烧瓶应用程序中创建路线。

你会想要这样的东西:

from flask import Flask
from flask import render_template
app = Flask(__name__)
@app.route('/')
def geo_distance():
    return render_template('index.html')
if __name__ == '__main__':
    app.run()

然后,当您点击http://geodesicdistance.herokuapp.com/时,它将呈现index.html,它应该运行您的JS。

您还需要一条通往/geodesicDistance的路线。

另外,getDistance()函数中的url参数应该是/geodesicDistance-您不需要127.0.0.1:5000

我已经添加了路由,并将上面Javascript中包含的url修改为"/goldgroundDistance"。现在html页面正在渲染,但我无法获得距离值,就好像查询没有进行一样

app = Flask(__name__)
@app.route("/")
def renderIndex():
    return render_template("index.html")
@app.route("/geodesicDistance")
def geodesicDistance():
    query = parseQ(request.args)
    if query:
        position = geocodeAddress(query)
        if (position) and (len(position[u'results'])>0):
            lat = position[u'results'][0][u'geometry'][u'location'][u'lat']
            lng = position[u'results'][0][u'geometry'][u'location'][u'lng']
            response = createResponse(200,'Good query',lat,lng,position[u'results'][0]  [u'formatted_address'],getDistance(lat,lng))
        else:
            response = createResponse(400,'Bad formed query','','','','')
    else:
        response = createResponse(204,'No query     made',givenAddress['lat'],givenAddress['lng'],'White Bear Yard, 144a Clerkenwell Road,    London, EC1R 5DF, UK',0.0)                               
    http_response = make_response(json.dumps(response))
    http_response.headers['Content-type'] = 'application/json'
    http_response.headers['Access-Control-Allow-Origin'] = '*'
    return http_response

我的procfile看起来像这个

web: gunicorn geodesicDistance:app