コード例 #1
0
ファイル: inv.py プロジェクト: yvid/AngelBoardProtoType
def inv_register():
    iSerial = iSerial_GEN()
    inv = request.get_json(force=True)
    invASerial = inv['invAserial']
    invHSerial = inv['invHserial']

    row = Inv.query.filter(Inv.invASerial == func.binary(invASerial)).\
                    filter(Inv.invHSerial == func.binary(invHSerial)).first()

    if row:
        return ('Registration aleady exist', 200)

    if iSerial:
        new_inv = Inv(
            iSerial=iSerial,
            invASerial=invASerial,
            invHSerial=invHSerial,
            invType=inv['invType'],
            reqDate=dt.now(),
            invStep='a00',
            chngDate=dt.now(),
        )

        db.session.add(new_inv)

        db.session.commit()  # Commits all changes
        db.session.close()

    return ('Registration completed', 200) if new_inv else ('', 400)
コード例 #2
0
ファイル: routes.py プロジェクト: yvid/AngelBoardProtoType
def update_user():
    """Update a user."""
    account = request.get_json(force=True)
    name = account['name']
    emailId = account['emailId']

    row = Account.query.filter(Account.emailId == func.binary(emailId)).first()
    if name and emailId:
        row.emailId = emailId,
        row.emailPsw = account['emailPsw'],
        row.name = name,
        row.nickName = account['nickName'],
        row.belong = account['belong'],
        row.rank = account['rank'],
        row.status = account['status'],
        row.modyDate = dt.now(),
        row.latelyDate = dt.now(),
        row.modyIP = account['modyIP']
        db.session.commit()  # Commits all changes

    row = AccountInfo.query.filter(
        AccountInfo.emailIdF == func.binary(emailId)).first()
    if name and emailId:
        row.emailIdF = emailId
        row.accountType = account['accountType']
        row.accountCo = account['accountCo']
        row.accountFCo = account['accountFCo']
        row.accountFTech = account['accountFTech']
        row.newsRx = account['newsRx']

        db.session.commit()  # Commits all changes
        db.session.close()

    return make_response(f"{emailId} successfully modified!")
コード例 #3
0
ファイル: routes.py プロジェクト: yvid/AngelBoardProtoType
def login_user():
    account = request.get_json(force=True)
    emailId = account['emailId']
    emailPsw = account['emailPsw']

    row = db.session.query(Account, Payment).join(Payment).\
    filter(Account.emailId == func.binary(emailId)).order_by(Payment.expDate.desc()).limit(1)

    df = pd.read_sql(row.statement, row.session.bind)
    res = json.loads(df.to_json(orient='records'))

    response = {'res': 'e0'}

    if not res:
        row = db.session.query(Account).filter(
            Account.emailId == func.binary(emailId))
        df = pd.read_sql(row.statement, row.session.bind)
        res = json.loads(df.to_json(orient='records'))

    if res:
        login_handler(emailPsw, response, res[0])

    db.session.close()

    return jsonify(response)
コード例 #4
0
def register():
    userName = request.json['userName']
    password = request.json['password']
    nombre = request.json['nombre']
    imag = request.json['imag']

    encryptPassword = hashlib.md5(password.encode()).hexdigest()
    new_usuario = Usuario(userName, nombre, encryptPassword)
    #print(new_usuario.password,' ',password,' ',imag)
    # guardar usuario
    db.session.add(new_usuario)

    #buscar username
    userFind = Usuario.query.filter(
        Usuario.userName == func.binary(userName)).first()
    numRandom = (random.randint(300, 500) + random.randint(0, 100)) * 37
    idUsuario = userFind.idUsuario

    #guardar album
    new_album = Album('perfil', idUsuario)
    db.session.add(new_album)
    #buscar album
    userFindAlbum = Album.query.filter(
        Album.idUsuario == func.binary(idUsuario),
        Album.nombre.like('perfil')).first()
    idAlbum = userFindAlbum.idAlbum
    print('*************qq', idAlbum)

    image_base64 = imag
    bucket_name = 'practica1-g19-imagenes'

    file_name = 'Fotos_Perfil/img' + str(numRandom) + '_perfil.jpg'

    try:
        obj = s3.Object(bucket_name, file_name)
        obj.put(Body=base64.b64decode(image_base64))
        #response = s3_client.upload_file(base64.b64decode(base64_message), bucket_name, file_name)
        response = jsonify({"message": "Registro guardado"})
    except Exception as e:
        response = make_response(
            jsonify({"message": str(e)}),
            400,
        )
        response.headers["Content-Type"] = "application/json"

    #guardar foto
    nombreFoto = 'foto' + str(numRandom) + '_perfil'
    new_foto = Foto(nombreFoto, file_name, True, idAlbum)
    db.session.add(new_foto)

    db.session.commit()
    response = jsonify({"message": "Registro guardado"})
    return response
コード例 #5
0
    def find_all_by_student_uuid_and_status_and_term(
            self, student_uuid: str, status: str, start_time: int, end_time: int):
        generated_start_time = datetime.datetime.fromtimestamp(start_time + 32400)
        generated_end_time = datetime.datetime.fromtimestamp(end_time + 32400)

        model = (self.sql._db_session.query(Outing)
                 .filter(Outing.status == func.binary(status))
                 .filter(Outing.student_uuid == func.binary(student_uuid))
                 .filter(and_(Outing.start_time >= generated_start_time,
                              Outing.start_time <= generated_end_time)).all())
        self.sql._db_session.commit()
        self.sql._db_session.close()
        return model
コード例 #6
0
ファイル: model.py プロジェクト: nengnengwu/APIKG-Summary
 def get_remote_object(self, session):
     if self.id:
         return self
     else:
         try:
             return session.query(CodeElement).filter(
                 CodeElement.qualified_name == func.binary(
                     self.qualified_name),
                 CodeElement.element_type == func.binary(self.element_type),
                 CodeElement.type_return == self.type_return,
                 CodeElement.description == self.description,
             ).first()
         except Exception:
             traceback.print_exc()
             return None
コード例 #7
0
ファイル: apis.py プロジェクト: KK-12345/target
 def post(self):
     data = request.get_json()
     response = dict()
     response['status'] = 'failure'
     response['data'] = 'Some error occurred. Please try again.'
     session = DBBackend().get_session()
     try:
         user = session.query(User).filter_by(
             email=func.binary(data['email'])).one()
         response['status'] = 'success'
         response['data'] = dict()
         response['data']['user_id'] = user.id
         response['data']['email'] = user.email
         response['data']['auth_token'] = user.encode_token()
         session.add(user)
         session.commit()
         response_code = 200
     except NoResultFound:
         response['data'] = 'User not found.'
         response_code = 401
     except Exception as ex:
         response['data'] = "Error occured : " + str(ex.message)
         response_code = 500
         response['status'] = 'failure'
     session.close()
     return make_response(jsonify(response)), response_code
コード例 #8
0
def update_question_for_type(question_id):
	"""
	"	admin change question name for type
	"""
	try:
		review_type = request.args.get('type', '')
		if len(review_type) == 0:
			return response_error(MESSAGE.TYPE_INVALID, CODE.TYPE_INVALID)
		
		t = db.session.query(ReviewType).filter(ReviewType.name==func.binary(review_type)).first()
		if t is None:
			return response_error(MESSAGE.TYPE_INVALID, CODE.TYPE_INVALID)

		question = db.session.query(Question).filter(Question.id==question_id, Question.type_id==t.id).first()
		if question is None:
			return response_error(MESSAGE.QUESTION_NOT_EXIST, CODE.QUESTION_NOT_EXIST)

		if request.method == 'PUT':
			data = request.json
			if data is None:
				return response_error(MESSAGE.INVALID_DATA, CODE.INVALID_DATA)

			name = data.get('name', '')
			question.name = name

		else:
			db.session.delete(question)

		db.session.commit()
		return response_ok()
	except Exception, ex:
		db.session.rollback()
		return response_error(ex.message)
コード例 #9
0
def add_quesion_for_type():
	"""
	"	admin will add questions for object type which need to be reviewed
	"""
	try:
		data = request.json
		if data is None:
			return response_error(MESSAGE.INVALID_DATA, CODE.INVALID_DATA)

		review_type = request.args.get('type', '')
		if len(review_type) == 0:
			return response_error(MESSAGE.TYPE_INVALID, CODE.TYPE_INVALID)

		t = db.session.query(ReviewType).filter(ReviewType.name==func.binary(review_type)).first()
		if t is None:
			return response_error(MESSAGE.TYPE_INVALID, CODE.TYPE_INVALID)

		for d in data:
			if 'name' in d:
				question = Question(
					name=d['name'],
					type_id=t.id
				)
				db.session.add(question)
				db.session.flush()

		db.session.commit()
		return response_ok()
	except Exception, ex:
		db.session.rollback()
		return response_error(ex.message)
コード例 #10
0
def login():
    userName = request.json['userName']
    password = request.json['password']
    result = Usuario.query.filter(
        Usuario.userName == func.binary(userName)).first()
    print('*********sdfdsfsd  ', userName)
    #result = Usuario.query.filter(Usuario.userName.like(userName)).first()
    #response = usuario_schema.jsonify(result)
    #print('************************************************', type(result),result.nombre)
    #result = Usuario.query.filter(Usuario.userName == func.binary(userName)).first()
    if not result:
        response = make_response(
            jsonify({"message": "no existe usuario"}),
            401,
        )
        response.headers["Content-Type"] = "application/json"
    else:
        encryptPassword = hashlib.md5(password.encode()).hexdigest()
        if (encryptPassword == result.password):
            result = {
                "idUsuario": result.idUsuario,
                "userName": result.userName,
                "nombre": result.nombre
            }
            response = usuario_schema.jsonify(result)
        else:
            response = make_response(
                jsonify({"message": "password incorrecta"}),
                402,
            )
            response.headers["Content-Type"] = "application/json"

    return response
コード例 #11
0
 def find_all_by_student_uuid(self, student_id):
     model = self.sql._db_session.query(Outing) \
         .filter(Outing.student_uuid == func.binary(student_id)) \
         .order_by(Outing.end_time.desc()).all()
     self.sql._db_session.commit()
     self.sql._db_session.close()
     return model
コード例 #12
0
 def find_all_by_student_uuid_and_status(self, student_uuid, status) -> List["Outing"]:
     query = self.sql._db_session.query(Outing).filter(Outing.student_uuid == func.binary(student_uuid))
     if status: query = query.filter(Outing.status == status)
     model = query.all()
     self.sql._db_session.commit()
     self.sql._db_session.close()
     return model
コード例 #13
0
 def get_document_by_wikipedia_title(session, title):
     try:
         return session.query(WikipediaDocument).filter_by(
             title=func.binary(title)).first()
     except Exception:
         traceback.print_exc()
         return None
コード例 #14
0
def is_able_to_claim_redeem_code(user):
    redeems = db.session.query(Redeem).filter(
        Redeem.reserved_id == user.id,
        Redeem.code != func.binary('DOJO')).all()
    if redeems is not None and len(redeems) > 0:
        return False

    return True
コード例 #15
0
ファイル: model.py プロジェクト: zk467701860/MyWorkingProject
 def exist(session, qualified_name):
     try:
         if session.query(APIEntity.id).filter(APIEntity.qualified_name == func.binary(qualified_name)).first():
             return True
         else:
             return False
     except Exception:
         traceback.print_exc()
         return None
コード例 #16
0
 def get(self):
     form = ProfileForm()
     user = User.query.filter_by(user_name=func.binary(current_user.user_name)).first()
     form.username.data = current_user.user_name
     # form.password.data = user.password
     form.name.data =  user.real_name
     form.email.data = user.email
     form.rolename.data = ','.join([role.role_name for role in user.roles])
     return render_template("auth/profile.html", form = form)
コード例 #17
0
 def get_structure(self, abbrv):
     """
     Returns a structure
     This search has to be case sensitive!
     :param abbrv: the abbreviation of the structure
     :return: structure object
     """
     return self.session.query(Structure).filter(
         Structure.abbreviation == func.binary(abbrv)).one()
コード例 #18
0
 def find_by_student_uuid_and_time(self, student_uuid: str, time: float) -> Outing:
     generated_time = datetime.datetime.fromtimestamp(time + 32400)
     current_day = datetime.datetime(generated_time.year, generated_time.month, generated_time.day)
     model = (self.sql._db_session.query(Outing)
              .filter(Outing.student_uuid == func.binary(student_uuid))
              .filter(and_(Outing.start_time >= current_day,
                           Outing.end_time < current_day + datetime.timedelta(days=1))).first())
     self.sql._db_session.commit()
     self.sql._db_session.close()
     return model
コード例 #19
0
ファイル: model.py プロジェクト: zk467701860/MyWorkingProject
 def get_remote_object(self, session):
     if self.id:
         return self
     else:
         try:
             return session.query(APIInstanceEntity).filter(
                 APIInstanceEntity.qualified_full_name == func.binary(self.qualified_full_name)).first()
         except Exception:
             traceback.print_exc()
             return None
コード例 #20
0
    def get(cls, username) -> 'Account':
        # PS: 鉴权和计费共用
        # 查找用户明文密码
        with Transaction() as session:
            account = session.query(Account).filter(Account.username == func.binary(username)).first()

        if not account:
            log.warning(f'account not exist in db')

        return account or None
コード例 #21
0
ファイル: decorators.py プロジェクト: ninjadotorg/KPI
    def wrap(*args, **kwargs):
        current_user = get_jwt_identity()
        user = db.session.query(User).filter(
            User.email == func.binary(current_user)).first()

        if user is None or \
            user.role is None or \
            user.role.name != Role['HR']:
            return response_error("Access deny!")

        return f(*args, **kwargs)
コード例 #22
0
ファイル: model.py プロジェクト: zk467701860/MyWorkingProject
 def get_remote_object(self, session):
     if self.id:
         return self
     else:
         try:
             return session.query(APIAlias).filter(APIAlias.alias == func.binary(self.alias),
                                                   APIAlias.type == self.type,
                                                   ).first()
         except Exception:
             traceback.print_exc()
             return None
コード例 #23
0
ファイル: routes.py プロジェクト: yvid/AngelBoardProtoType
def get_Cpny():
    account = request.get_json(force=True)
    emailId = account['emailId']

    row = AccountInfo.query.filter(
        AccountInfo.emailIdF == func.binary(emailId))
    df = pd.read_sql(row.statement, row.session.bind)
    res = json.loads(df.to_json(orient='records'))

    db.session.close()

    return (jsonify({'accountInfo': res}), 200) if row else ('', 400)
コード例 #24
0
 def get_structure_color_rgb(self, abbrv):
     """
     Returns a color code in RGB format like (1,2,3)
     This search has to be case sensitive!
     :param abbrv: the abbreviation of the structure
     :return: tuple of rgb
     """
     row = self.session.query(Structure).filter(
         Structure.abbreviation == func.binary(abbrv)).one()
     hexa = row.hexadecimal
     h = hexa.lstrip('#')
     return tuple(int(h[i:i + 2], 16) for i in (0, 2, 4))
コード例 #25
0
ファイル: inv.py プロジェクト: yvid/AngelBoardProtoType
def inv_updater():
    inv = request.get_json(force=True)
    iSerial = inv['iSerial']
    invStep = inv['invStep']

    print('invStep :: ', invStep, flush=True)

    row = Inv.query.filter(Inv.iSerial == func.binary(iSerial)).first()

    if iSerial and invStep:
        row.invStep = invStep,
        row.chngDate = dt.now()
        db.session.commit()

    row = Inv.query.filter(Inv.iSerial == func.binary(iSerial))
    df = pd.read_sql(row.statement, row.session.bind)
    res = json.loads(df.to_json(orient='records'))

    db.session.close()

    return jsonify({'updateRes': res})
コード例 #26
0
ファイル: inv.py プロジェクト: yvid/AngelBoardProtoType
def inv_getDetail():
    serials = request.get_json(force=True)

    aSerial = serials['aSerial']
    hSerial = serials['hSerial']

    res = []

    row = Angel.query.filter(Angel.aSerial == func.binary(aSerial))

    df = pd.read_sql(row.statement, row.session.bind)
    res.append(json.loads(df.to_json(orient='records')))

    row = Human.query.filter(Human.hSerial == func.binary(hSerial))

    df = pd.read_sql(row.statement, row.session.bind)
    res.append(json.loads(df.to_json(orient='records')))

    db.session.close()

    return jsonify(res)
コード例 #27
0
def db_teacher(id=None, code=None, full_name=False):
    if id:
        teacher = Teacher.query.get(id)
    elif code:
        teacher = Teacher.query.filter(
            Teacher.code == func.binary(code),
            Teacher.school == db_utils.school()).first()
    if not full_name:
        return teacher
    elif teacher:
        return '{} ({} {})'.format(teacher.code, teacher.first_name,
                                   teacher.last_name)
    return None
コード例 #28
0
ファイル: routes.py プロジェクト: yvid/AngelBoardProtoType
def dup_user():
    account = request.get_json(force=True)
    emailId = account['emailId']

    row = Account.query.filter(Account.emailId == func.binary(emailId)).first()
    res = 'e0'

    if row:
        res = 's1'

    db.session.close()

    return res
コード例 #29
0
 def post(self):
     form = ProfileForm()
     if form.validate_on_submit():
         username = form.data['username']
         user = User.query.filter_by(user_name=func.binary(username)).first()
         user.email = form.email.data
         user.password = form.password.data
         user.real_name = form.name.data
         user.update_time = datetime.now()
         db.session.add(user)
         db.session.commit()
         flash("个人资料修改成功!")
     else:
         flash(form.errors.popitem()[1][0])
     return render_template("auth/profile.html", form=form)
コード例 #30
0
    def _handle_search(search_query):
        if len(search_query) < 3:
            return []

        filter_like = f'%{search_query.title()}%'
        authors = models.Terms.query.filter(
            models.Terms.name.like(func.binary(filter_like))).order_by(
                models.Terms.slug).all()

        result = []
        for author in authors:
            taxonomy = models.TermTaxonomies.query.filter_by(
                term_id=author.term_id, taxonomy='autor').first()
            if taxonomy:
                result.append(TermsList._build_author(taxonomy))
        return result