/
app.py
97 lines (65 loc) · 2.36 KB
/
app.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
''' A script to generate Wikipedia articles '''
import wikipedia
# Import flask library
from flask import Flask, render_template, url_for, request, redirect
from flask_sqlalchemy import SQLAlchemy
# Create a flask object of app.py
app = Flask(__name__)
# Configure the Database
app.config ['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
db = SQLAlchemy(app)
# Define the Database
class Article(db.Model):
id = db.Column(db.Integer, primary_key=True)
# will store the article title
title = db.Column(db.String(80), nullable=False)
# will store the article url
url = db.Column(db.String(80), nullable=False)
def __repr__(self):
return '<Article %r>' % self.article
# Function to Generate Wikipedia titles and their associate URLs
@app.route('/wiki_gen', methods=['POST','GET'])
def wiki_gen():
titles = wikipedia.random(pages=3)
for title in titles:
import wikipediaapi
# initialize wikipedia object
wiki = wikipediaapi.Wikipedia('en')
# Turn the titles into pages
page_py = wiki.page(title)
# Get page url
page_url = page_py.fullurl
# Save the page and URL in a dictionary
article = {
'article_title':title,
'article_url':page_url
}
print(article)
return article
# Create a default homepage route
@app.route('/', methods=['POST', 'GET'])
def index():
if request.method == 'POST':
article = wiki_gen()
new_article = Article(title=article['article_title'], url=article['article_url'])
try:
db.session.add(new_article)
db.session.commit()
return redirect('/')
except:
return 'There was an issue getting your article from the database'
else:
articles = Article.query.all()
return render_template('index.html', articles=articles)
# Delete Route
@app.route('/delete/<int:id>')
def delete(id):
article_to_delete = Article.query.get_or_404(id)
try:
db.session.delete(article_to_delete)
db.session.commit()
return redirect('/')
except:
return 'This article could not be deleted'
if __name__ == '__main__':
app.run(debug=True)