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.
Related
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">
<!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)
i'm trying to make a simple todo list using flask and a text file database, for now I'm trying to add items and save it in a text file, and also show the items online, but I'm not sure what I'm going wrong,this is the code i have for now
from flask import Flask, render_template, request, redirect, url_for
import todo_list
app = Flask(__name__)
#app.route('/')
def index():
with open('programming.pkl', 'rb') as output:
new_list = todo_list.pickle.load(output)
return render_template('index.html', todo1=new_list, todo=todo )
#app.route('/task', methods=['GET''POST'])
def task():
if request.method == 'POST':
todo = request.form.get('todo')
with open('programming.pkl', 'wb+') as output:
todo_list.pickle.dump(todo, output)
return redirect('/')
and this is my HTML code, i have just used google.com as a place holder for now
<!DOCTYPE html>
<html>
<head>
<h1> TODO APP</h1>
</head>
<body>
<p>
<br>
<h2>Here are your todo items</h2>
</p>
<br>
<h3>{{ todo }}</h3>
<h4>Mark as done</h4>
<br>
<h3>{{ todo }}</h3>
<h4>Mark as done</h4>
<br>
<h3>stuff1</h3>
<h4>Mark as done</h4>
<br>
<form action="/task" method="POST">
<h3>Create todo</h3>
<input type="text" id="todo" name="todo"><br><br>
</form>
</body>
</html>
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.
I am reading about the Blobstore in Google App Engine. The code below is from the sample documentation. After the user selects a file to upload and clicks Submit, how do I get the key into a javascript variable? I can show it on a page, but I only want to keep it for later use. Obviously, I am new to Web programming.
#!/usr/bin/env python
#
import os
import urllib
from google.appengine.ext import blobstore
from google.appengine.ext import webapp
from google.appengine.ext.webapp import blobstore_handlers
from google.appengine.ext.webapp.util import run_wsgi_app
class MainHandler(webapp.RequestHandler):
def get(self):
upload_url = blobstore.create_upload_url('/upload')
self.response.out.write('<html><body>')
self.response.out.write('<form action="%s" method="POST" enctype="multipart/form-data">' % upload_url)
self.response.out.write("""Upload File: <input type="file" name="file"><br> <input type="submit"
name="submit" value="Submit"> </form></body></html>""")
class UploadHandler(blobstore_handlers.BlobstoreUploadHandler):
def post(self):
upload_files = self.get_uploads('file') # 'file' is file upload field in the form
blob_info = upload_files[0]
self.response.out.write('<html><body>')
self.response.out.write(str(blob_info.key()))
self.response.out.write('</body><html>')
def main():
application = webapp.WSGIApplication(
[('/', MainHandler),
('/upload', UploadHandler),
], debug=True)
run_wsgi_app(application)
if __name__ == '__main__':
main()
You could do something like this:
self.response.out.write("""
<html>
<script>
var blobKey = "%s";
</script>
<body>
...
</body>
</html>""" % (blob_info.key(),)