我正在创建一个将学生与学校联系起来的 Flask 应用程序,我想添加一个功能,让学生搜索他们想要的学校。我的学校采用邮寄形式,按与学生的距离(如果他们提供位置)或按字母顺序排列。 请注意 - 请不要推荐flask-wooshalchemy。我曾多次尝试使用它,其过时的代码使其非常难以使用,尤其是对于像我这样经验很少的人。
main.routes.py 的代码:
@main.route("/", methods=['GET', 'POST'])
@main.route("/home", methods=['GET', 'POST'])
def home():
if current_user.is_anonymous:
return render_template('home_ams.html', title='Home')
if current_user.account_type == "Teacher":
return render_template('home_ams.html', title='Home')
form = LocationForm()
page = request.args.get('page', 1, type=int)
posts = Post.query.order_by(Post.school_title.desc()).paginate(page=page,
per_page=5)
posts_dis = Post.query.all()
location = session["location"]
flash(location, 'info')
for post in posts_dis:
api_key = "myapikey"
url1 = "https://maps.googleapis.com/maps/api/distancematrix/json?origins="
url2 = "&destinations="
url3 = "&mode=car&key="
origin = location
school = post.school_location_p
origin_up = origin.replace(' ', '+')
school_up = school.replace(' ', '+')
url_full = url1+origin_up+url2+school_up+url3+api_key
output = requests.get(url_full).json()
for obj in output['rows']:
for data in obj['elements']:
x = data['distance']['value']
y = x /1000
post.distance = round(y)
if post.distance != "X":
posts = Post.query.order_by(Post.distance.asc()).paginate(page=page,
per_page=5)
else:
posts = Post.query.order_by(Post.school_title.desc()).paginate(page=page,
per_page=5)
return render_template('home.html', posts=posts, form=form)