示例#1
0
文件: people.py 项目: UPCnet/max
def addUser(users, request):
    """
        Add a user

        Creates a new user in the system, with all the attributes provided
        in the posted user object.

        - `username` - Used to identify and login the user. This is the only required parameter and cannot be modified.
        - `displayname` - The full name of the user.
        - `twitterUsername` - A valid Twitter® username (without @ prefix), used on the twitter integration service.


        This operation is idempotent, which means that a request to create a user that already exists,
        will not recreate or overwrite that user. Instead, the existing user object will be returned. You can
        tell when this happens by looking at the HTTP response status code. A new user insertion will return
        a **201 CREATED** code, and a **200 OK** for an existing user.

        + Request

            {
                "username": "******",
                "displayName": "user2",
                "twitterUsername": "******"
            }

    """
    payload = request.decoded_payload
    if not isinstance(payload, dict):
        raise ValidationError('Unexpected data type in request')

    username = payload.get('username', None)
    if username is None:
        raise ValidationError('Missing username in request')

    rest_params = {'username': username.lower()}

    # Initialize a User object from the request
    newuser = User.from_request(request, rest_params=rest_params)

    # If we have the _id setted, then the object already existed in the DB,
    # otherwise, proceed to insert it into the DB
    # In both cases, respond with the JSON of the object and the appropiate
    # HTTP Status Code

    if newuser.get('_id'):
        # Already Exists
        code = 200

        # Determine if we have to recreate exchanges for an existing user
        # Defaults NOT to recreate them if not specified
        create_exchanges = asbool(request.params.get('notifications', False))
        if create_exchanges:
            notifier = RabbitNotifications(request)
            notifier.add_user(username)
    else:
        # New User
        code = 201

        # Determine if we have to recreate exchanges for a new user
        # Defaults to Create them if not specified
        create_exchanges = asbool(request.params.get('notifications', True))
        userid = newuser.insert(notifications=create_exchanges)

        newuser['_id'] = userid
    handler = JSONResourceEntity(request, newuser.getInfo(), status_code=code)
    return handler.buildResponse()