Created
October 22, 2013 01:53
-
-
Save hirokazumiyaji/7094025 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding: utf-8 | |
from __future__ import unicode_literals | |
from flask import Flask, jsonify, session, request, redirect, url_for | |
app = Flask(__name__) | |
class User(object): | |
fixtures = { | |
'1': { | |
'name': "Johnson", | |
'age': 20, | |
'height': 180, | |
'weight': 70, | |
}, | |
'2': { | |
'name': "Mike", | |
'age': 25, | |
'height': 170, | |
'weight': 60, | |
}, | |
} | |
class DoesNotExist(Exception): | |
pass | |
def __init__(self, **kwargs): | |
for k, v in kwargs.items(): | |
setattr(self, k, v) | |
@classmethod | |
def get(cls, user_id): | |
try: | |
print type(user_id) | |
fixture = cls.fixtures[user_id] | |
except KeyError: | |
raise cls.DoesNotExist('user_id:{}'.format(user_id)) | |
return cls(**fixture) | |
def json_response(self): | |
return jsonify(user_name=self.name, | |
user_age=self.age, | |
user_height=self.height, | |
user_weight=self.weight) | |
@app.route('/') | |
def index(): | |
if 'userid' in session: | |
return redirect(url_for('home')) | |
return redirect(url_for('login')) | |
@app.route('/login', methods=['POST']) | |
def login(): | |
if request.method == 'POST': | |
session['userid'] = '1' | |
else: | |
raise | |
return redirect(url_for('home')) | |
@app.route('/home') | |
@app.route('/home/<user_id>') | |
def home(user_id=None): | |
if user_id is None: | |
user_id = session.get('user_id') | |
user = User.get(user_id) | |
return user.json_response() | |
if __name__ == '__main__': | |
app.run(debug=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment