Why does request.get() return empty string? - python

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.

Related

python Unsupported method ('POST')

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">

How to pass value to python in flask api from a input field

<!DOCTYPE html>
<html>
<head>
<title>Rango</title>
</head>
<h1>We Would Like to know your name </h1>
<h2>192.168.29.109</h2>
<label for="username">Username:</label>
<input type="text" id="username" name="username" maxlength="10"><br><br>
<button onclick="https://">GO FURTHER</button>
Submit<br />
About<br />
<img src="{{ user_image }}" alt="User Image">
</div>
</body>
</html>
from here python flask file I have only 1 file
#IMPORTING
from flask import Flask , render_template
from flask_script import Manager
from wtforms import StringField
import os
#Launching Server
app = Flask(__name__)
manager = Manager(app)
#Settings..!
PEOPLE_FOLDER = os.path.join('static', 'people_photo')
app.config['UPLOAD_FOLDER'] = PEOPLE_FOLDER
#Defining URL's And Rendering!
#app.route('/index')
def index():
full_filename = os.path.join(app.config['UPLOAD_FOLDER'], 'lkj.jpg')
return render_template("index.html", user_image = full_filename)
#app.route('/user/<name>')
def user(name):
return '<h1>Hey %s, Welcome to Flask</h1>' % name
#Deployment
if __name__ == '__main__':
manager.run()
#app.run(debug=True)
Okay so I wanted to pass the value from input field to python flask file where I have defined #app.route(/user/)
in the input field I asked someone's name he put the name and I wanted to take that name and put it in the user/ and display his name I can manually do that by writing the url myself like '192.168.29.10:5000/user/laxman' it would display 'Hey Laxman...etc' but I wanted that its done through the input field from that the parameters are passed and flask take that and display 'Hey Name...etc' so Can anyone help I only have two files and I have showed them already abobe SO anyone's help will be appreciated pls Thankyou
:)
If you want to ask anything ask I am gonna tell you! thankyou!
You can wrap your input into a form and submit it to the /user view.
<form action="/user">
<input type="text" id="username" name="username" maxlength="10"><br><br>
<button type="submit" name="button">Submit</button>
</form>
then in your view function
#app.route('/user')
def user():
who = request.args.get('username')
# Do something with who
return render_template("user.html", name=who)

Connect HTML page with Elasticsearch using Python flask

I am new to web development. I am trying to create a web page which will display index from elastic search database. I am using python flask for backend.
I see html page and python console shows index.
But I am not able to fetch index from HTML page.
I am not sure what could be the issue
Python code is as follows:
from flask import Flask,render_template, request
from elasticsearch import Elasticsearch
app = Flask(__name__)
es = Elasticsearch([{'host': 'localhost', 'port': 9200}])
doc1 = {"food": "Japanese", "spice_level": "moderate"}
doc2 = {"food": "Italian", "spice_level": "mild"}
doc3 = {"food": "Indian", "spice_level": "spicy"}
es.index(index="food", doc_type="spice_level", id=1, body=doc2)
resp = es.get(index="food", doc_type="spice_level", id=1)
print(resp)
#app.route('/')
def home():
return render_template('index.html')
app.route('/dashboard', methods=['GET', 'POST'])
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
HTML code is as follows:
<!DOCTYPE html>
<BODY bgcolor="cyan">
<form method="GET" action="/dashboard">
<center>
<H1>Database UI </H1> <br>
search here <input type = "text" name= "index" /> <br>
<input type = "submit">
</center>
</form>
</BODY>
</html>
Whenever I type a index name and click on search button, page gives me error as :
The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.
I cannot see any other error then this, and it's really difficult to debug with less information about error.
why your /dashboard return 404 ?
because lack of view function to response.
app.route('/dashboard', methods=['GET', 'POST']) is invalid.
How to access /dashboard of elascticsearch ?
In your case, the simplest way is modify the index.html
<!DOCTYPE html>
<BODY bgcolor="cyan">
<form method="POST" action="http://localhost:9200/dashboard">
<center>
<H1>Database UI </H1> <br>
search here <input type = "text" name= "index" /> <br>
<input type = "submit">
</center>
</form>
</BODY>
</html>
can you use this here? for Parse data from html to python code you need to have POST inside #app.route like this:
#app.route("/", methods=['GET', 'POST'])
def home():
return render_template('index.html')
if you want to pase data into index.html you can use this here:
somedata = "variable string"
render_template('index.html', somedata=somedata)
inside index.html do {{ somedata }}
<!DOCTYPE html>
<BODY bgcolor="cyan">
<form method="POST" action="">
<center>
<H1>Database UI </H1> <br>
<!-- it will show (variable string) -->
{{ somedata }}
search here <input type = "text" name= "index" /> <br>
<input type = "submit">
</center>
</form>
</BODY>
</html>
happy codeing.

Google app engine form not working

I'm having troubles with Google App Engine. It is all set up (and working hour before), when I reconnected the Engine the form simply stop working, when I hit submit, the page goes to the server's page and nothing happens.
<!DOCTYPE html>
<html lang="en">
<body>
<form action="http://localhost:9080/sub" method="post">
<input type="email" name="email" placeholder="Email"/>
<input type="submit" value="Subscribe"/>
</form>
</body>
</html>
import webapp2
class SubscribeHandler(webapp2.RequestHandler):
def post(self):
self.response.headers['Content-Type'] = 'text/plain'
email = self.request.get("email")
if email == '':
self.response.out.write("no email")
self.response.out.write(email)
app = webapp2.WSGIApplication([('/sub', SubscribeHandler)], debug=True)

Subclass of webapp.RequestHandler doesn't have a response attribute

Using the below code, my template loads fine until I submit the from, then I get the following error:
e = AttributeError("'ToDo' object has no attribute 'response'",)
Why doesn't my ToDo object not have a response attribute? It works the first time it's called.
import cgi
import os
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
from google.appengine.ext import db
class Task(db.Model):
description = db.StringProperty(required=True)
complete = db.BooleanProperty()
class ToDo(webapp.RequestHandler):
def get(self):
todo_query = Task.all()
todos = todo_query.fetch(10)
template_values = { 'todos': todos }
self.renderPage('index.html', template_values)
def renderPage(self, filename, values):
path = os.path.join(os.path.dirname(__file__), filename)
self.response.out.write(template.render(path, values))
class UpdateList(webapp.RequestHandler):
def post(self):
todo = ToDo()
todo.description = self.request.get('description')
todo.put()
self.redirect('/')
application = webapp.WSGIApplication(
[('/', ToDo),
('/add', UpdateList)],
debug=True)
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main()
Here's the template code so far, I'm just listing the descriptions for now.
<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
<html>
<head>
<title>ToDo tutorial</title>
</head>
<body>
<div>
{% for todo in todos %}
<em>{{ todo.description|escape }}</em>
{% endfor %}
</div>
<h3>Add item</h3>
<form action="/add" method="post">
<label for="description">Description:</label>
<input type="text" id="description" name="description" />
<input type="submit" value="Add Item" />
</form>
</body>
</html>
why do you do what you do in post? it should be:
def post(self):
task = Task() # not ToDo()
task.description = self.request.get('description')
task.put()
self.redirect('/')
put called on a subclass of webapp.RequestHandler will try to handle PUT request, according to docs.

Categories