-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
hello.py
270 lines (218 loc) · 8.4 KB
/
hello.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# FILE: hello.py
# AUTHOR: haya14busa
# License: MIT license
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
#=============================================================================
from random import choice
from nltk.corpus import stopwords
# from nltk import tokenize
from nltk import stem
from pymongo import Connection
# from pymongo.errors import ConnectionFailure
import os
from urllib.parse import urlsplit
''' Import the Flask class.
An Instance of this class will be our WSGI application
'''
from flask import Flask, url_for, request, render_template, redirect
''' Create an instance of this class.
The first argument is the name of the application's module or package.
Single module -> `__name__`
This is needed so that Flask knows where to look for templates, static files,
and so on
'''
app = Flask(__name__)
# Use the `route()` decorator
# to tell Flask what URL should trigger our function
@app.route('/')
def index():
# http://localhost:5000/
# return 'Index Page'
return render_template('index.html', title='Learning Flask')
# `route()` decorator is used to bind a function to a URL
@app.route('/hello')
@app.route('/hello/<name>')
def hello(name=None):
# http://localhost:5000/hello
# http://localhost:5000/hello/haya14busa
return render_template('hello.html', name=name)
@app.route('/post/<int:post_id>')
def show_post(post_id):
# Show the post with the given id, the id is an integer
# The following converters exists
# -------------------------------------------------
# int | accepts integers
# float | like `int` but for floating point values
# path | like the default but also accepts slashes
# -------------------------------------------------
# http://localhost:5000/post/14
return 'Post {id}'.format(id=post_id)
@app.route('/login', methods=['GET', 'POST'])
def login():
# http://localhost:5000/login
if request.method == 'POST':
return 'do_the_login()'
else:
return 'show_the_login_form()'
@app.route('/user')
def show_user_by_parameters():
# http://localhost:5000/user?user=haya14busa
user = request.args.get('user', '')
return user
@app.route('/user/<username>')
def show_user_profile(username):
# Show the user profile for that user
# http://localhost:5000/user/haya14busa
return 'User {username}'.format(username=username)
@app.route('/user/redirect')
def redirect_user_by_parameters():
# http://localhost:5000/user/redirect?user=haya14busa
user = request.args.get('user', '')
return redirect(url_for('hello', name=user))
@app.route('/learn/url_building')
def learn_url_building():
# with app.test_request_context():
# http://localhost:5000/learn/url_building
# url_for() looks for **function** instead of URL
text = \
'''
url_for('index') : {index}<br>
url_for('login') : {login}<br>
url_for('login', next='/') : {login_next}<br>
url_for('show_user_profile', username='haya14busa') : {profile}<br>
'''.format(index=url_for('index'),
login=url_for('login'),
login_next=url_for('login', next='/'),
profile=url_for('show_user_profile',
username='haya14busa'),)
return text
@app.route('/static_file')
def static_file():
return url_for('static', filename='style.css')
@app.route('/random')
def random():
# http://localhost:5000/random
return choice([str(i) for i in range(1000)])
# return choice(list(map((lambda x: str(x)), range(1000))))
# Learn POST by Change Title Sample Application
# http://localhost:5000/post_title
# http://localhost:5000/post_title?title=Happy+Vimming!
# See: http://kuroneko0208.hatenablog.com/entry/2013/11/27/043038
@app.route('/post_title')
def post_title():
title = request.args.get('title', 'Change Title')
return render_template('post_title.html', title=title)
@app.route('/send_title', methods=['POST'])
def send_title():
# Get values with `request.form['name']`
title = request.form['message']
return redirect(url_for('post_title', title=title))
@app.errorhandler(404)
def page_not_found(e):
return render_template('404.html'), 404
class NLTK:
def __init__(self):
self.stopwords = stopwords.words('english')
self._lancaster = stem.LancasterStemmer()
self._porter = stem.PorterStemmer()
self._lemmatizer = stem.WordNetLemmatizer()
def lancaster_stemmer(self, word):
return self._lancaster.stem(word)
def porter_stemmer(self, word):
return self._porter.stem(word)
def lemmatizer(self, word):
return self._lemmatizer.lemmatize(word)
n = NLTK()
@app.route('/nltk/stopwords')
def show_stopwords():
return str(n.stopwords)
@app.route('/nltk/stemmer')
def show_stem():
word = request.args.get('word', '')
lancaster_stem = n.lancaster_stemmer(word)
porter_stem = n.porter_stemmer(word)
return render_template('stemmer.html',
word=word,
lancaster_stem=lancaster_stem,
porter_stem=porter_stem,)
@app.route('/send_word_stem', methods=['POST'])
def send_word_stem():
# Get values with `request.form['name']`
word = request.form['message']
return redirect(url_for('show_stem', word=word))
#========================================
# MongoDB
def connect2mongodb(db):
try:
MONGO_URL = os.environ.get('MONGOHQ_URL', None)
if MONGO_URL:
# For heroku
c = Connection(host=MONGO_URL, port=27017)
parsed = urlsplit(MONGO_URL)
db_name = parsed.path[1:]
# Get your DB
return c[db_name]
else:
c = Connection(host='localhost', port=27017)
return c[db]
except:
return None
def searchMongo(dbh, searchword, field):
# db = connect2mongodb('mydict')
return dbh.words.find_one({field: searchword}, {'alc_etm.unum': 1})
@app.route('/mongodb')
def mongodb():
try:
db = connect2mongodb('mydict')
if not db:
return 'Could not connect to database'
aio_url_format = \
'http://home.alc.co.jp/db/owa/etm_sch?unum={unum}&stg=2'
word_link = '<a href="{url}" target="_blank">{word}</a>'
word = request.args.get('word', '')
redirect_ = request.args.get('redirect', 0)
word_db = (searchMongo(db, word, 'lemma') or
searchMongo(db, n.lemmatizer(word), 'lemma') or
searchMongo(db, n.porter_stemmer(word), 'lemma') or
searchMongo(db, n.porter_stemmer(word), 'stem') or
searchMongo(db, n.lancaster_stemmer(word), 'stem'))
if word_db:
word_url = aio_url_format.format(unum=word_db['alc_etm']['unum'])
if redirect_:
# http://localhost:5000/mongodb?word=connect&redirect=1
return redirect(word_url)
else:
# http://localhost:5000/mongodb?word=connect
return word_link.format(url=word_url, word=word)
else:
return 'Not found'
except Exception as e:
return str(e)
def main():
# app.run(debug=True) enable the server reload itself on code changes
# same as `app.debug = True`
# app.debug = True
app.run()
if __name__ == '__main__':
main()