Esempio n. 1
0
 def _get_all(self):
     users = db.session.query(User).all()
     schema = UserSchema(many=True)
     dumped_users = schema.dumps(users).data
     return Response(response=dumped_users,
                     mimetype="application/json",
                     status=200)
Esempio n. 2
0
def post_users():
    """
    post user
    ---
    tags:
      - user
    produces:
      - application/json
    parameters:
      - in: body
        name: user
        schema:
          $ref: '#/definitions/UserSchema'
    responses:
      200:
        description: Successful operation
        schema:
          $ref: "#/definitions/UserSchema"
    """
    payload = request.json

    # 入力値の検証を行います。入力値がSchemaと一致しない場合はValidationErrorがraiseされます。
    schema = UserSchema()
    schema.load(payload)

    # バリデーションが完了したら何らかのロジックを実行するでしょう。
    db.Users.save(schema.dump(payload))

    return jsonify(payload)
Esempio n. 3
0
 def post(self):
     try:
         UserSchema().load(request.json)
     except ValidationError as e:
         return {'error': str(e)}
     user = User(**request.json).save()
     return UserSchema().dump(user)
Esempio n. 4
0
 def _get_one(self, uid):
     users = User.all()
     schema = UserSchema()
     dumped_users = schema.dumps(users).data
     return Response(response=dumped_users,
                     mimetype="application/json",
                     status=200)
Esempio n. 5
0
def users():
    active_users = ActiveUser.query.all()
    users = []
    for u in active_users:
        user_ = UserSchema()
        user = user_.dump(u.user).data
        users.append(user)
    io.emit('list_users', users)
Esempio n. 6
0
def get_users():
    users = db.session.query(User).order_by(User.userId).all()
    user_schema = UserSchema(many=True)
    dump_data = user_schema.dump(users)
    for i in range(len(dump_data)):
        dump_data[i]['password'] = str(dump_data[i]['password'])

    return jsonify({'response': dump_data}), 200
Esempio n. 7
0
 def create_random_user():
     session = get_session()
     schema = UserSchema(session=session)
     ins, errors = schema.load(
         {"name": "test_user" + str(random.randint(1, 100))})
     session.add(ins)
     session.commit()
     return jsonify({"random_user": schema.dump(ins).data})
Esempio n. 8
0
async def get_user(request):
    user_schema = UserSchema()
    id_ = int(request.match_info.get('user_id'))
    user = await User.query.where(User.id == id_).gino.first()
    resp = {
        'user': user_schema.dump(user).data,
    }
    return web.json_response(resp)
Esempio n. 9
0
async def get_users(request):
    user = await User.query.gino.all()
    user_schema = UserSchema(many=True)

    resp = {
        'items': user_schema.dump(user).data,
        'total': len(user),
    }
    return web.json_response(resp)
Esempio n. 10
0
def get_user_by_id(id):
    if db.session.query(User.userId).filter_by(userId=id).scalar() is None:
        return jsonify({'response': "Invalid ID found"}), 406

    result = db.session.query(User).filter(User.userId == id).order_by(
        User.userId).all()
    schema = UserSchema(many=True)
    dump_data = schema.dump(result)
    dump_data[0]['password'] = str(dump_data[0]['password'])

    return jsonify({'response': dump_data}), 200
Esempio n. 11
0
    def post(self):
        data = request.get_json()
        schema = UserSchema()
        results = schema.load(request.get_json())

        if results.errors:
            return results.errors, 400

        db.session.add(results.data)
        db.session.commit()

        token = user.encode_auth_token()
        response = {"token": token.decode(), "user": schema.dumps(user)}

        return response, 201
Esempio n. 12
0
def update_delete_user(username):
    if request.method == 'PUT':
        user_data = request.args
        new_username = user_data.get('username')
        firstName = user_data.get('firstName')
        lastName = user_data.get('lastName')
        email = user_data.get('email')

        user = User.query.filter_by(username=username).first()
        if user is None:
            abort(404, description="Resource not found")

        try:
            UserSchema().load(user_data)
        except ValidationError:
            abort(400, description="Error validation")

        user.username = new_username
        user.firstName = firstName
        user.lastName = lastName
        user.email = email

        db.session.commit()
        return user_schema.jsonify(user)

    elif request.method == 'DELETE':
        user = User.query.filter_by(username=username).first()
        if user is None:
            abort(404, description="Resource not found")
        db.session.delete(user)
        db.session.commit()

        return user_schema.jsonify(user)
Esempio n. 13
0
def create_user():
    data = request.get_json()
    if not data:
        return jsonify({"response": "No input data provided"}), 400

    try:
        result = UserSchema().load(data)
    except Exception:
        return jsonify({'response': "Invalid input"}), 400

    if db.session.query(User.userId).filter_by(
            username=result["username"]).scalar() is not None:
        return jsonify({'response': "Username is already used"}), 409

    password = result["password"]
    salt = os.urandom(32)  # Новая соль для данного пользователя
    key = hashlib.pbkdf2_hmac('sha256', password.encode('utf-8'), salt, 10000)
    storage = salt + key

    user = User(username=result["username"],
                email=result["email"],
                password=storage)
    db.session.add(user)
    db.session.commit()

    userId = db.session.query(
        User.userId).filter_by(username=result["username"]).scalar()
    encoded_jwt = bu.encode_auth_token(userId, 0)
    return jsonify({
        'response':
        "Sign up successfully! Please LOG IN to get access token"
    }), 201
Esempio n. 14
0
 def get(self, id=None):
     if id:
         return UserSchema().dump(User.objects.get(id=id))
     else:
         users = User.objects()
         user_json = users.to_json()
         return json.loads(user_json)
Esempio n. 15
0
def test(obj):
    try:
        #the behavior to take on unknown fields (EXCLUDE, INCLUDE, RAISE)
        print(UserSchema(unknown='EXCLUDE').load(obj))

    except ValidationError as err:
        print(err.messages)
    print('==================')
Esempio n. 16
0
def get_users():
    """
    get users
    ---
    tags:
      - user
    produces:
      - application/json
    responses:
      200:
        description: Successful operation
        schema:
          type: array
          items:
            $ref: "#/definitions/UserSchema"
    """
    schema = UserSchema()
    return jsonify([schema.dump(u) for u in db.Users.all()])
Esempio n. 17
0
    def get(self, username):

        # find user by username
        user = User.query.filter_by(username=username).first()
        if user is None:
            return "User {} does not exist".format(username), 400

        # deserialize user object into JSON
        return UserSchema(strict=True).dump(user).data
Esempio n. 18
0
def create_user():
    if request.method == 'POST':
        user_data = request.get_json()
        email = user_data.get('email')
        password = user_data.get('password')
        name = user_data.get('name')
        hash_password = bcrypt.generate_password_hash(password)

        try:
            UserSchema().load(user_data)
        except ValidationError:
            abort(400, description="Error validation")

        new_user = Users(email, hash_password, name)

        db.session.add(new_user)
        db.session.commit()

        return jsonify(UserSchema().dump(new_user))
Esempio n. 19
0
 def post(self):
     data_load = request.get_json()
     try:
         data = UserSchema().load(data_load)
     except ValidationError as err:
         return err.messages, 404
     if UserModel.find_by_username(data["username"]) is None:
         user = UserModel(data["username"], data["password"])
         user.add_user()
         return {"response": "The user was successfuly created"}, 201
     else:
         return dict(error="User with this username already exist"), 500
Esempio n. 20
0
    def post(self):

        # validate initial post data
        try:
            data = UserSchema(strict=True).load(request.json).data
        except ValidationError:
            return "Incorrect parameters were passed", 400

        username = data['username']

        # try to create user
        try:
            user = User(**data)
            db.session.add(user)
            db.session.commit()

        # if user with username already exists, send 400 status error
        except IntegrityError:
            return "User {} already exists".format(username), 400

        # return success response and API endpoint to access user object
        return {'Location': '/api/v1/users/{}'.format(username)}, 201
Esempio n. 21
0
def update_user(uid):
    if request.method == 'PUT':
        user_data = request.args
        email = user_data.get('email')
        name = user_data.get('name')


        user = Users.query.filter_by(uid=uid).first()
        if user is None:
            abort(404, description="Resource not found")

        try:
            UserSchema().load(user_data)
        except ValidationError:
            abort(400, description="Error validation")

        user.name = name
        user.email = email


        db.session.commit()
        return user_schema.jsonify(user)
Esempio n. 22
0
from user import User
from schema import UserSchema

from marshmallow import pprint

user = User(name='M K', email='*****@*****.**')
schema = UserSchema()
result = schema.dump(user)
pprint(result.data)

json_result = schema.dumps(user)
pprint(json_result.data)

Esempio n. 23
0
from flask import jsonify, request, Response
from flask_restful import Resource, reqparse
from sqlalchemy.exc import IntegrityError

from models import Device, Measurement, User
from schema import UserSchema, DeviceSchema, MeasurementSchema

user_schema = UserSchema(strict=True)
users_schema = UserSchema(many=True, strict=True)
device_schema = DeviceSchema()
devices_schema = DeviceSchema(many=True,
                              only=('id', 'model', 'manufacturerID'))
measurement_schema = MeasurementSchema()
measurements_schema = MeasurementSchema(many=True,
                                        only=('id', 'meas_date', 'event_type',
                                              'manufacturerID', 'gluc_value',
                                              'insulin_value', 'carb'))


class UserListResource(Resource):
    def get(self):
        users = User.query.all()
        users_result = users_schema.dump(users)
        return jsonify({'users': users_result.data})


class UserResource(Resource):
    def not_found_response(self):
        not_found_response = jsonify({"message": "User could not be found."})
        not_found_response.status_code = 400
        return not_found_response
Esempio n. 24
0
import datetime
from schema import UserSchema

if __name__ == "__main__":

    data = dict(name='test',
                age=11,
                password='******',
                created=datetime.datetime.now())
    schema = UserSchema()
    json_obj = schema.dump(data)
    print(json_obj)

    obj2 = schema.load({'password': '******', **json_obj})
    print(obj2)
Esempio n. 25
0
def get_users():
    """route to get all."""
    users = User.query.all()
    users_schema = UserSchema()
    result = users_schema.dump(users, many=True)
    return jsonify({'users': result.data})
Esempio n. 26
0
from passlib.hash import pbkdf2_sha256 as sha256
from flask import request, current_app
from flask_restful import Resource
from marshmallow import ValidationError
from flask_jwt_extended import (create_access_token,
                                create_refresh_token,
                                jwt_required,
                                jwt_refresh_token_required,
                                get_jwt_identity)
from mail import send_confirm_mail, confirm_token
from model import db, User
from schema import UserSchema, UserRegistrationSchema
from decorators import is_enabled


user_schema = UserSchema()
user_reg_schema = UserRegistrationSchema()


class Registration(Resource):
    def post(self):
        json_data = request.get_json(force=True)
        if not json_data:
            return {'message': 'No input data provided'}, 400
        try:
            json_user = json_data["user"]
            url = json_data["url"]
        except Exception:
            return {'message': 'Url or user does not found in input data'}, 400
        # Validate and deserialize input
        try:
Esempio n. 27
0
     'age': 21,
     'level': 4
 })
 test({
     'id': 1,
     'name': 'longgggggggg',
     'lastname': 'nammmmmmeee_trigger_schema_level_validation',
     'password': '******',
     'age': 17,
     'level': 1
 })
 """
     valid
 """
 test({
     'id': 1,
     'name': 'a',
     'lastname': 'b',
     'password': '******',
     'age': 17,
     'level': 1
 })
 validate_result = UserSchema().validate({
     'id': 'abc',
     'name': '',
     'lastname': '',
     'password': '******',
     'age': 10,
     'level': 4
 })
 print(validate_result)
Esempio n. 28
0
from flask import request, jsonify
from flask_restful import Resource

from init import app, db, api
from datamodel import User, UserProfile, Organisation
from schema import UserSchema, UserProfileSchema, OrganisationSchema

# Init schema
organisation_schema = OrganisationSchema()

userprofile_schema = UserProfileSchema()

user_schema = UserSchema()
users_schema = UserSchema(many=True)


# Create a User
class UserResource(Resource):
    def post(self):
        name = request.json['name']
        age = request.json['age']
        profile = request.json['profile']
        organisation = request.json['organisation']
        new_user = User(name, age)
        new_user.profile = UserProfile(new_user.id, profile['address'])

        for i in organisation:
            new_organisation = Organisation(new_user.id, i['name'])
            new_user.organisation.append(new_organisation)
            db.session.add(new_organisation)
Esempio n. 29
0
 def create(data):
     user_schema = UserSchema(**data).save()
     return user_schema
Esempio n. 30
0
 def get_by_id(user_id):
     qs = UserSchema.objects(pk=user_id)
     if qs.count == 0:
         return None
     return qs.first()