Browse Source

starting with tests, but we cant start the database this way because "outside of application context"

master
Julio Biason 11 years ago
parent
commit
473d546c55
  1. 16
      luncho/blueprints/users.py
  2. 5
      luncho/database.py
  3. 35
      luncho/helpers.py
  4. 2
      luncho/server.py
  5. 32
      tests/users_tests.py

16
luncho/blueprints/users.py

@ -8,11 +8,25 @@ from flask import request
# from flask import jsonify # from flask import jsonify
# from flask import current_app # from flask import current_app
from pony.orm import commit
from luncho.helpers import ForceJSON
from luncho.database import User
users = Blueprint('users', __name__) users = Blueprint('users', __name__)
@users.route('', methods=['PUT']) @users.route('', methods=['PUT'])
@ForceJSON(required=['username', 'full_name', 'password'])
def create_user(): def create_user():
"""Create a new user. Request must be: """Create a new user. Request must be:
{ "username": "username", "full_name": "Full Name", "password": "hash" }""" { "username": "username", "full_name": "Full Name", "password": "hash" }"""
json = request.get_json(force=True)
new_user = User(username=json['username'],
fullname=json['full_name'],
passhash=json['password'],
validated=False)
commit()
return jsonify(status='OK')

5
luncho/database.py

@ -3,18 +3,21 @@
import datetime import datetime
from flask import current_app
from pony.orm import Database from pony.orm import Database
from pony.orm import PrimaryKey from pony.orm import PrimaryKey
from pony.orm import Optional from pony.orm import Optional
from pony.orm import Required from pony.orm import Required
# from pony.orm import Set # from pony.orm import Set
db = Database("sqlite", "tagallery.db", create_db=True) db = Database("sqlite", current_app.config['SQLITE_FILENAME'], create_db=True)
class User(db.Entity): class User(db.Entity):
"""Users.""" """Users."""
username = PrimaryKey(unicode) username = PrimaryKey(unicode)
fullname = Required(unicode)
passhash = Required(unicode) passhash = Required(unicode)
token = Optional(unicode) # 1. if the user never logged in, they will token = Optional(unicode) # 1. if the user never logged in, they will
# not have a token. # not have a token.

35
luncho/helpers.py

@ -0,0 +1,35 @@
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""Helper functions."""
from functools import wraps
from flask import request
from flask import jsonify
class ForceJSON(object):
def __init__(self, required=None):
self.required = required or []
def __call__(self, func):
@wraps(func)
def check_json(*args, **kwargs):
json = request.get_json(force=True, silent=True)
if not json:
return jsonify(status='ERROR',
error='Request MUST be in JSON format'), 400
# now we have the JSON, let's check if all the fields are here.
missing = []
for field in required or []:
if not field in json:
missing.append(field)
if missing:
return jsonify(status='ERROR',
error='Missing fields: {fields}'.format(
fields=', '.join(missing)))
return func(*args, **kwargs)
return check_json

2
luncho/server.py

@ -21,8 +21,10 @@ app.config.from_envvar('LUCNHO_CONFIG', True)
# Blueprints # Blueprints
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
from blueprints.index import index from blueprints.index import index
from blueprints.users import users
app.register_blueprint(index, url_prefix='/') app.register_blueprint(index, url_prefix='/')
app.register_blueprint(users, url_prefix='/user/')
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
# Database # Database

32
tests/users_tests.py

@ -0,0 +1,32 @@
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import os
import tempfile
import unittest
import json
from luncho import server
class TestUsers(unittest.TestCase):
"""Test users request."""
def setUp(self):
(_, server.app.config['SQLITE_FILENAME']) = tempfile.mkstemp()
self.app = server.app.test_client()
def tearDown(self):
os.unlick(server.app.config['SQLITE_FILENAME'])
def test_create_user(self):
request = {'username': 'username',
'full_name': 'full name',
'password': 'hash'}
rv = self.app.put('/users/',
data=json.dumps(request),
content_type='application/json')
print rv.data
if __name__ == '__main__':
unittest.main()
Loading…
Cancel
Save