Esempio n. 1
0
    def createAccount():
        request.get_json(force=True)
        name = request.json.get("name")
        if not name: return responde(400, True, 'No name was provided', None)

        email = request.json.get('email')
        if not email: return responde(400, True, 'No email was provided', None)

        password = request.json.get('password')
        if not password:
            return responde(400, True, 'No password was provided', None)

        existingUser = None
        try:
            existingUser = User.objects.raw({'email': email})[0]
        except:
            print('User does not exists')

        if existingUser: return responde(400, True, 'Email already used', None)

        try:
            newUser = User(name, email, password, False).save()
            return responde(200, False, 'User was created', newUser.toJson())
        except:
            return responde(500, True, 'There was an error creating the user',
                            None)
Esempio n. 2
0
def category_api():
    method = request.method

    if method == 'GET':
        categories = Category.query.all()

        response = jsonify(
            categories=[category.serialize for category in categories])
        return response

    elif method == 'POST':
        data = request.get_json()

        objects = []
        for i in data:
            objects.append(Category(name=i['name']))

        db.session.add_all(objects)
        db.session.commit()

        return jsonify([r.serialize for r in objects])

    elif method == 'DELETE':
        if request.args:
            id = request.args.get('id')
            status = Category.query.filter_by(id=id).delete()

            db.session.commit()
            return jsonify(rows_affected=status)
        else:
            raise InvalidUsage('Please specify your parameters',
                               status_code=500)

    elif method == 'PUT':
        if request.args:
            id = request.args.get('id')
            data = request.get_json()

            status = Category.query.filter_by(id=id).update(data)

            db.session.commit()
            return jsonify(rows_affected=status)
        else:
            raise InvalidUsage('Please specify your parameters',
                               status_code=500)

    else:
        raise InvalidUsage('No such method!', status_code=500)
    def post(self):
        json_data = request.get_json(force=True)
        result = CopyProjectModel.copy_project(json_data)

        # Clear redis cache
        r.delete("all_projects")
        return result
Esempio n. 4
0
def AddCategoryBlg():
    Urlbase = URLBASE
    username = CONFIG['TYPE_USER']['ROOT']
    connect = Model(username)
    req = request.get_json()
    result = {}
    name_category = req["name_category"]

    #id = None
    Insert_ofCategory = dict()
    Insert_ofCategory = {
        'TABLE': 'blg_category',
        'Col1': 'id',
        'Col2': 'name',
        'Val3': '%s',
        'Val4': '%s'
    }

    nombre_id = "id"
    nombre_tabla = "blg_category"
    id_max = connect.MAX_ID_TABLE(username, nombre_tabla, nombre_id)
    print(id_max[0]["max_id"])
    if id_max[0]["max_id"] == None:
        id_sig = "1"
    else:
        proximo_id = id_max[0]["max_id"] + 1
        id_sig = str(proximo_id)

    Data = [id_sig, name_category]
    ''' result["new_proveedor"] = name '''
    res_insert = connect.IT_TABLE(username, Insert_ofCategory, Data)
    result = {"hola": 2}

    return result
    def post(self):
        json_data = request.get_json(force=True)
        result = CustomActionsModel.create_action(json_data)

        # Clear redis cache
        r.delete("all_custom_actions")
        return result
    def post(self, project_id):
        json_data = request.get_json(force=True)
        result = DomainsModel.create_domain(project_id, json_data)

        # Clear redis cache
        r.delete("all_domains_" + str(project_id))
        return result
Esempio n. 7
0
def ver_coordenadas():
    req = request.get_json(
    )  #Conversion de datos tipos json a lenguaje python (diccionario/lista)
    print(req)
    lista_coordenadas = req[
        "coordenadas"]  #Extraer los datos como lista python
    print(lista_coordenadas)
    for item in lista_coordenadas:
        print(lista_coordenadas[0])

    #Diccionario con lista de coordenadas se enviara a la vista
    result = {"array": lista_coordenadas}
    #Respuesta de exito de peticion.
    #No se como tienes los datos de coordenadas almacenadas pero un ejemplo de modelo de objeto
    # que puede entender json es este. Son varios diccionarios con latitud y longitud y estos dentro de una lista
    # algo asi similar te deberia devolver una consulta de la base de datos y ese array lo guardas en un diccionario
    # con clave coordenadas. Yo no tengo base de datos asi que solo simulo la lectura con datos traidos desde la vista
    """  {'coordenadas': [{'lat': 4.443581, 'lng': -75.230992}, 
    {'lat': 4.445581, 'lng': -75.231992}, 
    {'lat': 4.446581, 'lng': -75.232992}, 
    {'lat': 4.447581, 'lng': -75.233992}, 
    {'lat': 4.448581, 'lng': -75.234992}, 
    {'lat': 4.449581, 'lng': -75.235992}, 
    {'lat': 4.440581, 'lng': -75.236992}, 
    {'lat': 4.441581, 'lng': -75.237992}, 
    {'lat': 4.442581, 'lng': -75.238992}, 
    {'lat': 4.447581, 'lng': -75.239992}]
    } """
    res = make_response(jsonify({"message": "OK"}), 200)
    """Nota: Los print y el for comentados permiten ver los datos en consola pero como se muestran en 
       servidor WEB no se pueden ver a menos que se implemente desde cero la APP"""
    return result
Esempio n. 8
0
def Category_id():
    Urlbase = URLBASE
    username = CONFIG['TYPE_USER']['ROOT']
    connect = Model(username)
    req = request.get_json()
    id_categoria = req["id_categoria"]
    wid = id_categoria
    TablaServicioAutomotor = dict()
    TablaServicioAutomotor = {
        'TABLE': 'products',
        'Col1': 'id_product ',
        'Col2': 'id_proveedor',
        'Col3': 'id_categoria',
        'Col4': 'name',
        'Col5': 'precio',
        'Col6': 'descripcion',
        'Col7': 'media',
        'Whe8': 'id_categoria=%s'
    }
    Data = (wid, )

    DatosServicioV = connect.SW_TABLE(username, TablaServicioAutomotor, Data)
    print(DatosServicioV)
    DatosAllMedia = json.dumps(DatosServicioV)

    return (DatosAllMedia)
    def delete(self):
        # Deleting record
        json_data = request.get_json()
        result = CustomActionsModel.delete_action(json_data)

        # Clear redis cache
        r.delete("all_custom_actions")
        return result
    def post(self, story_id):
        json_data = request.get_json(force=True)

        result = StoryDetailModel.insert_story_details(json_data)

        # Clear redis cache
        r.delete("response_" + str(story_id))
        return result
    def delete(self):
        # Deleting record
        object_id = request.get_json()
        result = ProjectsModel.delete_project(object_id)

        # Clear redis cache
        r.delete("all_projects")
        return result
    def post(self, project_id):
        json_data = request.get_json(force=True)

        result = EntityModel.create_entity(json_data)

        # Clear redis cache
        r.delete("entity_" + str(project_id))
        return result
    def post(self, response_id):
        json_data = request.get_json(force=True)

        result = ResponseDetailModel.insert_response_detail(json_data)

        # Clear redis cache
        r.delete("response_" + str(response_id))
        return result
    def post(self, intent_id):
        json_data = request.get_json(force=True)

        result = IntentDetailModel.insert_intent_detail(json_data)

        # Clear redis cache
        r.delete("intent_" + str(intent_id))
        return result
    def delete(self, project_id):
        # Deleting record
        object_id = request.get_json()
        result = DomainsModel.delete_domain(project_id, object_id)

        # Clear redis cache
        r.delete("all_domains_" + str(project_id))
        return result
    def delete(self, story_id):
        # Deleting record
        json_data = request.get_json(force=True)

        result = StoryDetailModel.delete_story_detail(json_data)

        # Clear redis cache
        r.delete("response_" + str(story_id))
        return result
    def delete(self, intent_id):
        # Deleting record
        json_data = request.get_json(force=True)

        result = IntentDetailModel.delete_intent_detail(json_data)

        # Clear redis cache
        r.delete("intent_" + str(intent_id))
        return result
    def delete(self, project_id):
        # Deleting record
        json_data = request.get_json(force=True)

        result = EntityModel.delete_entity(json_data)

        # Clear redis cache
        r.delete("entity_" + str(project_id))
        return result
    def put(self, project_id):

        # Updating record
        json_data = request.get_json(force=True)
        result = DomainsModel.update_domain(project_id, json_data)

        # Clear redis cache
        r.delete("all_domains_" + str(project_id))
        return result
    def put(self):

        # Updating record
        json_data = request.get_json(force=True)
        result = CustomActionsModel.update_action(json_data)

        # Clear redis cache
        r.delete("all_custom_actions")
        return result
    def put(self):

        # Updating record
        json_data = request.get_json(force=True)
        result = ProjectsModel.update_project(json_data)

        # Clear redis cache
        r.delete("all_projects")
        return result
Esempio n. 22
0
def login():
    """
    Checking if user is authorized and authorizing if not (as a random user)
    req.args: {
        # login: String,
        # pass: String
    }
    :return:
    {
        user: User,
        error: 0,  # 2 - DB error
    }
    """

    result = {'error': 0, 'user': None}

    if 'user_id' in session:
        # Taking user info from a current session
        result['user'] = helpers.session_to_user_result(session)
    else:
        user = None

        # If user_id is provided (was stored on a frontend part)
        if request.get_json() is not None \
                and request.get_json().get('user_id') is not None:
            user = User.load_user(int(request.get_json().get('user_id')))

        # Getting a random user if user_id is not provided or not found in DB
        if user is None:
            try:
                user = User.load_random_user()
            except Exception as ex:
                result['error'] = 2
                # or raise further maybe
                return result

        # Setting data to the session and returning a result
        if user is not None:
            helpers.user_to_session(session, user)
            result['user'] = helpers.session_to_user_result(session)
        else:
            result['error'] = 1

    return result
 def post(self):
   content = request.get_json()
   print(content)
   p = m.Produk(id=content['id'], nama=content['nama'], stok=content['stok'], harga=content['harga'], kategori_id=content['kategori_id'], produsen_id=content['produsen_id'], detail=content['detail'], gambar=content['gambar'], cakupan=content['cakupan'])
   db.session.add(p)
   db.session.commit()
   resp = {
     'message': 'add product {} success'.format(content['nama'])
   }
   return resp
Esempio n. 24
0
    def gradeTest():
        from bson.objectid import ObjectId
        user = UserController.userFromSession()
        if not user: return responde(401,True,'You must be log in to take the test',None)

        request.get_json(force=True)
        answers = list(request.json.get('answers'))
        
        try:
            for answer in answers:
                currEcg = ECGModel.objects.raw({'_id': ObjectId(answer['id'])})[0]
                if answer['category'] != currEcg.category: return responde(200,True,'One or more answers were incorrect',None)
        except Exception as e:
            return responde(404,True,'One or more of the ecg doenst exist: ' + str(e),None)

        # Si llego aqui, significa que todas las respuestas fueron correctas
        user.isAuthorized = True
        user.save()
        return responde(200,False,'User is now authorized',user.toJson())
    def post(self):
        json_data = request.get_json(force=True)

        project_id = json_data['project_id']
        domain_id = json_data['domain_id']

        result = StoryModel.create_story(json_data)

        # Clear redis cache
        r.delete("stories_" + str(project_id) + "_" + str(domain_id))
        return result
    def delete(self):
        # Deleting record
        json_data = request.get_json(force=True)

        project_id = json_data['project_id']
        domain_id = json_data['domain_id']

        result = ResponseModel.delete_response(json_data)

        # Clear redis cache
        r.delete("responses_" + str(project_id) + "_" + str(domain_id))
        return result
Esempio n. 27
0
def AddPostBlg():
    Urlbase = URLBASE
    username = CONFIG['TYPE_USER']['ROOT']
    connect = Model(username)
    req = request.get_json()
    result = {}
    id_category = req["id_category"]
    id_users = req["id_users"]
    title_post = req["title_post"]
    date_post = req["date_post"]

    #id = None
    Insert_ofPost = dict()
    Insert_ofPost = {
        'TABLE': 'post',
        'Col1': 'id',
        'Col2': 'title',
        'Col3': 'image',
        'Col4': 'created_at',
        'Col5': 'status',
        'Col6': 'user_id',
        'Col7': 'category_id',
        'Val8': '%s',
        'Val9': '%s',
        'Val10': '%s',
        'Val11': '%s',
        'Val12': '%s',
        'Val13': '%s',
        'Val14': '%s'
    }

    nombre_id = "id"
    nombre_tabla = "post"
    id_max = connect.MAX_ID_TABLE(username, nombre_tabla, nombre_id)
    print(id_max[0]["max_id"])
    if id_max[0]["max_id"] == None:
        id_sig = "1"
    else:
        proximo_id = id_max[0]["max_id"] + 1
        id_sig = str(proximo_id)

    img_name = "post" + id_sig + "user" + id_users + "catg" + id_category + ".jpg"
    status = "1"

    Data = [
        id_sig, title_post, img_name, date_post, status, id_users, id_category
    ]

    res_insert = connect.IT_TABLE(username, Insert_ofPost, Data)
    result = {"hola": 2}

    return result
Esempio n. 28
0
def AddUserBlg():
    urlrev = URLBASE
    username = CONFIG['TYPE_USER']['ROOT']
    connect = Model(username)
    print(connect)
    req = request.get_json()
    #result = {}
    #wid = req["name_user"]
    id = None
    ''' let name_user = evt.target.form[0].value
    let lastname = evt.target.form[1].value
    let username = evt.target.form[2].value
    let email = evt.target.form[3].value
    let password = evt.target.form[4].value
    let image = evt.target.form[5].value
    let created_at = evt.target.form[6].value '''
    name_user = req["name_user"]
    lastname = req["lastname"]
    user_name = req["username"]
    email = req["email"]
    password = req["password"]
    image = req["image"]
    created_at = req["created_at"]
    result = {}

    Insert_ofblg_user = dict()
    Insert_ofblg_user = {
        'TABLE': 'blg_user',
        'Col1': 'id',
        'Col2': 'name',
        'Col3': 'lastname',
        'Col4': 'username',
        'Col5': 'email',
        'Col6': 'password',
        'Col7': 'image',
        'Col8': 'created_at',
        'Val9': '%s',
        'Val10': '%s',
        'Val11': '%s',
        'Val12': '%s',
        'Val13': '%s',
        'Val14': '%s',
        'Val15': '%s',
        'Val16': '%s'
    }
    Data = [
        id, name_user, lastname, user_name, email, password, image, created_at
    ]
    result["new_topico"] = "Registro exitoso"
    res_insert = connect.IT_TABLE(username, Insert_ofblg_user, Data)

    return result
    def put(self):

        # Updating record
        json_data = request.get_json(force=True)

        project_id = json_data['project_id']
        domain_id = json_data['domain_id']

        result = IntentsModel.update_intent(json_data)

        # Clear redis cache
        r.delete("intents_" + str(project_id) + "_" + str(domain_id))
        return result
Esempio n. 30
0
def create_admin():
    """
    This route is responsible for creating new admins. This should be disabled to prevent additional account creation
    :return: a JSON file containing new user's info
    """
    data = request.get_json()
    hashed_password = generate_password_hash(data['password'], method='sha256')
    username = data['username']
    new_admin = Admin(username, hashed_password)
    db.session.add(new_admin)
    db.session.commit()

    return admin_Schema.jsonify(new_admin)