Beispiel #1
0
def return_renamed():
    f = request.files['file']
    memory_file = ZIPTool(f).change_extension('txt')

    # FileWrapper used because of Pythonanywhere
    # https://stackoverflow.com/questions/50087728/alternative-of-send-file-in-flask-on-pythonanywhere
    w = FileWrapper(memory_file)

    res = Response(w, mimetype='application/zip', direct_passthrough=True)
    return res
Beispiel #2
0
def download():
    f = form_data_to_excel(request.form)
    w = FileWrapper(f)
    response = Response(w, direct_passthrough=True)
    response.headers.set(
        'Content-Type',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response.headers.set('Content-Disposition',
                         'attachment',
                         filename='grid.xlsx')
    return response
Beispiel #3
0
def send_result(resolution, images):
    try:
        result = get_result(resolution, images)
        bytes_result = BytesIO()
        result.save(bytes_result, 'JPEG', quality=70)
        bytes_result.seek(0)
        file = FileWrapper(bytes_result)
        return Response(file, mimetype='image/jpeg', direct_passthrough=True)
        # return send_file(bytes_result, mimetype='image/jpeg')
    except requests.exceptions.RequestException as e:
        print(e)
        return render_template('error.html')
Beispiel #4
0
def preview2k(dataset):
    dsid = getDatasetId(dataset)
    import tifffile
    # tiffb = tifffile.imread(io.BytesIO(session.execute(text("SELECT ST_AsTIFF(raster_2k_all, 'GTiff') from dataset;")).fetchone()[0]))
    # b = io.BytesIO(session.execute(text("SELECT ST_AsTIFF(raster_2k_all, 'GTiff') from dataset;")).fetchone()[0])
    # b = io.BytesIO(session.execute(text("SELECT ST_AsTIFF(ST_Resample(raster_2k_all,100,100), 'GTiff') from dataset;")).fetchone()[0])
    b = io.BytesIO(
        session.execute(
            text(
                "SELECT ST_AsJPEG(ST_Resample(raster_2k_all,200,200)) from dataset;"
            )).fetchone()[0])
    w = FileWrapper(b)
    return Response(w, mimetype="image/jpeg", direct_passthrough=True)
Beispiel #5
0
def generate():
    label_data = json.loads(request.args.get("layout"))
    min_lon = float(request.args.get("minLon"))
    max_lon = float(request.args.get("maxLon"))

    min_lat = float(request.args.get("minLat"))
    max_lat = float(request.args.get("maxLat"))

    if not label_data:
        raise BadRequest("'layout' must be provided.")
    if min_lon > max_lon:
        raise BadRequest("Min longitude is larger than max longitude.")
    if min_lat > max_lat:
        raise BadRequest("Min latitude is larger than max latitude.")

    label_image = create_label_image(
        label_data,
        INPUT_WIDTH, INPUT_HEIGHT,
        (min_lon, min_lat, max_lon, max_lat)
    )

    label_tensor = transforms.RandomCrop(
        (INPUT_HEIGHT, INPUT_WIDTH)
    )(label_image)
    label_tensor = TRANSFORMS(label_tensor)
    generated_tensor = generator(label_tensor.unsqueeze(0)).squeeze()

    generated_array = min_max(
        np.transpose(
            generated_tensor.detach().numpy(),
            (1, 2, 0)
        )
    ) * 255
    generated_image = Image.fromarray(
        generated_array.astype('uint8')
    ).convert('RGB')

    result_bytes = io.BytesIO()
    result_image = Image.new('RGB', (INPUT_WIDTH * 2, INPUT_HEIGHT))
    x_offset = 0
    for image in [label_image, generated_image]:
        result_image.paste(image, (x_offset, 0))
        x_offset += INPUT_WIDTH

    result_image.save(result_bytes, format='JPEG')
    result_bytes.seek(0)

    return Response(
        FileWrapper(result_bytes),
        mimetype="image/jpeg"
    )
Beispiel #6
0
def return_converted():
    f = request.files['file']
    allowed_samples_regexp = request.form.get('allowed_samples_regexp')
    # text file required for csv
    out_file = StringIO()
    convert_genmap_to_dnastat(f, out_file, sample_match=allowed_samples_regexp)
    out_file.seek(0)

    # Convert output text stream to Bytes stream
    bytes_stream = BytesIO(out_file.read().encode('utf-8'))

    # FileWrapper used because of Pythonanywhere
    # https://stackoverflow.com/questions/50087728/alternative-of-send-file-in-flask-on-pythonanywhere
    w = FileWrapper(bytes_stream)

    res = Response(w, mimetype='text/csv', direct_passthrough=True)
    return res
Beispiel #7
0
def get_avatar():
    """Get favicon.

    :return: result

    """
    import base64
    import io
    from werkzeug import FileWrapper
    site_info = SiteInfo.get()
    if not site_info:
        return jsonify({})
    favicon = site_info.favicon.split(',')[1]
    favicon = base64.b64decode(favicon)
    b = io.BytesIO(favicon)
    w = FileWrapper(b)
    return Response(b, mimetype="image/x-icon", direct_passthrough=True)
Beispiel #8
0
def graph(metric_id, from_dt, to_dt):
    #print('from = `%s`, to = `%s`' % (from_dt, to_dt))
    data = db.get_rows(q_graph, {
        'metric_id': metric_id,
        'from': from_dt,
        'to': to_dt
    })
    #print(data)
    dt = np.array([i['dt'] for i in data])
    v = np.array([i['integer_value'] for i in data])
    fig = plt.figure(figsize=(10, 4), dpi=90)
    p_main = fig.add_subplot()
    p_main.plot(dt, v)
    p_main.set(xlabel='time', ylabel=data[0]['name'], title=data[0]['name'])
    p_main.fmt_xdata = mdates.DateFormatter('%Y-%m-%d %H:%M')
    p_main.grid()
    buf = io.BytesIO()
    plt.savefig(buf, format='svg')
    w = FileWrapper(buf)
    buf.seek(0)
    return Response(w, mimetype="image/svg+xml", direct_passthrough=True)
Beispiel #9
0
    def send_byte_photo(self, byte_png):
        byte_png = io.BytesIO(byte_png)

        w = FileWrapper(byte_png)
        return flask.Response(w, mimetype="image/jpg", direct_passthrough=True)
Beispiel #10
0
def module003_assignment_send(course_id, assignment_id):

    follow = Follow.query.filter(
        and_(Follow.course_id == course_id,
             Follow.user_id == current_user.id)).first()
    form = GradesForm()
    form2 = DownloadForm()
    course = Course.query.filter_by(id=course_id).first()
    if follow:
        assignment = Assignment.query.filter_by(id=int(assignment_id)).first()
        if course.user_id == current_user.id:
            entrega = Entrega.query.filter_by(assignment_id=int(assignment_id))
            if request.method == 'POST':

                entrega2 = Entrega.query.filter(
                    and_(Entrega.assignment_id == int(assignment_id),
                         Entrega.user == int(request.form['user']))).first()
                if form.validate_on_submit():
                    try:
                        entrega2.nota = float(form.name.data)
                        db.session.commit()
                        flash("Grade updated!")
                    except:
                        db.session.rollback()
                        flash("Error updating grade!")
                    return render_template(
                        "module003_correccion_ejercicio.html",
                        module='module003',
                        assignment=assignment,
                        entrega=entrega,
                        form=form,
                        form2=form2)

                if form2.validate_on_submit():
                    file_contents = Entrega.query.filter(
                        and_(Entrega.assignment_id == int(assignment_id),
                             Entrega.user == int(
                                 request.form['user']))).first()
                    bytesio = BytesIO(file_contents.file)
                    fileW = FileWrapper(bytesio)
                    return Response(fileW,
                                    mimetype="application/zip",
                                    direct_passthrough=True)

            return render_template("module003_correccion_ejercicio.html",
                                   module='module003',
                                   assignment=assignment,
                                   entrega=entrega,
                                   form=form,
                                   form2=form2)
        else:
            entrega = Entrega.query.filter(
                and_(Entrega.assignment_id == assignment_id,
                     Entrega.user == current_user.id)).first()
            if request.method == 'POST':
                if entrega:
                    db.session.delete(
                        Entrega.query.filter_by(
                            user=current_user.id,
                            assignment_id=assignment_id).first())
                    db.session.commit()
                    return redirect(
                        url_for('module003.module003_assignment_course',
                                course_id=course_id))

                file_contents = request.files['file']
                newfile = Entrega(name=file_contents.filename,
                                  file=file_contents.read(),
                                  user=current_user.id,
                                  assignment_id=assignment_id)
                try:
                    db.session.add(newfile)
                    db.session.commit()
                    flash("Uploaded file succesfully")
                except:
                    db.session.rollback()
                    flash("Error creating Assignment!")
                return redirect(
                    url_for('module003.module003_assignment_course',
                            course_id=course_id))
            else:
                return render_template("module003_upload_assignment.html",
                                       module='module003',
                                       assignment=assignment,
                                       entrega=entrega,
                                       assignment_id=assignment_id)

    else:
        flash("Access denied!")
        #       abort(404,description="Access denied!")
        return redirect(url_for('index'))