def _registration():
    """Register"""
    from server import logger
    bag = {
        'request_body': request.get_json(),
        'response_body': {},
    }

    logger.info(bag)
    request_body = bag.get('request_body')
    validate_request_body(bag)
    _id = get_uuid()
    db = Database()
    try:
        cursor, conn = db.connect()
        cursor.execute(
            """insert into user(id, email, name, password, phone)
            values(%s, %s, %s, %s, %s)""",
            (
                _id, request_body['email'],
                request_body['name'], request_body['password'],
                request_body['phone']
            )
        )
    except pymysql.err.IntegrityError as e:
        logger.error(e)
        raise DuplicateEntry
    else:
        pass

    return send_response(
        data={'id': _id},
        message='Resource Created Successfully',
        status_code=201
    )
Exemple #2
0
def course_branch_sem(text):
    button_list = []
    colm = 1
    course_full = branch_full = ''
    course_in, branch_in, sem_in = text
    for module, tag in COURSES_LIST.items():
        if course_in == tag:
            course_full = module
            break
    for branch, key in BRANCHES_COURSE[course_full].items():
        if branch_in == key:
            branch_full = branch
            break

    word = """Selected Course: `{}` \nSelected Branch: `{}` \nSelected Sem: `{}` \nSelect Subject :""". \
        format(course_full, branch_full, sem_in)

    # we don't use 'papers' here just use subs
    subs, papers = qpaper_utils.collect_subs_n_papers(course_full, branch_full,
                                                      sem_in)

    pre = [course_in, branch_in, sem_in]
    if len(subs) == 0:
        word += '\n _Unavailable_ \U0001F615'
        query_log = {
            'level': 3,
            'course': course_full,
            'branch': branch_full,
            'semester': sem_in,
            'subject': "",
            'available': False
        }
        threading.Thread(target=query_collect, args=(query_log, ),
                         daemon=True).start()
    else:
        for sub in subs:
            sub_ = ''.join(sub.split(' '))
            callback_str = "qa={}".format('+'.join(pre))
            callback_str += "+" + sub_

            if len(callback_str) > 64:
                logger.error("".join(text) + "=>" + callback_str + "#" +
                             str(len(callback_str)))
                callback_str = callback_str[:64]
                logger.info("serialized to =>" + callback_str)

            button_list.append(
                InlineKeyboardButton(
                    text="{}".format(sub),
                    callback_data=callback_str,
                ))

    # back_button data
    back_data = "qa={}".format("+".join([course_in, branch_in]))

    return button_list, word, colm, back_data
 def _validate_scope(self):
     try:
         if not isinstance(self.scope, Scope):
             logger.error('Provided scope must be of type Scope (enum).')
             abort(500)
     except AttributeError as e:
         logger.error(
             'Must define a valid scope as a property of the class. For example: `self.scope = Scope.MEMBER`'
         )
         abort(500)
Exemple #4
0
def add_args(ok, args, arg_list):
    if ok:
        try:
            args['args'] = {}
            for arg in arg_list:
                args['args'][arg] = request.args[arg]
        except Exception as e:
            logger.error('Occurred a error when added args£º%s',
                         e,
                         exc_info=True)
            return False, build_result(APIStatus.BadRequest)
    return ok, args
Exemple #5
0
    def init_database(self) -> None:
        """
        Se connecte à la base de données.

        :return:
        """
        try:
            self.db = Database("127.0.0.1", "root", "", "tipe")
            info("Connecté à la base de données")
        except:
            error(
                "Une erreur est survenue lors de la connexion à la base de données"
            )
def insert_phrases(user, phrases_list):
    if get_user_id(user.__dict__) is None:
        logger.error("insert_phrases: Bad user id")
        return None
    # User has updated tags, so add phrases that the user has typed
    user_id = get_user_id(user.__dict__)
    user_id['tags'] += user.tags
    user_id['tags'] = list(set(user_id['tags']))
    for p in phrases_list:
        phrase = p.__dict__
        user_id['phrases'].append(phrase)
    # Update both the tags and the phrases
    update_user(user_id)
Exemple #7
0
def add_payload(ok, data):
    if ok:
        try:
            # print(request.data)
            payload = request.json
            # print(payload)
            data['payload'] = payload
            # print(data['payload'].keys())
            return True, data
        except Exception as e:
            logger.error('Occurred a error when added payload £º%s',
                         e,
                         exc_info=True)
            return False, build_result(APIStatus.InternalServerError)
    return ok, data
    def im_save(path, image):
        ret = -1
        try:
            if image is not None and path != '':
                ret = image.save(path)
        except Exception as ex:
            ret = -2
            # print(ex)
            logger.error('occur error: %s', ex, exc_info=True)
        else:
            pass
        finally:
            pass

        return ret
    def recognition_frnn(ok, source):
        try:
            if ok:
                tic = time.time()
                print('start processing.............................................')

                # 1. get image
                image = CommdityRecognitionImp.get_image_from_base64(source)

                # 2. predict
                data = predict_frnn(image)

                toc = time.time()
                print("Request time: " + str(1000 * (toc - tic)) + " ms")
                print(data)
                return build_result(APIStatus.Ok, data=data), to_http_status(APIStatus.Ok)
            else:
                return source, to_http_status(source['status'])

        except Exception as e:
            logger.error('occur error: %s', e, exc_info=True)
            return build_result(APIStatus.InternalServerError), to_http_status(APIStatus.InternalServerError)
Exemple #10
0
import os

from server import logger
from server.app import build_app

database_url = os.getenv("DATABASE_URL")

if database_url is not None:
    database_url = database_url.replace("postgres", "postgis", 1)
    database_url = database_url.replace("sqlite", "spatialite", 1)
else:
    logger.error("No database url provided! Exiting.")
    exit(1)

app = build_app(database_url)