示例#1
0
def buildModel():
    response = {"response": "success"}
    NB_Model, count_vectorizer = buildModelFromExcel()
    app.config['model'] = NB_Model
    app.config['countVectorizer'] = count_vectorizer
    print(NB_Model)
    return flask_response(json.dumps(response),
                          status=200,
                          mimetype='application/json')
示例#2
0
def table_extraction():
    response = {"response": "success"}
    file = request.files['file']
    save_path = os.path.abspath(
        os.path.join(app.config['UPLOAD_FOLDER'], file.filename))
    print(save_path)
    file.save(save_path)
    extractTable(save_path)
    return flask_response(json.dumps(response),
                          status=200,
                          mimetype='application/json')
示例#3
0
def update_comment(comment_id):
    new_version_id = request.args.get("version_id")

    if new_version_id is None:
        msg = "Must provide accurate version_id to perform comment update"
        rsp = flask_response(msg, status=400, content_type="application/json")
        return rsp

    new_user = request.args.get("user")
    new_text = request.args.get("text")
    new_tags = request.args.get("tags")

    update_response = comments_table.update_comment(comment_id, new_user,
                                                    new_text, new_tags,
                                                    new_version_id)

    msg = update_response["ResponseMetadata"]["ResponseMsg"]
    status = update_response["ResponseMetadata"]["HTTPStatusCode"]

    rsp = flask_response(msg, status=status, content_type="application/json")
    return rsp
示例#4
0
def add_comment():
    user_email = request.args["user"]
    text = request.args["text"]
    tags = request.args.get("tags", [])

    new_comment = Comment(user_email, text, tags)
    comments_table.create_comment(new_comment.as_dict)
    location = "/api/comments/" + new_comment.comment_id
    msg = {"Location:": location}

    rsp = flask_response(json.dumps(msg),
                         status=201,
                         content_type="application/json")
    return rsp
示例#5
0
def add_response(comment_id):
    comment = comments_table.get_comment_by_id(comment_id)
    if not comment:
        rsp = flask_response(
            "Comment {} not found".format_map(comment_id),
            status=404,
            content_type="application/json",
        )
        return rsp

    user_email = request.args["user"]
    text = request.args["text"]
    response = Response(user_email, text)

    comments_table.add_response_to_comment(comment_id, response.as_dict)

    location = "/api/comments/{}/responses/{}".format(comment_id,
                                                      response.response_id)
    msg = {"Location:": location}

    rsp = flask_response(json.dumps(msg),
                         status=201,
                         content_type="application/json")
    return rsp
示例#6
0
def make_response(instance, status_code=200, indent=2):
    """
    make json http response with indent settings and auto encoding
    Args:
        instance: instance of a cmdbDao instance or instance of the subclass
        status_code: optional status code
        indent: indent of json response
    Returns:
        http valid response
    """
    from flask import make_response as flask_response

    # encode the dict data from the object to json data
    resp = flask_response(json.dumps(instance, default=json_encoding.default, indent=indent), status_code)
    # add header information
    resp.mimetype = DEFAULT_MIME_TYPE
    return resp
示例#7
0
def classifyDocument():
    response = {"response": "success"}
    file = request.files['file']
    save_path = os.path.abspath(
        os.path.join(app.config['UPLOAD_FOLDER'], file.filename))
    print(save_path)
    file.save(save_path)
    NB_Model = app.config['model']
    count_vectorizer = app.config['countVectorizer']
    if NB_Model is not None:
        print('Model loaded')
        documentType = classifyDocumentType(NB_Model, count_vectorizer,
                                            save_path)
        response = documentType[0]
    else:
        print('Model not loaded')
    return flask_response(json.dumps(response),
                          status=200,
                          mimetype='application/json')
示例#8
0
def make_api_response(body, status: int = 200, mime: str = None, indent: int = 2) -> BaseResponse:
    """
    Make a valid http response.

    Args:
        body: http body content
        status: http status code
        mime: mime type
        indent: display indent

    Returns:
        BaseResponse
    """
    from cmdb.interface import API_VERSION

    response = flask_response(dumps(body, default=default, indent=indent), status)
    response.mimetype = mime or DEFAULT_MIME_TYPE
    response.headers['X-API-Version'] = API_VERSION
    return response
示例#9
0
def buildExcelForModel():
    response = {"response": "success"}
    buildModelExcel()
    return flask_response(json.dumps(response),
                          status=200,
                          mimetype='application/json')
示例#10
0
def ping():
    response = {"response": "success"}
    return flask_response(json.dumps(response),
                          status=200,
                          mimetype='application/json')
示例#11
0
        def forward_request(service, method=None):
            # STEP 1. Read requests auth params
            auth = None
            if request.authorization is not None and len(
                    request.authorization) > 0:
                auth = ()
                for i in request.authorization:
                    auth = auth + (request.authorization[i], )

            if method == None:
                method = request.method

            if service == "upload/":
                if self.settings.SAFE_UPLOAD:
                    self.log("New upload request detected")
                    service = "/api/tools"

                    data = dict(request.form)

                    tmp_files = AdminFunctions.storeTmpFiles(
                        request.files, self.settings.TMP_DIRECTORY)
                    self.log("All files were temporary stored at: " +
                             ", ".join(tmp_files))

                    self.log("Forwarding the files uploading...")

                    history_id = data.get("history_id")[0]
                    galaxy_key = data.get("key")[0]

                    gi = GalaxyInstance(self.settings.GALAXY_SERVER,
                                        galaxy_key)

                    responses = []
                    for tmp_file in tmp_files:
                        responses.append(
                            gi.tools.upload_file(tmp_file, history_id))

                    for tmp_file in tmp_files:
                        removeFile(tmp_file)

                    return jsonify({'success': True, 'responses': responses})
                else:
                    service = "/api/tools"

                    data = dict(request.form)
                    # STEP 2. Generate the new requests
                    resp = requests.request(method=method,
                                            url=self.settings.GALAXY_SERVER +
                                            service,
                                            data=data,
                                            files=request.files,
                                            auth=auth,
                                            cookies=request.cookies,
                                            allow_redirects=False)

            elif service == "signup/":
                self.log("New sign up request detected")

                service = "/user/create?cntrller=user"

                data = dict(request.form)
                # STEP 2. Generate the new requests
                resp = requests.request(
                    method=method,
                    url=self.settings.GALAXY_SERVER + service,
                    params=dict(request.args),
                    headers={
                        u'content-type': u'application/x-www-form-urlencoded'
                    },
                    data=data,
                    auth=auth,
                    cookies=request.cookies,
                    allow_redirects=False)
            else:
                service = "/api/" + service

                self.log("New request detected (" + service + ")")

                # STEP 2. Generate the new requests
                resp = requests.request(method=method,
                                        url=self.settings.GALAXY_SERVER +
                                        service,
                                        params=dict(request.args),
                                        data=request.get_data(),
                                        auth=auth,
                                        cookies=request.cookies,
                                        allow_redirects=False)

            headers = []
            excluded_headers = [
                'content-encoding', 'content-length', 'transfer-encoding',
                'connection'
            ]
            headers = [(name, value)
                       for (name, value) in resp.raw.headers.items()
                       if name.lower() not in excluded_headers]

            self.log("Done! Returning response...")

            response = flask_response(resp.content, resp.status_code, headers)
            return response