forked from lindsaymarkward/flaskdemo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathflaskdemo.py
54 lines (41 loc) · 1.53 KB
/
flaskdemo.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
from flask import Flask, render_template, request, redirect, url_for, session
import wikipedia
app = Flask(__name__)
# Set the secret key. Keep this really secret:
app.secret_key = 'IT@JCUA0Zr98j/3yXa R~XHH!jmN]LWX/,?RT'
@app.route('/')
def home():
return render_template("home.html")
@app.route('/about')
def about():
# return "I am still working on this"
return render_template("about.html")
@app.route('/search', methods=['POST', 'GET'])
def search():
if request.method == 'POST':
session['search_term'] = request.form['search']
return redirect(url_for('results'))
return render_template("search.html")
@app.route('/results')
def results():
search_term = session['search_term']
page = get_page(search_term)
return render_template("results.html", page=page)
def get_page(search_term):
try:
page = wikipedia.page(search_term)
except wikipedia.exceptions.PageError:
# no such page, return a random one
page = wikipedia.page(wikipedia.random())
except wikipedia.exceptions.DisambiguationError:
# this is a disambiguation page, get the first real page (close enough)
page_titles = wikipedia.search(search_term)
# sometimes the next page has the same name (different caps), so don't try the same again
if page_titles[1].lower() == page_titles[0].lower():
title = page_titles[2]
else:
title = page_titles[1]
page = get_page(wikipedia.page(title))
return page
if __name__ == '__main__':
app.run()