-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
362 lines (282 loc) · 10.1 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
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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
# -*- coding:utf-8 -*-
import os, json
from flask import Flask
from flask import url_for
from flask import render_template
from flask import request, session
from flask import make_response, redirect, abort
# if __name__ == '__main__':
# flask will take some action
app = Flask(__name__)
# load config (config.py -> class Config)
app.config.from_object('config.Config')
use_kvsession = False
if not use_kvsession:
# init Flask-Session
from flask.ext.session import Session
#from flask.ext.sqlalchemy import SQLAlchemy
#db = SQLAlchemy(app)
#app.config['SESSION_SQLALCHEMY'] = db
#app.config.update(SESSION_SQLALCHEMY=db)
Session(app)
else:
# init Flask-KVSession
from flask.ext.kvsession import KVSessionExtension
from simplekv.db.sql import SQLAlchemyStore
from sqlalchemy import create_engine, MetaData
print 'KVSESSION_DATABASE_URI:', app.config['KVSESSION_DATABASE_URI']
print 'KVSESSION_DATABASE_TABLE:', app.config['KVSESSION_DATABASE_TABLE']
engine = create_engine(app.config['KVSESSION_DATABASE_URI'])
metadata = MetaData(bind=engine)
store = SQLAlchemyStore(engine, metadata, \
app.config['KVSESSION_DATABASE_TABLE'])
metadata.create_all()
KVSessionExtension(store, app)
# init user and login check
from login_check import apply_login_check, login_check_exempt, user
#apply_login_check(app)
# =========== steps before request handling ===========
@app.before_request
def step1():
#app.logger.debug('step1')
# abort(401) # return a http 401 error page (generated by flask) as response
pass
@app.before_request
def step2():
#app.logger.debug('step2')
#return 'intercepted by step2 of before_request' # this will intercept reuest handling
pass
# ==== steps after request handling ====
@app.after_request
def after_step1(response):
#app.logger.debug(repr(response))
return response
# ==== sub url route modules ====
from suburl import sub
app.register_blueprint(sub, url_prefix='/sub')
# ======== url rules ========
#@login_check_exempt
@app.route('/')
def index():
resp = make_response('Index page.')
app.logger.debug('app.session_cookie_name: %s' % app.session_cookie_name)
return resp
#return "Index Page."
print '---- login check exempt:', index
# ======== variable url rules ========
# url param is passed as show_user(username="admin")
@app.route('/user/<username>/')
def show_user(username):
return "User %s" % username
# variable with type restriction
# available types:
# int -> integer
# float -> floating point number
# path -> like the default but also accept slash
@app.route('/post/<int:post_id>/')
def show_post(post_id):
return "Post %d" % post_id
# ======== unique urls / redirection behavior ========
# Flask's URL rules are based on Werkseug's routing module.
# url should end with a trailing slash
# and if access without a trailing slash,
# it will be added automatically(redirect)
# ======== url building ========
def test_url_building():
with app.test_request_context():
app.logger.debug(url_for('index'))
# url with parameter
app.logger.debug(url_for('show_user', username="admin"))
# extra value will be appended as querystring
app.logger.debug(url_for('show_post', post_id=33, extra="extra_value"))
# static url
app.logger.debug(url_for('static', filename='style.css'))
# ======== HTTP methods in url rule ========
# supported methods:
# GET -> just get
# HEAD -> GET without content (only http header)
# POST -> data stored only once
# PUT -> server might trigger the store precedure multiple times
# by overwriting the old values.
# DELETE -> remove info at the give location
# OPTIONS -> used to figure out supported methods of a url.
@app.route('/get_post/', methods=['GET', 'POST'])
def get_post():
if request.method == 'POST':
return 'post request'
else:
return 'get request'
# ======== static files ========
# create dir static
# url "/static/*" will access files in static dir
# ======== tempalte ========
# flask use Jinja2
# create dir templates
# template files will be searched in templates
# below is accessible in template:
# request, session, g obj, get_flashed_messages func
# *note:
# g obj is something in whicn you can store information for your own needs.
@app.route('/hello/')
@app.route('/hello/<name>')
def hello(name=None):
return render_template('hello.html', name=name)
# ======== request ========
# by global flask.request object
# which is context locals -> thread safe
@app.route('/login/', methods=['POST', 'GET'])
def login():
err = None
app.logger.debug(dict(request.args)) # access querystring params
if request.method == 'POST':
# if password or username not in request.form:
# -> KeyError -> HTTP 404 (automatically)
if request.form['username'] == 'admin' \
and request.form['password'] == '123456':
return 'logged in.'
else:
err = "invalid username or password"
return render_template('login.html', error=err)
# ======== file uploads ========
@app.route('/upload/', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
f = request.files['the_file'] # the_file -> name of the file field
f.save(os.path.join('uploaded', f.filename))
return 'file uploaded'
elif request.method == 'GET':
return render_template('upload_file.html')
else:
return "not supported method for url: /upload/"
# ======== request arams ========
@app.route(r'/request_demonstration/', methods=['GET', 'POST'])
def request_demonstration():
print 'query string:', request.args
print 'request data:', request.data
print 'form data:', request.form
print 'params(form+query_string):', request.values
print 'files(from form data):', request.files
print 'cookies:', request.cookies
print 'http headers:', request.headers
print 'request path:', request.path
print 'request full path:', request.full_path
print 'request url:', request.url
print 'request base url(without querystring):', request.url
print 'url root:', request.url_root
print 'host url:', request.host_url
print 'host:', request.host
print 'host:', request.host
print 'access route:', request.access_route
print 'remote addr:', request.remote_addr
return 'request demonstrated in console.'
# ======== cookie ========
# flask.request.cookies
@app.route('/show_cookies/')
def show_cookies():
return json.dumps(request.cookies)
@app.route('/set_cookies/')
def set_cookies():
resp = make_response(render_template('cookies.html', info="add cookie"))
resp.set_cookie('test_cookie', 'This is test cookie value.')
return resp
@app.route('/del_cookies/')
def del_cookies():
resp = make_response(render_template('cookies.html', info='delete cookie'))
resp.set_cookie('test_cookie', '', expires=0) # set expiration to 1970
return resp
# ======== redirect and errors ========
@app.route('/redirect/')
def redirect_handler():
app.logger.debug('redirect')
return redirect(url_for('abort_handler'))
@app.route('/abort/')
def abort_handler():
app.logger.debug('abort')
#abort(404) # this will return http 404 page as response
# ======== custom error page ========
@app.errorhandler(404)
def page_not_found(error):
resp = make_response(render_template('page_not_found.html'), 404)
resp.headers['X-Something'] = 'A custom header'
return resp
# ======== response ========
# view return response obj -> return it directly
# view return string -> response obj is created with string and default params
# view return tuple -> tuple must be in the form of (response, status, headers)
# where:
# status -> override the status code
# headers -> list or dict of additional header values
# ======== sessions ========
# by default, FLask session is stored in signed cookies
@app.route('/show_session/')
def show_session():
from flask.ext.kvsession import SessionID
print '=== session created time:', SessionID.unserialize(session.sid_s).created
print '=== session object', session._get_current_object()
return json.dumps(dict(session), indent=4)
@app.route('/set_session/')
def set_session():
session['test'] = 'test session value'
return 'set session value'
@app.route('/pop_session/')
def session_pop():
session.pop('test', None)
return 'delete session value'
@app.route('/del_session/')
def del_session():
print 'before destroy session'
session.destroy()
print 'after destroy session'
return 'session deleted from db.'
#@login_check_exempt
@app.route(r'/simple_login/')
def simple_login():
if not user:
abort(500)
user['username'] = 'admin'
user['password'] = '123456'
return 'user info in db'
@app.route(r'/logout/')
def logout():
if not user:
abort(500)
user.destroy()
return 'user session deleted'
# ======= flask_kvsession ======
# bugs:
# Expiration of sid (singed) in cookie is refreshed per request,
# while the lifetime of session data (in backend db) will not change.
#
# session.sid_s:
# key in db. format: "id_created"
#
# open_session:
# no app.secret_key: NullSession
# no session_id in cookie: make new session
# session expoired: KeyError exception
# session exists and not expired: return session(KVSession)
#
# save_session:
# save session if modified
# if session.sid_s is None: session.sid_s = new_signed_session_id
# save procedure: save data to db; save signed sid_s to cookie(expiration is refreshed)
# ======= Flask-Session =========
#@login_check_exempt
@app.route(r'/test/')
def test():
"""
a test interface
"""
app.logger.debug('session.permanent: %s' % session.permanent)
return 'a test interface'
if __name__ == '__main__':
# debug mode:
# changed code will be reload automatically
# traceback will be shown on web page.
# enable:
# app.debug=True
# or
# app.run(debug=True)
#app.debug = True
app.run(host='0.0.0.0', debug=True)
#test_url_building()