python Unsupported method ('POST') - python

python Unsupported method ('POST') this program is meant to convert images to text but I kept getting this error over and over I don't know what is the problem
I don't know exactly if the problem with the HTML code or this code
or am I missing other files
I don't quite understand the HTML code so I will be thankful if you elaborate
from gettext import gettext
from click import get_text_stream
from flask import Flask, render_template, request
import os, pytesseract
from jinja2 import Template
from flask_uploads import UploadSet, configure_uploads, IMAGES
from PIL import Image
project_dir = os.path.dirname(os.path.abspath(__file__))
app = Flask(__name__, static_url_path='', static_folder = 'static', template_folder = 'gg.html')
photos = UploadSet('photos', IMAGES)
app.config['DEBUG'] = True
app.config['UPLOAD_FOLDER'] = 'images'
class UploadText(object):
def __init__(self, file):
self_file = pytesseract.image_to_string(Image.open(project_dir + '/imges/' + file))
#app.route('/gg', methods =["POST" , "GET"])
def home():
if request.method == "POST":
if 'photo' not in request.files:
return 'there is no photo in form'
name = request.form['img-name'] + '.jpg'
photo = request.files['photo']
path = os.path.join(app.config['UPLOAD_FOLDER'], name)
photo.save(path)
textObject = get_text_stream(name)
return textObject.file
return render_template('gg.html')
if __name__ == ' __main__':
app.run()
The HTML:
<head>
<meta charset = "utf-8">
<title> Image to Text</title>
</head>
<body>
<div class='text-center'><br><br>
<form method='post' enctype="multipart/form-data">
<input type="file" class='btn btn-dark' name='photo'>
<input id ='input' type='text' class ='form-control' placeholder='enter image name' name='img-name'>
<input class = 'btn btn-dark' type='submit'>
</form>
</div>
</body>
<style>
#input{
margin: auto;
width: auto;
}
</style>

You don't specify an action attribute in the HTML <form> tag, which tells the form where to submit to. Instead try:
<form method='post' action='/gg' enctype="multipart/form-data">
Of course it's also possible to render the /gg part dynamically, based on the name of your python function home:
<form method='post' action='{{ url_for("home") }}' enctype="multipart/form-data">

Related

Showing an image on an HTML page without saving to disk

I want to load an image from the folder do some processing on it and then show it on the HTML page without storing on the disk. I followed this post which discusses similar problem but image is not showing
Here is the code I am using
app.py
from flask import Flask, render_template
from base64 import b64encode
import cv2 as cv
import os
app = Flask(__name__)
APP_ROOT = os.path.dirname(os.path.abspath(__file__))
target = os.path.join(APP_ROOT, 'static')
#app.route("/")
def index():
uri1 = ''
return render_template("output.html", uri1=uri1)
#app.route("/img_prcoess", methods=['POST'])
def img_prcoess():
# Read the image
src_img = cv.imread("/".join([target, 'bradley_cooper.jpg']))
# Convert image to Gray
img1_gray = cv.cvtColor(src_img, cv.COLOR_BGR2GRAY)
# Encode
uri1 = "data:%s;base64,%s" % ("image/jpeg", b64encode(img1_gray))
return render_template("output.html", uri1=uri1)
if __name__ == "__main__":
app.run(port=4444, debug=True)
output.html
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form id="form1" action="{{ url_for('img_prcoess') }}" method="POST" enctype="multipart/form-data">
<input type="submit" value="Show Image" id="button1" width="100px">
</form>
<img style="height: 300px" src="{{ uri1 }}">
</body>
Directory Structure
You cannot convert the raw data of the image into a data url. You have to change the format first.
#app.route('/process', methods=['POST'])
def process():
path = os.path.join(APP_ROOT, 'static', 'example.jpg')
srcimg = cv.imread(path)
dstimg = cv.cvtColor(srcimg, cv.COLOR_BGR2GRAY)
retval, buffer = cv.imencode('.jpg', dstimg)
uri = "data:%s;base64,%s" % ('image/jpeg', b64encode(buffer).decode('ascii'))
return render_template('process.html', **locals())

TypeError: 'JpegImageFile' object is not callable

I'm actually trying to link my ml model(inception) with flask . The
output is binary (0 or 1). The image format is jpg or jpeg (both). I have tried with .stream while asking for input. Actually the model doesnt take image when file = Image.open(request.files['file'].stream).
flask code :
import os
from try1 import obj12
from flask import Flask, request, render_template,
send_from_directory,send_file
from PIL import Image
import io
import cv2
app = Flask(__name__)
#app.route("/")
def index():
return render_template('test.html')
#app.route("/upload", methods=['GET','POST'])
def upload():
file = request.files['file']
image = Image.open(file)
count = obj2(image)
print (count)
return (count)
if __name__ == "__main__":
#port = int(os.environ.get('PORT', 5000))
app.run(debug=True)
html code :
<!DOCTYPE html>
<html>
<head>
<title>Upload</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js">
</script>
</head>
<body>
<form id="upload-form" action="{{ url_for('upload') }}" method="POST"
enctype="multipart/form-data">
<strong>Files:</strong><br>
<input id="file-picker" type="file" name="file" accept="image/*"
multiple>
<div id="msg"></div>
<input type="submit" value="Upload!" id="upload-button">
</form>
</body>
</html>
Just want to pass my image in that model.

Files not uploading in flask

I am trying to upload files into server using flask but the files are *not uploading.
I am new to python and flask.
import os
from flask import *
app = Flask(__name__)
APP_ROOT = os.path.dirname(os.path.abspath(__file__))
#app.route('/')
def index():
return render_template('upload.html')
#app.route('/upload', methods = ['POST'])
def upload():
target = os.path.join(APP_ROOT, 'uploads/')
if not os.path.join(target):
os.mkdir(target)
for file in request.files.getlist('file'):
print(file.filename)
destination = '/'.join([target, file.filename])
print(destination)
file.save(destination)
return render_template('successful.html')
if __name__ == '__main__':
app.run(debug = True)
upload.html
<!DOCTYPE html>
<html>
<head>
<title> Upload file </title>
</head>
<body>
<form id="upload-form" action="{{ url_for('upload') }}"
method="post" enctype="multipart/form-data">
<input type="file" name="cssv_file" multiple>
<input type="submit" value="Submit"/>
</form>
</body>
</html>
Change this line
if not os.path.join(target):
to
if not os.path.isdir(target):

Get input filename and extension without actual uploading witn Flask

I use Flask+Python to locate relevant files for further processing. Currently I'm only able to upload files to a specified directory with the following:
Backend:
from flask import Flask, render_template, request
from werkzeug import secure_filename
app = Flask(__name__)
#app.route('/upload')
def upload_file():
return render_template('upload.html')
#app.route('/uploader', methods = ['GET', 'POST'])
def upload_file():
if request.method == 'POST':
f = request.files['file']
f.save(secure_filename(f.filename))
return 'file uploaded successfully'
if __name__ == '__main__':
app.run(debug = True)
Frontend:
<html>
<body>
<form action = "http://localhost:5000/uploader" method = "POST"
enctype = "multipart/form-data">
<input type = "file" name = "file" />
<input type = "submit"/>
</form>
</body>
</html>
But I have several problems and questions with this solution:
I don't want actually touch (move/upload) any file, I only need the
filenames of the selected files. How to discard the actual uploading
and get the filenames as a list?
Is there any way to select a directory (and not specific files) for batch processing?
You can do it with Javascript ;)
Change your server side code to this:
from flask import Flask, render_template, request
from werkzeug import secure_filename
app = Flask(__name__)
#app.route('/upload')
def upload_file():
return render_template('upload.html')
#app.route('/uploader', methods = ['GET', 'POST'])
def uploader_file():
print(request)
if request.method == 'POST':
f = request.form['filename']
return f
if __name__ == '__main__':
app.run(debug = True)
And change your upload.html like this:
<html>
<body>
<script type="text/javascript">
function readURL(){
var fullPath = document.getElementById('upload').value;
if (fullPath) {
var startIndex = (fullPath.indexOf('\\') >= 0 ? fullPath.lastIndexOf('\\') : fullPath.lastIndexOf('/'));
var filename = fullPath.substring(startIndex);
if (filename.indexOf('\\') === 0 || filename.indexOf('/') === 0) {
filename = filename.substring(1);
}
document.getElementById("filename").value = filename;
}
}
</script>
<input id="upload" type ="file" name = "file" onchange="readURL();" />
<form action = "http://localhost:5000/uploader" method = "POST"
enctype = "multipart/form-data">
<input id="filename" type="hidden" name="filename" />
<input type = "submit"/>
</form>
</body>
</html>
according to #RaminNietzsche's answer, I make a some changes.
frontend: input with attribute webkitdirectory enable web browser(Chrome, Firefox works, Safari doesn't) upload directory
<input id="directory" type='file' onchange="readFiles()" webkitdirectory>
<form action="{{ url_for('upload') }}" method="POST" enctype="multipart/form-data">
<input id="filenames" type="hidden" name="filenames"/>
<input type="submit"/>
</form>
<script type="text/javascript">
function readFiles() {
var directory = document.getElementById('directory').files;
var filenames = [];
for (var i = 0; i < directory.length; i++) {
filenames.push(directory[i].name);
}
document.getElementById("filenames").value = filenames;
}
</script>
backend:
#app.route("/upload", methods=["POST"])
def upload():
filenames = request.form.get('filenames', '').split(',')
# handle filenames here
return 'file uploaded successfully'

Why does request.get() return empty string?

I am new to python and google app-engine. I made the simple code to get input from a form and then display it on a new page . However, the self.request.get() methods returned empty strings. Why is this happening and how do I solve this problem?
import os
import jinja2
import webapp2
template_dir = os.path.join(os.path.dirname(__file__), 'templates')
jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir), autoescape = True)
class NewPost(webapp2.RequestHandler):
def get(self):
self.response.out.write(jinja_env.get_template('newpost.html').render())
def post(self):
title = self.request.get('title')
body = self.request.get('body')
self.redirect('/message')
class Message(webapp2.RequestHandler):
def get(self):
title = self.request.get('title')
body = self.request.get('body')
self.response.out.write('message: ' + title + body)
app = webapp2.WSGIApplication([webapp2.Route(r'/', handler=NewPost, name='newpost'), webapp2.Route(r'/message', handler=Message, name='message')], debug = True)
the newpost.html is:
<!DOCTYPE HTML>
<html>
<head>
<title> Title </title>
</head>
<body>
<form method="post">
<label>
<div>Title</div>
</label>
<input type="text" name="title" value="{{title}}">
<label>
<div>Body</div>
</label>
<textarea name="body">{{body}}</textarea>
<input type="submit">
</form>
</body>
</html>
The form parameters are available to the POST / request (NewPost.post()), but they are not carried forward on the redirect to /message. You have to store the form data somehow (such as to the datastore) when handling the POST, then retrieve it from storage after the redirect.

Categories