I'm new to Google App Engine and Django forms. I'm getting an encoding error when I try to run the follow code:
import webapp2
from google.appengine.ext import db
from google.appengine.ext.webapp import template
from django import newforms as forms
from google.appengine.ext.db import djangoforms
import os
import re
import fix_path
import config
import static
def slugify(s):
return re.sub('[^a-zA-Z0-9-]+', '-', s).strip('-')
def format_post_path(post, num):
slug = slugify(post.title)
if num > 0:
slug += "-" + str(num)
return config.post_path_format % {
'slug': slug,
'year': post.published.year,
'month': post.published.month,
'day': post.published.day,
}
def render_template(template_name, template_vals=None, theme=None):
template_path = os.path.join("themes", theme or config.theme, template_name)
return template.render(template_path, template_vals or {})
class BlogPost(db.Model):
# The url path to the blog post. Posts have a path if they are published.
path = db.StringProperty()
title = db.StringProperty(required=True, Indexed=False)
body = db.TextProperty(required=True)
published = db.DateTimeProperty(auto_now_add=True)
updated = db.DateTimeProperty(auto_now=True)
def render(self):
template_vals = {
'config': config,
'post': self,
}
return render_template("post.html", template_vals)
def publish(self):
rendered = self.render()
if not self.path:
num = 0
content = None
while not content:
path = format_post_path(self, num)
content = static.add(path, rendered, "text/html")
num += 1
self.path = path
self.put()
else:
static.set(self.path, rendered, "text/html")
class PostForm(djangoforms.ModelForm):
class Meta:
model = BlogPost
exclude = ['path', 'published', 'update']
class PostHandler(webapp2.RequestHandler)
def render_to_response(self, template_name, template_vals=None, theme=None):
template_name = os.path.join("admin", template_name)
self.response.out.write(render_template(template_name, template_vals, theme))
def render_form(self, form):
self.render_to_response("edit.html", {'form': form})
def get(self):
self.render_form(PostForm())
def post(self)
form = PostForm(date=self.request.POST)
if form.is_valid():
post = form.save(commit=False)
post.publish()
self.render_to_response("published.html", {'post': post})
else:
self.render_form(form)
app = webapp2.WSGIApplication([('/admin/newpost', PostHandler)],
debug=True)
Here is the traceback.
ERROR 2012-05-08 10:35:03,609 cgi.py:121] Traceback (most recent call last):
File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev_appserver_import_hook.py", line 676, in Decorate
return func(self, *args, **kwargs)
File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev_appserver_import_hook.py", line 1911, in get_code
source_code.decode(encoding)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 0: ordinal not in range(128)
INFO 2012-05-08 10:35:03,627 dev_appserver.py:2891] "GET /admin/newpost HTTP/1.1" 500 -
The traceback doesn't give me enough information to fix the problem. Any ideas?
When I had this problem with appengine I could clean all my data to unicode / utf-8 and then it worked.
Some of your data is not unicode / utf-8. I've had this problem on several occassions with GAE and it's always the data and not the source code that is not unicode in some way.
If you inspect your data and/or source formatting and set everything to utf-8 / unicode it will work. It might seem that you've already set everything to utf-8, but if you're still getting this error it means some string or the like is is some other charset than utf-8.
Related
I'm trying to do a multiple file upload functionality but I've been getting the issue: init() takes 1 positional argument but 2 were given
I was able to do it for uploading a single file or in my case an image.
model.py
from django.db import models
from django.utils import timezone
class images(models.Model):
session = models.CharField(max_length=50, blank=True)
picture = models.ImageField(upload_to='photoadmin/pictures')
created_date = models.DateTimeField(default=timezone.now)
forms.py
from django import forms
from django.db import models
from .models import images
class uploadImages(forms.ModelForm):
class Meta:
model = images
fields = ('session', 'picture')
widgets = {'picture': forms.ClearableFileInput(
attrs={'multiple': True})}
views.py
from django.http import HttpResponse
from django.shortcuts import render
from .forms import uploadImages
from django.views.generic.edit import FormView
def index(request):
return render(request, 'photoadmin/index.html')
class upload(FormView):
form_class = uploadImages
template_name = 'photoadmin/upload.html'
success_url = 'photoadmin/upload.html'
def post(self, request, *args, **kwargs):
form_class = self.get_form_class()
form = self.get_form(form_class)
files = uploadImages(request.POST, request.FILES)
if form.is_valid():
for f in files:
form.save()
return self.form_valid(form)
else:
return self.form_invalid(form)
Traceback
Environment:
Request Method: GET Request URL:
http://127.0.0.1:8000/photoadmin/upload
Django Version: 2.2.5 Python Version: 3.7.3 Installed Applications:
['django.contrib.admin', 'django.contrib.auth',
'django.contrib.contenttypes', 'django.contrib.sessions',
'django.contrib.messages', 'django.contrib.staticfiles',
'photoadmin.apps.PhotoadminConfig'] Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File
"C:.virtualenvs\BusinessPhotoManagementApp-wSA_cSYW\lib\site-packages\django\core\handlers\exception.py"
in inner
34. response = get_response(request)
File
"C:.virtualenvs\BusinessPhotoManagementApp-wSA_cSYW\lib\site-packages\django\core\handlers\base.py"
in _get_response
115. response = self.process_exception_by_middleware(e, request)
File
"C:\Users.virtualenvs\BusinessPhotoManagementApp-wSA_cSYW\lib\site-packages\django\core\handlers\base.py"
in _get_response
113. response = wrapped_callback(request, *callback_args, **callback_kwargs)
Exception Type: TypeError at /photoadmin/upload Exception Value:
init() takes 1 positional argument but 2 were given
Hi looks like the issue was the name of my Model was not following
PEP8, I changed images for Images, made the migrations and the error
disappeared.
I'm trying to make a simple app on GAE that allows a user to enter a url to an image and a name. The app then uploads this image to the Datastore along with its name.
After the upload the page self redirects and then should send the image back to the client and display it on their machine.
After running all I get is a Server error. Since I am new to GAE please could someone tell me if my code is at least correct.
I can't see what is wrong with my code. (I have checked for correct indentation and whitespace). Below is the code:
The python:
import jinja2 # html template libary
import os
jinja_environment = jinja2.Environment(
loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))
import urllib
import urllib2
import webapp2
from google.appengine.ext import db
from google.appengine.api import urlfetch
class Default_tiles(db.Model):
name = db.StringProperty()
image = db.BlobProperty(default=None)
class MainPage(webapp2.RequestHandler):
def get(self):
template = jinja_environment.get_template('index.html')
self.response.out.write(template.render())
class Upload(webapp2.RequestHandler):
def post(self):
# get information from form post upload
image_url = self.request.get('image_url')
image_name = self.request.get('image_name')
# create database entry for uploaded image
default_tile = Default_tiles()
default_tile.name = image_name
default_tile.image = db.Blob(urlfetch.Fetch(image_url).content)
default_tile.put()
self.redirect('/?' + urllib.urlencode({'image_name': image_name}))
class Get_default_tile(webapp.RequestHandler):
def get(self):
name = self.request.get('image_name')
default_tile = get_default_tile(name)
self.response.headers['Content-Type'] = "image/png"
self.response.out.write(default_tile.image)
def get_default_tile(name):
result = db.GqlQuery("SELECT * FROM Default_tiles WHERE name = :1 LIMIT 1", name).fetch(1)
if (len(result) > 0):
return result[0]
else:
return None
app = webapp2.WSGIApplication([('/', MainPage),
('/upload', Upload),
('/default_tile_img', Get_default_tile)],
debug=True)
The HTML:
<html>
<head>
<link type="text/css" rel="stylesheet" href="/stylesheets/main.css" />
</head>
<body>
<form action="/upload" method="post">
<div>
<p>Name: </p>
<input name="image_name">
</div>
<div>
<p>URL: </p>
<input name="image_url">
</div>
<div><input type="submit" value="Upload Image"></div>
</form>
<img src="default_tile_img?{{ image_name }}">
</body>
</html>
Any help at all will be so much appreciated. Thanks you!
UPDATE
Thanks to Greg, I know know how to view error logs. As Greg said I was missing a comma, I have updated the code above.
The app now runs, but when I upload an image, no image shows on return. I get the following message in the log:
File "/Users/jamiefearon/Desktop/Development/My Programs/GAE Fully functional website with css, javascript and images/mywebsite.py", line 53, in get
default_tile = self.get_default_tile(name)
TypeError: get_default_tile() takes exactly 1 argument (2 given)
I only passed one argument to get_default_tile() why does it complain that I passed two?
You're missing a comma after ('/upload', Upload) in the WSGIApplication setup.
use this python code
import jinja2 # html template libary
import os
jinja_environment = jinja2.Environment(
loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))
import urllib
import urllib2
import webapp2
from google.appengine.ext import db
from google.appengine.api import urlfetch
class Default_tiles(db.Model):
name = db.StringProperty()
image = db.BlobProperty(default=None)
class MainPage(webapp2.RequestHandler):
def get(self):
template = jinja_environment.get_template('index.html')
self.response.out.write(template.render())
class Upload(webapp2.RequestHandler):
def post(self):
# get information from form post upload
image_url = self.request.get('image_url')
image_name = self.request.get('image_name')
# create database entry for uploaded image
default_tile = Default_tiles()
default_tile.name = image_name
default_tile.image = db.Blob(urlfetch.Fetch(image_url).content)
default_tile.put()
self.redirect('/?' + urllib.urlencode({'image_name': image_name}))
class Get_default_tile(webapp2.RequestHandler):
def get_default_tile(self, name):
result = db.GqlQuery("SELECT * FROM Default_tiles WHERE name = :1 LIMIT 1", name).fetch(1)
if (len(result) > 0):
return result[0]
else:
return None
def get(self):
name = self.request.get('image_name')
default_tile = self.get_default_tile(name)
self.response.headers['Content-Type'] = "image/png"
self.response.out.write(default_tile)
app = webapp2.WSGIApplication([('/', MainPage),
('/upload', Upload),
('/default_tile_img', Get_default_tile)],
debug=True)
I'm trying to add chat to my site and am integrating some code with my existing code. The chat app works fine on its own when it's all set up in the original main.app file. But when I try to move that same code to a handlers.py file and then setup up routes in routes.py I get errors saying template variables are undefined. Are the two different codes conflicting in the way they render templates? They seem to be using webapp2 differently, i.e. my code renders templates like this:
self.render_template('secure_zone.html', **params)
And the chat app like this:
self.response.out.write(render("main.html",
username=username,
usernameerror=usernameerror,
channel=channelname,
channelerror=channelerror))
Are both acceptable?
Here's my handlers.py file:
Routes are setup in routes.py and added in main.py
"""
import httpagentparser
from boilerplate import models
from boilerplate.lib.basehandler import BaseHandler
from boilerplate.lib.basehandler import user_required
class SecureRequestHandler(BaseHandler):
"""
Only accessible to users that are logged in
"""
#user_required
def get(self, **kwargs):
user_session = self.user
user_session_object = self.auth.store.get_session(self.request)
user_info = models.User.get_by_id(long( self.user_id ))
user_info_object = self.auth.store.user_model.get_by_auth_token(
user_session['user_id'], user_session['token'])
try:
params = {
"user_session" : user_session,
"user_session_object" : user_session_object,
"user_info" : user_info,
"user_info_object" : user_info_object,
"userinfo_logout-url" : self.auth_config['logout_url'],
}
return self.render_template('secure_zone.html', **params)
except (AttributeError, KeyError), e:
return "Secure zone error:" + " %s." % e
Here's the main.py file for the chat app:
import os
import hashlib
import urllib
import logging
import re
import json
import webapp2
import jinja2
from google.appengine.api import channel as channel_api # 'channel' is kind of ambiguous in context
from google.appengine.ext import db
from google.appengine.api import memcache
# This section will eventually get moved to a Handler class
template_dir = os.path.join(
os.path.dirname(__file__), 'templates')
jinja_env = jinja2.Environment(
loader = jinja2.FileSystemLoader(template_dir),
autoescape = True)
def render_str(template, **params):
'''Returns a string of the rendered template'''
t = jinja_env.get_template(template)
return t.render(params)
def render(template, **kw):
'''Render using the template and parameters'''
return(render_str(template, **kw))
# End Handler
class Main(webapp2.RequestHandler):
def get(self):
'''Show connection page'''
return self.render_template("main.html", channel="#udacity")
def post(self):
'''Displays chat UI'''
username = self.request.get('username')
channelname = self.request.get('channel')
usernameerror = ""
if not username:
usernameerror="Please enter a username"
elif not re.compile(r'^[a-zA-Z0-9_-]{3,20}$').match(username):
usernameerror = "Username must consist of 3-20 alphanumeric characters."
elif get_user(username):
usernameerror="Username already in use"
channelerror = ""
if channelname and not re.compile(r'^#[\w]{3,20}$').match(channelname):
channelerror="Channel must consist of 3-20 alpha_numeric characters and start with a #"
if len(usernameerror+channelerror) > 0:
self.response.out.write(render("main.html",
username=username,
usernameerror=usernameerror,
channel=channelname,
channelerror=channelerror))
app = webapp2.WSGIApplication([
('/', Main),
('/communication', Communication),
('/_ah/channel/connected/?', Connect),
('/_ah/channel/disconnected/?', Disconnect)
], debug=True)
The specific error you posted in the comments "Error: 'Main' object has no attribute 'render_template'" is because in your Main handler, you try to return self.render_template. You should be just calling the function like this:
render_template("main.html", channel="#udacity")
Please note that I did not check the rest of your code, so if you run into any other issues, please post the specific errors you get.
It is because your webapp2.RequestHandler do not have the corresponding function "render_template"
you can use a BaseHandler with render_template function added to achieve the template rendering
from google.appengine.ext.webapp import template
class BaseHandler(webapp2.RequestHandler):
def render_template(self, filename, **template_args):
path = os.path.join(os.path.dirname(__file__), 'templates', filename)
self.response.write(template.render(path, template_args))
class Main(BaseHandler):
def get(self):
'''Show connection page'''
return self.render_template("main.html", channel="#udacity")
ref: http://blog.notdot.net/2011/11/Migrating-to-Python-2-7-part-2-Webapp-and-templates
I just started using webapp2 + python 2.7 + Jinja2 few days, and that is the same problem I encountered.
Hope this solution can help you ;)
I'm getting a TemplateNotFound error on Google App Engine with Jinja2 (complete stack trace below.)
What I expect to see is the index.html with the "greet" variable passed to the index.html template file. What I don't understand is why I get the template not found error when the path to index.html in the TraceBack is correct.
What I've tried...
tried a relative path by taking out "os.path.dirname(file)" in template path.
using "template" instead of themes as a directory name.
Here is my code.
app.yaml
application: codemywayout
version: 1
runtime: python27
api_version: 1
threadsafe: true
handlers:
- url: /admin/.*
script: admin.app
login: admin
- url: /static/([^/]+)/(.*)
static_files: template/\1/static/\2
upload: static/.*
- url: /favicon\.ico
static_files: favicon.ico
upload: favicon\.ico
- url: .*
script: static.app
builtins:
- remote_api: on
libraries:
- name: webapp2
version: "2.5.1"
- name: jinja2
version: latest
admin.py
from google.appengine.ext import db
import webapp2
import jinja2
import os
import fix_path
import config
def render_template(template_name, template_vals=None, theme=None):
template_path = os.path.join(os.path.dirname(__file__) , \
"themes", theme or config.theme, template_name)
env = jinja2.Environment(
loader=jinja2.FileSystemLoader(template_path))
return env.get_template(template_path, template_vals or {})
class BlogPost(db.Model):
title = db.StringProperty()
body = db.StringProperty()
def render(self):
template_vals = {
'config': config,
'post': self,
}
return render_template("post.html", template_vals)
class BaseHandler(webapp2.RequestHandler):
def render_to_response(self, template_name, \
template_vals=None, theme=None):
template_name = os.path.join("admin", template_name)
self.response.out.write(render_template(template_name,\
template_vals, theme))
class AdminHandler(BaseHandler):
def get(self):
greet = "hello"
template_vals = {
'greet': greet
}
self.render_to_response("index.html", template_vals)
config.py
# Name of the blog
blog_name = 'My Blog'
# Selects the theme to use. Theme names correspond to directories under
# the 'themes' directory, containing templates and static content.
theme = 'default'
# Defines the URL organization to use for blog postings. Valid substitutions:
# slug - the identifier for the post, derived from the title
# year - the year the post was published in
# month - the month the post was published in
# day - the day the post was published in
# URL Options
# post_path_format = '/%(year)d/%(month)02d/%(slug)s'
post_path_format = '/%(slug)s'
TraceBack
Traceback (most recent call last):
File "C:\Users\john\webdev\google\lib\webapp2\webapp2.py", line 1536, in __call__
rv = self.handle_exception(request, response, e)
File "C:\Users\john\webdev\google\lib\webapp2\webapp2.py", line 1530, in __call__
rv = self.router.dispatch(request, response)
File "C:\Users\john\webdev\google\lib\webapp2\webapp2.py", line 1278, in default_dispatcher
return route.handler_adapter(request, response)
File "C:\Users\john\webdev\google\lib\webapp2\webapp2.py", line 1102, in __call__
return handler.dispatch()
File "C:\Users\john\webdev\google\lib\webapp2\webapp2.py", line 572, in dispatch
return self.handle_exception(e, self.app.debug)
File "C:\Users\john\webdev\google\lib\webapp2\webapp2.py", line 570, in dispatch
return method(*args, **kwargs)
File "C:\Users\john\webdev\workspace\codemywayout\admin.py", line 49, in get
self.render_to_response("index.html", template_vals)
File "C:\Users\john\webdev\workspace\codemywayout\admin.py", line 34, in render_to_response
template_vals, theme))
File "C:\Users\john\webdev\workspace\codemywayout\admin.py", line 14, in render_template
return env.get_template(template_path, template_vals or {})
File "C:\Users\john\webdev\google\lib\jinja2\jinja2\environment.py", line 719, in get_template
return self._load_template(name, self.make_globals(globals))
File "C:\Users\john\webdev\google\lib\jinja2\jinja2\environment.py", line 693, in _load_template
template = self.loader.load(self, name, globals)
File "C:\Users\john\webdev\google\lib\jinja2\jinja2\loaders.py", line 115, in load
source, filename, uptodate = self.get_source(environment, name)
File "C:\Users\john\webdev\google\lib\jinja2\jinja2\loaders.py", line 162, in get_source
pieces = split_template_path(template)
File "C:\Users\john\webdev\google\lib\jinja2\jinja2\loaders.py", line 33, in split_template_path
raise TemplateNotFound(template)
TemplateNotFound: C:\Users\john\webdev\workspace\codemywayout\themes\default\admin\index.html
I hope your not trying to load the Jinja template from the same path as your static files
static_files: template/\1/static/\2
As that path is not accessible to your application.
I would try and log the path that Jinja is trying to load the template from to help you understand where it is trying to load the template.
If you look at C:\Users\john\webdev\google\lib\jinja2\jinja2\loaders.py line 33 you can probably set a pdb breakpoint import pdb; pdb.set_trace( ) and see what's going on.
I'm using the SDK source distribution on a Mac, but if your code is the same as what I see, it's:
def split_template_path(template):
"""Split a path into segments and perform a sanity check. If it detects
'..' in the path it will raise a `TemplateNotFound` error.
"""
pieces = []
for piece in template.split('/'):
if path.sep in piece \
or (path.altsep and path.altsep in piece) or \
piece == path.pardir:
raise TemplateNotFound(template)
elif piece and piece != '.':
pieces.append(piece)
return pieces
Note the for piece in template.split('/') where it splits on '/' instead of path.sep. I suspect that your input is a C:\Path\to\file.html in which case piece is the entire path, adn path.sep (\ on windows) is indeed in piece, which gives a TemplateNotFound error.
Instead of template_name = os.path.join("admin", template_name) you could try template_name = 'admin/%s' % template_name, don't include template_name in the template_path and pass template_name instead of template_path into env.get_template(template_name, template_vals or {}) as loaders.py line 162 indicates that it looks for template_name in template_path
Your code, modified but untested would look something like
from google.appengine.ext import db
import webapp2
import jinja2
import os
import fix_path
import config
def render_template(template_name, template_vals=None, theme=None):
template_path = os.path.join(os.path.dirname(__file__) , \
"themes", theme or config.theme)
env = jinja2.Environment(
loader=jinja2.FileSystemLoader(template_path))
return env.get_template(template_name, template_vals or {})
class BlogPost(db.Model):
title = db.StringProperty()
body = db.StringProperty()
def render(self):
template_vals = {
'config': config,
'post': self,
}
return render_template("post.html", template_vals)
class BaseHandler(webapp2.RequestHandler):
def render_to_response(self, template_name, \
template_vals=None, theme=None):
template_name = "admin/%s" % template_name
self.response.out.write(render_template(template_name,\
template_vals, theme))
class AdminHandler(BaseHandler):
def get(self):
greet = "hello"
template_vals = {
'greet': greet
}
self.render_to_response("index.html", template_vals)
i'm working on a task that i want to convert text file into PDF one using conversion API that is in GAE , i tried as: https://developers.google.com/appengine/docs/python/conversion/overview
This is the code that i used:
from __future__ import with_statement
from google.appengine.api import files
import cgi, cgitb ; cgitb.enable()
import StringIO
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
import mimetypes
from google.appengine.ext import blobstore
from mimetypes import guess_type
from google.appengine.api import conversion
def mime_type(filename):
return guess_type(filename)[0]
class get(webapp.RequestHandler):
def post(self):
form = cgi.FieldStorage()
file_upload = form['file']
name=file_upload.filename
m=mimetypes.guess_type(name)[0]
data=file_upload.file.read()
buf = StringIO.StringIO()
asset = conversion.Asset("text/plain", data, file_upload.filename)
conversion_obj = conversion.ConversionRequest(asset, "application/pdf")
result = conversion.convert(conversion_obj)
if result.assets:
for asset in result.assets:
buf.write(asset.data)
else:
print "ERROR"
u_file = files.blobstore.create(mime_type="application/pdf",_blobinfo_uploaded_filename="test.pdf")
data=buf.getvalue()
with files.open(u_file, 'a') as f:
f.write(data)
files.finalize(u_file)
blob_key = files.blobstore.get_blob_key(u_file)
blob_info = blobstore.get(blob_key)
name2 = blob_info.filename
self.response.out.write("""<html><br><body style="background-color:#CC9999"><b><font size="5" face="Batang" ><center> <li ><a href="download.py?blob_key=%s" style="color:black">%s
</center></font><hr></body></html>
""" % (str(blob_key),str(name2)))
def main():
application = webapp.WSGIApplication( [(r'/get.py', get)], debug=True)
run_wsgi_app(application)
if __name__ == "__main__":
main()
download.py:
from __future__ import with_statement
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
from mimetypes import guess_type
def mime_type(filename):
return guess_type(filename)[0]
class Thumbnailer(blobstore_handlers.BlobstoreDownloadHandler):
def get(self):
blob_key = self.request.get("blob_key")
if blob_key:
blob_info = blobstore.get(blob_key)
if blob_info:
save_as1 = blob_info.filename
type2=mime_type(blob_info.filename)
self.send_blob(blob_info,content_type=type2,save_as=save_as1)
return
def main():
application = webapp.WSGIApplication([
(r'/download.*', Thumbnailer),
], debug=True)
run_wsgi_app(application)
if __name__ == '__main__':
main()
EDIT:i edited the code, and when i try to print buf.getvalue(),i get :failed to load pdf document.
But when i try to open this PDF,i can't open it and the adobe reader gives error immediately that it can't open the file. Sorry i'm still beginner,any help please? Any suggestions are welcome.
Here is my working code sample(it's for Python2.7 runtime though). Good luck!
import os
import StringIO
from google.appengine.api import conversion
from google.appengine.api import files
from google.appengine.ext import blobstore
from google.appengine.ext import webapp
from google.appengine.ext.webapp import blobstore_handlers
import jinja2
template_dir = os.path.join(os.path.dirname(__file__), 'templates')
jinja2_env = jinja2.Environment(
loader=jinja2.FileSystemLoader(template_dir))
class MainHandler(webapp.RequestHandler):
def get(self):
tmpl = jinja2_env.get_template('index.jinja2')
self.response.out.write(tmpl.render())
class PostHandler(blobstore_handlers.BlobstoreDownloadHandler):
def post(self):
data = self.request.get('file')
asset = conversion.Asset('text/plain', data, 'test.txt')
conversion_obj = conversion.Conversion(asset, 'application/pdf')
result = conversion.convert(conversion_obj)
buf = StringIO.StringIO()
if result.assets:
for asset in result.assets:
buf.write(asset.data)
else:
raise Exception('Conversion failed.')
u_file = files.blobstore.create(mime_type='application/pdf',
_blobinfo_uploaded_filename='test.pdf')
with files.open(u_file, 'a') as f:
f.write(buf.getvalue())
files.finalize(u_file)
blob_key = files.blobstore.get_blob_key(u_file)
blob_info = blobstore.get(blob_key)
self.send_blob(blob_info)
app = webapp.WSGIApplication([
('/', MainHandler),
('/post_file', PostHandler),
],
debug=True)
Are you sure that your 'data' (retrieved by data=file_upload.file.read()) is correct?
Maybe you can stop using cgi module, and just use a request object that webapp creates for you like:
data = self.request.get('file')
BTW, please don't use private attributes like asset._data, use asset.data instead. Additionally, what the StringIO is for? Have you considered just writing asset.data directly to the opened file?
Update: I think I find the cause.
Just after the conversion, please do as follows:
if result.assets:
for asset in result.assets
buf.write(asset.data)