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(),)
Related
<!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 want to render an image from gridfs on my html pyge using flask.
I store the image in my mongodb using gridfs with one button and also store the ObjectId of the image in a serverside session using Flask-Session.
When I click on another button, I get the correct ObjectId of the image stored before via my session and then want to render this image from gridfs in my html page, but I don't know how to do it.
My app.py file:
from flask import Flask, render_template, request, redirect, session
from werkzeug.utils import secure_filename
from pymongo import MongoClient
from gridfs import GridFS
from flask_session import Session
DB = 'test-grid'
COLLECT = 'test-session'
client = MongoClient('mongodb://127.0.0.1:27017')
db = client[DB]
fs = GridFS(db)
app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 16*1024*1024
app.config['SESSION_TYPE'] = 'mongodb'
app.config['SESSION_MONGODB'] = client
app.config['SESSION_MONGODB_DB'] = DB
app.config['SESSION_MONGODB_COLLECT'] = COLLECT
Session(app)
#app.route("/")
def home():
return render_template("index.html")
#app.route('/upload', methods=['POST'])
def upload_file():
if request.method == 'POST':
f = request.files['file']
filename = secure_filename(f.filename)
f_id = fs.put(f, filename=filename)
session['f_id'] = f_id
session['filename'] = filename
return redirect('/')
#app.route('/display', methods=['GET'])
def display_file():
if request.method == 'GET':
f = fs.get(session['f_id'])
image = f.read()
return render_template("index.html", user_image=image)
if __name__ == "__main__":
app.run(debug=True)
My index.html file:
<html lang='en'>
<head>
<meta charset='UTF-8'/>
</head>
<body>
<form method="post" action="/upload" enctype="multipart/form-data">
<input type="file" onchange="this.form.submit()" name="file" autocomplete="off" required>
</form>
<form method="get" action="/display">
<input type="submit" value="Display">
</form>
<img src="{{ user_image }}" alt="Show image here"/>
</body>
</html>
My requirements.txt file:
Flask
Flask-Session
pymongo
But this doesn't work and I get the following output:
Output
Can someone please help me fix this? Maybe with examples I can look up.
I am new to web development. I have written the following python code to get input in a form and send it to '/testform'
import webapp2
form="""
<form action="/testform">
<input name="q">
<input type="submit">
</form>
"""
class MainHandler(webapp2.RequestHandler):
def get(self):
self.response.out.write(form)
class TestHandler(webapp2.RequestHandler):
def get(self):
q=self.request.get("q")
self.response.out.write(q)
app = webapp2.WSGIApplication([
('/', MainHandler),('/testform',TestHandler)
], debug=True)
But when I am opening the file in my browser, nothing is being displayed. Why is it so?
In my application, I have a form, and when I submit the entered data, the page should be redirected to another link, which has it's own handler.
Here's the python code for the same:
import os
import webapp2
import jinja2
from google.appengine.ext import db
import urllib2
import re
template_dir = os.path.join(os.path.dirname(__file__), 'templates')
jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir), autoescape=True)
class Handler(webapp2.RequestHandler):
def write(self, *a, **kw):
self.response.out.write(*a, **kw)
def render_str(self, template, **params):
t = jinja_env.get_template(template)
return t.render(params)
def render(self, template, **kw):
self.write(self.render_str(template, **kw))
class MainPage(Handler):
def get(self):
self.render("formrss.html")
def post(self):
x = self.request.get("rssquery")
if x:
self.redirect("/extract")
class ExtractFeeds(Handler):
def get(self):
self.write("ok")
app = webapp2.WSGIApplication([('/', MainPage),
('/extract', ExtractFeeds)], debug=True)
formrss.html
<html>
<head>
<title>Live Quora Feed</title>
</head>
<body>
<form>
Search:<input type = "text" name = "rssquery"><br>
<input type = "submit">
</form>
</body>
</html>
Now, when I submit the form data, instead of redirecting to the /extract link and displaying 'ok', the form page gets reloaded and the url is of the form '/?rssquery=(entered_data)'.
I can't seem to figure out what the problem could be here.
You are not using post on your form!
<form method="POST">
Search:<input type = "text" name = "rssquery"><br>
<input type = "submit">
</form>
This handler
def post(self):
x = self.request.get("rssquery")
if x:
self.redirect("/extract")
is bound to the post and with no post happening it was running the GET
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.