Skip to content
Snippets Groups Projects
Verified Commit a187ac33 authored by Sachin Kamath's avatar Sachin Kamath
Browse files

Enhance user model and add user creation endpoint

parent 8fb41f02
No related branches found
No related tags found
No related merge requests found
# -*- coding: utf-8 -*-
# app/__init__.py
import time
from termcolor import colored
import sys
from flask_api import FlaskAPI
from flask_sqlalchemy import SQLAlchemy
# local import
from instance.config import app_config
# initialize sql-alchemy
......@@ -21,15 +18,19 @@ application.config.from_object(app_config[config_name])
application.config.from_pyfile('config.py')
application.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db.init_app(application)
application.config['SECRET_KEY'] = 'blehblehbleh'
# Delay the application launch to get the user attention if running in testing mode
'''
if config_name != 'production':
for x in range(0, 5):
sys.stdout.write(colored("\rYou are not running the server in production mode. " +
"App will run in {} seconds..".format(5-x), 'red'))
sys.stdout.flush()
time.sleep(1)
'''
print(colored("\n\nRunning app in {} mode..".format(config_name), 'yellow'))
# This disables the HTML API renderer for flask_api when called through browsers.
......
# -*- coding: utf-8 -*-
from hodor import app
from flask import jsonify
from flask import request, jsonify, abort, make_response
from hodor.models.user import User
from sqlalchemy.exc import IntegrityError
@app.route('/')
def start():
return jsonify({'hello': 'world'})
# Get all Users
@app.route('/users', methods=['GET', 'POST'])
def get_all_users():
response = {}
response['status'] = 200
response ['data'] = []
"""
This function iterates the database to find all users and returns it as JSON.
:return: Response Code
"""
for ele in User.get_all():
user = ele.__dict__
print user
return 'Work in Progress'
@app.route('/users/new', methods=['GET', 'POST'])
def add_new_user():
"""
This function adds a new user
:return: Response Code
"""
newuser = {}
if request.method == "POST":
try:
newuser['username'] = str(request.data.get('username').strip())
newuser['first_name'] = str(request.data.get('first_name').strip())
newuser['last_name'] = str(request.data.get('last_name').strip())
newuser['email'] = str(request.data.get('email').strip())
newuser['password'] = str(request.data.get('password').strip())
newuser['verification_code'] = str(request.data.get('verification_code').strip()) or newuser['verification_code']
except Exception as e:
print(e)
abort(500)
print newuser
user = User(**newuser)
user.save()
return make_response(jsonify(status=201, msg="User {} successfully added to database".format(user.username)), 201)
@app.errorhandler(IntegrityError)
def handle_sqlalchemy_assertion_error(err):
try:
'''
err.orig.args is from the DBAPIError class of SQLAlchemy. It usually contains the original error message.
The below is an attempt to clean up the message and only return the relevant part to API
'''
errmsg = err.orig.args[0].split('\n')[1][9:]
except IndexError:
errmsg = err.orig.args[0].split('\n')
except IndexError:
errmsg = err.orig.args[0]
return make_response(jsonify(status=400, msg=errmsg), 400)
@app.route('/print', methods=['GET', 'POST'])
......
# -*- coding: utf-8 -*-
from hodor import db
from sqlalchemy import inspect
from sqlalchemy_utils import PasswordType
class User(db.Model):
__tablename__ = 'users'
# Values entered by the user
username = db.Column(db.String(32), primary_key=True)
username = db.Column(db.String(32), primary_key=True, nullable=False)
first_name = db.Column(db.String(32), nullable=False)
last_name = db.Column(db.String(32), nullable=False)
email = db.Column(db.String(64), unique=True, nullable=False)
password = db.Column(db.String(64), nullable=False)
'''PasswordType is an awesome function. To check for passwords later,
you can just do user['password'] == 'plaintext' for a boolean response.'''
password = db.Column(PasswordType(
schemes=[
'pbkdf2_sha512',
'md5_crypt'
],
deprecated=['md5_crypt']
), nullable=False)
# Platform values
disabled = db.Column(db.Boolean, default=False)
......@@ -20,11 +30,9 @@ class User(db.Model):
def __unicode__(self):
return unicode(self.username)
def __init__(self, name):
"""initialize with name."""
self.name = name
def save(self):
print type(self)
print self.email
db.session.add(self)
db.session.commit()
......@@ -32,6 +40,10 @@ class User(db.Model):
def get_all():
return User.query.all()
def get_all_dict(self):
return {c.key: getattr(self, c.key)
for c in inspect(self).mapper.column_attrs}
def delete(self):
db.session.delete(self)
db.session.commit()
......
# -*- coding: utf-8 -*-
......@@ -13,10 +13,10 @@ class Config(object):
class DevelopmentConfig(Config):
"""Configurations for Development."""
DEBUG = False
SQLALCHEMY_DATABASE_URI = 'postgresql://localhost/test_db'
DEBUG = True
SQLALCHEMY_DATABASE_URI = 'postgresql://localhost/hodor_test'
SECRET = "ChangeThisStringIfYouWant"
TESTING = False
TESTING = True
class TestingConfig(Config):
......
from flask_script import Manager # class for handling a set of commands
from flask_migrate import Migrate, MigrateCommand
from hodor import db, create_app
from hodor import db, app
app = create_app(config_name='development')
migrate = Migrate(app, db)
manager = Manager(app)
......
......@@ -5,3 +5,4 @@ Flask-DebugToolbar
flask_api
termcolor
flask_sqlalchemy
sqlalchemy_utils
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment