예제 #1
0
def add_user():
    # parse the json
    json = request.get_json()

    # extract data
    username = json.get('username')
    email = json.get('email')
    password = json.get('password')

    # sanity checks
    if not username:
        return jsonify(
            response="Could not create User, username is required"), 400

    if not email:
        return jsonify(
            response="Could not create User, email is required"), 400

    if not password:
        return jsonify(
            response="Could not create User, password is required"), 400

    # create user and commit
    new_user = User(username=username, email=email, password=password)
    session.add(new_user)
    session.commit()

    # make sure db xact occured
    if not new_user.id:
        return jsonify(response="Could not create User"), 404

    # Return user_id on success
    return jsonify(user_id=new_user.id), 201
예제 #2
0
def add_constellation():
    # grab authenticated user
    user = g.user

    # parse the json
    json = request.get_json()

    # extract data
    name = json.get('name')
    vectors = json.get('vectors')

    # sanity checks
    if not name:
        return jsonify(response="Could not create Constellation, name is required"), 400

    if not vectors:
        return jsonify(response="Could not create Constellations, one or more vectors are required"), 400

    # create new constellation for authenticated user
    new_constellation = Constellation(user_id=user.id, name=name)
    session.add(new_constellation)
    session.commit()

    # create vectors for constellation
    for vector in vectors:
        new_vector = Vector(constellation_id=new_constellation.id, a=vector[0], b=vector[1])
        session.add(new_vector)
        session.commit()

    # return constellation id
    return jsonify(constellation_id=new_constellation.id), 201
예제 #3
0
def create_records(model, docs) -> (dict, int):
    if not docs:
        return {"message": "Request body cannot be empty"}, 400
    model_name = model.__name__
    schema = get_schema(model, operation='create')
    for doc in docs:
        is_valid, errors = validate_request(doc, schema)
        if not is_valid:
            return errors, 400
        new_records = []
        for doc in docs:
            record = model(**doc)
            new_records.append(record)
        print(f'Created {model}:', new_records)
        for record in new_records:
            session.add(record)
        try:
            session.commit()
            return {
                "Success": f"Added {len(new_records)} {model_name} ",
                "ids": [rec.id for rec in new_records]
            }, 200
        except Exception as e:
            session.rollback()
            if e is Exception:
                exmsg = e.message
            else:
                exmsg = str(e.__cause__)
            print(f"{model_name} update failed with below exception")
            pprint(e.__repr__())
            return {e.__class__.__name__: exmsg}, 400
예제 #4
0
def add_user():
    # parse the json
    json = request.get_json()

    # extract data
    username = json.get('username')
    email = json.get('email')
    password = json.get('password')

    # sanity checks
    if not username:
        return jsonify(response="Could not create User, username is required"), 400

    if not email:
        return jsonify(response="Could not create User, email is required"), 400

    if not password:
        return jsonify(response="Could not create User, password is required"), 400

    # create user and commit 
    new_user = User(username=username, email=email, password=password)
    session.add(new_user)
    session.commit()
    
    # make sure db xact occured
    if not new_user.id:
        return jsonify(response="Could not create User"), 404
    
    # Return user_id on success
    return jsonify(user_id=new_user.id), 201
예제 #5
0
 def save(self):
     session.add(self)
     try:
         session.commit()
     except:
         session.rollback()
         raise
     return self
예제 #6
0
def load_menu_in_db(catalog):
    for item in catalog:
        pizza = Pizza()
        pizza.title = item.get('title')
        pizza.description = item.get('description')
        session.add(pizza)
        for choice in item.get('choices', []):
            p_choice = PizzaChoices()
            p_choice.pizza = pizza
            p_choice.title = choice.get('title')
            p_choice.price = choice.get('price')
            session.add(p_choice)
    session.commit()
예제 #7
0
    def add_new_message(self, message) -> 'User':
        """
        Создает сообщение и добавляет привязку к текущему пользователю

        :param message:
        :return:
        """

        message = Message(message)
        session.add(message)
        session.flush()
        self.messages.append(message)
        session.commit()

        return self
예제 #8
0
def save_server(ip, port, password, user_name, name):
    # 以ip和用户名为唯一标识
    server_data = session.query(Server).filter_by(ip=ip,
                                                  user_name=user_name).first()
    new_server = False
    if server_data is None:
        server_data = Server()
        new_server = True
    server_data.ip = ip
    server_data.port = port
    server_data.name = name
    server_data.user_name = user_name
    server_data.password = password
    if new_server:
        session.add(server_data)
    session.commit()
    return "ok"
예제 #9
0
    def post(self):
        """ Logins user according to JSON object data.

            Headers:
                Content-Type: application/json

            JSON Request format:
            {
                "email": email,
                "senha": senha
            }
        """

        data = sign_in_parser.parse_args()

        # Email exists/Verify password hash
        if not email_exists(data['email']) or \
        not User.verify_hash(data['senha'], get_user_hash(data['email'])):
            return {'mensagem': 'Usuário e/ou senha inválidos.'}, 401

        # Generate token
        user = get_user_by_email(data['email'])
        token = Log.generate_token(
            {
                'sub': user.uuid,
                'name': user.name,
                'exp':
                datetime.datetime.utcnow() + datetime.timedelta(minutes=30)
            }, app.config['SECRET_KEY'])

        log = Log(user, token)

        # Registering login
        session.add(log)
        session.commit()

        # User logged in successfully
        return {
            'id': user.uuid,
            'email': user.email,
            'data_criacao': user.creation_date.isoformat(),
            'data_atualizacao': user.update_date.isoformat(),
            'ultimo_login': user_last_login(user.email).date.isoformat(),
            'token': token.decode('UTF-8')
        }, 201
예제 #10
0
    def create_user(cls, login: str, password: str, token: str = None) -> 'User':
        """
        Создает пользователя

        :param token:
        :param login:
        :param password:
        :return:
        """

        if token and password and login:
            user = cls(login=login, password=password, token=token)
        elif login and password:
            user = cls(login=login, password=password)
        else:
            user = cls()

        session.add(user)
        session.commit()
        return user
예제 #11
0
def signup():
    form = RegisterForm(request.form)

    if request.method == "POST" and form.validate():
        print("signed up")
        hashed_password = generate_password_hash(form.password.data,
                                                 method='sha256')

        new_user = User()
        new_user.username = form.username.data
        new_user.email = form.email.data
        new_user.password = hashed_password

        session.add(new_user)
        session.commit()
        return render_template('login.html', form=form)
    else:
        print("error")

    return render_template('signup.html', form=form)
예제 #12
0
def create_records(model_class, form):
    new_record = model_class()
    form.populate_obj(new_record)
    if model_class is User:
        new_record: User = new_record
        new_record.set_password(new_record.username)
        new_record.date_created = datetime.utcnow()
    try:
        session.add(new_record)
        session.commit()
        msg = (css["yes"], f"{new_record} create succeeded")
        print(msg)
        return True, msg
    except Exception as e:
        session.rollback()
        if e is Exception:
            exmsg = e.message
        else:
            exmsg = str(e.__cause__)
        print(f"{model_class} create failed with below exception")
        pprint(e.__repr__())
        return False, (css["no"], exmsg)
예제 #13
0
def update_constellation(constellation_id):
    # grab authenticated user
    user = g.user

    # get the constellation
    constellation = session.query(Constellation)\
        .filter((Constellation.id==constellation_id) & (Constellation.user_id==user.id))\
        .first()

    if not constellation:
        return jsonify(
            response="Constellation not found for authenticated user."), 404

    # parse the json
    json = request.get_json()

    # extract constellation data
    name = json.get('name')
    vectors = json.get('vectors')

    # update the constellation information
    if name:
        constellation.name = name
        session.commit()

    # if we got new vectors
    if vectors:
        # delete all vectors associated with the constellation
        session.query(Vector)

        # associate new vectors with constellation
        for vector in vectors:
            new_vector = Vector(constellation_id=constellation.id,
                                a=vector[0],
                                b=vector[1])
            session.add(new_vector)
            session.commit()

    return jsonify(response="Constellation Added"), 200
예제 #14
0
def add_constellation():
    # grab authenticated user
    user = g.user

    # parse the json
    json = request.get_json()

    # extract data
    name = json.get('name')
    vectors = json.get('vectors')

    # sanity checks
    if not name:
        return jsonify(
            response="Could not create Constellation, name is required"), 400

    if not vectors:
        return jsonify(
            response=
            "Could not create Constellations, one or more vectors are required"
        ), 400

    # create new constellation for authenticated user
    new_constellation = Constellation(user_id=user.id, name=name)
    session.add(new_constellation)
    session.commit()

    # create vectors for constellation
    for vector in vectors:
        new_vector = Vector(constellation_id=new_constellation.id,
                            a=vector[0],
                            b=vector[1])
        session.add(new_vector)
        session.commit()

    # return constellation id
    return jsonify(constellation_id=new_constellation.id), 201
예제 #15
0
def update_constellation(constellation_id):
    # grab authenticated user
    user = g.user

    # get the constellation
    constellation = session.query(Constellation)\
        .filter((Constellation.id==constellation_id) & (Constellation.user_id==user.id))\
        .first()

    if not constellation:
        return jsonify(response="Constellation not found for authenticated user."), 404

    # parse the json
    json = request.get_json()

    # extract constellation data
    name = json.get('name')
    vectors = json.get('vectors')

    # update the constellation information
    if name:
        constellation.name = name
        session.commit()

    # if we got new vectors
    if vectors:
        # delete all vectors associated with the constellation
        session.query(Vector)

        # associate new vectors with constellation
        for vector in vectors:
            new_vector = Vector(constellation_id=constellation.id, a=vector[0], b=vector[1])
            session.add(new_vector)
            session.commit()

    return jsonify(response="Constellation Added"), 200
예제 #16
0
def seed_db():
    # add default user
    default_user = User(username="******",
                        email="*****@*****.**",
                        password="******")
    session.add(default_user)
    session.commit()

    # add all stars
    with open(settings.STAR_FILE, 'rb') as f:
        reader = csv.reader(f)
        reader.next()
        for row in reader:
            id = int(row[settings.ID_INDEX])
            ra = float(row[settings.RA_INDEX])
            dec = float(row[settings.DEC_INDEX])
            mag = float(row[settings.MAG_INDEX])

            star = Star(id=id, ra=ra, dec=dec, mag=mag)
            session.add(star)

    session.commit()

    # add all constellations
    with open(settings.CONST_FILE, 'rb') as f:
        reader = csv.reader(f)
        for row in reader:
            name = row[settings.NAME_INDEX]
            a, b = int(row[settings.A_INDEX]), int(row[settings.B_INDEX])

            constellation = session.query(Constellation).filter_by(
                name=name).first()
            if not constellation:
                constellation = Constellation(user_id=default_user.id,
                                              name=name)
                session.add(constellation)
                session.commit()

            vector = Vector(constellation_id=constellation.id, a=a, b=b)
            session.add(vector)
            session.commit()
예제 #17
0
def seed_db():
    # add default user
    default_user = User(username="******", email="*****@*****.**", password="******")
    session.add(default_user)
    session.commit()

    # add all stars
    with open(settings.STAR_FILE, 'rb') as f:
        reader = csv.reader(f)
        reader.next()
        for row in reader:
            id = int(row[settings.ID_INDEX])
            ra = float(row[settings.RA_INDEX])
            dec = float(row[settings.DEC_INDEX])
            mag = float(row[settings.MAG_INDEX])

            star = Star(id=id, ra=ra, dec=dec, mag=mag)
            session.add(star)

    session.commit()

    # add all constellations
    with open(settings.CONST_FILE, 'rb') as f:
        reader = csv.reader(f)
        for row in reader:
            name = row[settings.NAME_INDEX]
            a, b = int(row[settings.A_INDEX]), int(row[settings.B_INDEX])

            constellation = session.query(Constellation).filter_by(name=name).first()
            if not constellation:
                constellation = Constellation(user_id=default_user.id, name=name)
                session.add(constellation)
                session.commit()

            vector = Vector(constellation_id=constellation.id, a=a, b=b)
            session.add(vector)
            session.commit()
예제 #18
0
    def post(self):
        """ Registers user on database with JSON object data.

            Headers:
                Content-Type: application/json

            JSON Request format:
            {
                "nome": nome,
                "email": email,
                "senha": senha,
                "telefones": [
                    {
                        "numero": numero,
                        "ddd": ddd
                    },
                    ...
                ]
            }
        """

        data = sign_up_parser.parse_args()

        # Validate email
        if re.match("^[\w.]+@[\w]+\.[\w]+$", data.email) is None:
            return {
                'mensagem': '{} não é um email válido.'.format(data.email)
            }, 400

        # Email already registered
        if email_exists(data.email):
            return {
                'mensagem': '{} já foi registrado.'.format(data.email)
            }, 400

        # Validate phone numbers
        for phone in data['telefones']:
            if num.match(phone['numero']) is None or num.match(
                    phone['ddd']) is None:
                return {
                    'mensagem':
                    '{} {} não é um numero de telefone válido.'.format(
                        phone['ddd'], phone['numero'])
                }, 400

        # Create user ORM
        user = User(data['nome'], data['email'],
                    User.generate_hash(data['senha']))
        user.phones = [
            Phone(phone['numero'], phone['ddd']) for phone in data['telefones']
        ]

        # Generate token
        token = Log.generate_token(
            {
                'sub': user.uuid,
                'name': user.name,
                'exp':
                datetime.datetime.utcnow() + datetime.timedelta(minutes=30)
            }, app.config['SECRET_KEY'])

        # Add to database
        session.add(user)
        session.add(Log(user, token))
        session.commit()

        # User registered successfully
        return {
            'id': user.uuid,
            'email': user.email,
            'data_criacao': user.creation_date.isoformat(),
            'data_atualizacao': user.update_date.isoformat(),
            'ultimo_login': user_last_login(user.email).date.isoformat(),
            'token': token.decode('UTF-8')
        }, 201