I have created following model
class ConnectToFrom(models.Model):
person = models.ForeignKey(User, null=True)
kiosk = models.ForeignKey(Kiosks, null=True)
class Connect(models.Model):
parent_id = models.ForeignKey("self", null = True, blank = True)
sender = models.ForeignKey(ConnectToFrom, related_name='sent_messages' )
reciever = models.ForeignKey(ConnectToFrom, related_name='received_messages')
.
.
.
I am not able to access Connects to add any connect object through admin site !
Can i not reference same model to two fields ?
I am not able to figure out what exactly is causing the error .
Please help
Traceback :
Environment:
Request Method: GET
Request URL: http://www.example.com:8000/admin/connect/connect/
Django Version: 1.3
Python Version: 2.6.6
Installed Applications:
['broadcast',
'shastra',
'fb_api',
'log',
'nties',
'crc',
'connect',
'network',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.admin',
'kiosks',
'content',
'home',
'dashboard',
'trial',
'meta',
'oembed']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Traceback:
File "C:\Python26\lib\site-packages\django\core\handlers\base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "C:\Python26\lib\site-packages\django\contrib\admin\options.py" in wrapper
307. return self.admin_site.admin_view(view)(*args, **kwargs)
File "C:\Python26\lib\site-packages\django\utils\decorators.py" in _wrapped_view
93. response = view_func(request, *args, **kwargs)
File "C:\Python26\lib\site-packages\django\views\decorators\cache.py" in _wrapped_view_func
79. response = view_func(request, *args, **kwargs)
File "C:\Python26\lib\site-packages\django\contrib\admin\sites.py" in inner
197. return view(request, *args, **kwargs)
File "C:\Python26\lib\site-packages\django\utils\decorators.py" in _wrapper
28. return bound_func(*args, **kwargs)
File "C:\Python26\lib\site-packages\django\utils\decorators.py" in _wrapped_view
93. response = view_func(request, *args, **kwargs)
File "C:\Python26\lib\site-packages\django\utils\decorators.py" in bound_func
24. return func(self, *args2, **kwargs2)
File "C:\Python26\lib\site-packages\django\contrib\admin\options.py" in changelist_view
1159. 'selection_note': _('0 of %(cnt)s selected') % {'cnt': len(cl.result_list)},
File "C:\Python26\lib\site-packages\django\db\models\query.py" in __len__
82. self._result_cache = list(self.iterator())
File "C:\Python26\lib\site-packages\django\db\models\query.py" in iterator
273. for row in compiler.results_iter():
File "C:\Python26\lib\site-packages\django\db\models\sql\compiler.py" in results_iter
680. for rows in self.execute_sql(MULTI):
File "C:\Python26\lib\site-packages\django\db\models\sql\compiler.py" in execute_sql
735. cursor.execute(sql, params)
File "C:\Python26\lib\site-packages\django\db\backends\util.py" in execute
34. return self.cursor.execute(sql, params)
File "C:\Python26\lib\site-packages\django\db\backends\sqlite3\base.py" in execute
234. return Database.Cursor.execute(self, query, params)
Exception Type: DatabaseError at /admin/connect/connect/
Exception Value: no such column: connect_connect.reciever_id
Did you add the receiver field to your model after you initially created the connect_connect table? If so you'll have to manually add that field to your database (Django does not automatically sync changes to your models with your database.)
Just launch your interactive db shell, usually dbshell, and add the field. In MySQL it would be something like:
ALTER TABLE connect_connect ADD COLUMN receiver_id integer;
I'd recommend running manage.py sqlall appname to see how Django would create your db tables now, and then make sure the db matches that by making the necessary changes through your db shell.
Related
File "/layers/google.python.pip/pip/lib/python3.8/site-packages/django/core/handlers/exception.py", line 55, in inner
response = get_response(request)
File "/layers/google.python.pip/pip/lib/python3.8/site-packages/django/core/handlers/base.py", line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/layers/google.python.pip/pip/lib/python3.8/site-packages/django/views/generic/base.py", line 103, in view
return self.dispatch(request, *args, **kwargs)
File "/layers/google.python.pip/pip/lib/python3.8/site-packages/django/views/generic/base.py", line 142, in dispatch
return handler(request, *args, **kwargs)
File "/workspace/apps/account/views.py", line 235, in post
taskqueue.add(queue_name='create-waybill', url = reverse('_api:createWaybill') , params = {'key':url_key})
File "/layers/google.python.pip/pip/lib/python3.8/site-packages/google/appengine/api/taskqueue/taskqueue.py", line 575, in create_rpc
return apiproxy_stub_map.UserRPC('taskqueue', deadline, callback)
File "/layers/google.python.pip/pip/lib/python3.8/site-packages/google/appengine/api/apiproxy_stub_map.py", line 444, in __init__
self.__rpc = CreateRPC(service, stubmap)
File "/layers/google.python.pip/pip/lib/python3.8/site-packages/google/appengine/api/apiproxy_stub_map.py", line 69, in CreateRPC
assert stub, 'No api proxy found for service "%s"' % service
AssertionError: No api proxy found for service "taskqueue"
I am working on google app engine and try to run taskqueue and getting error
i am using django python3
from google.appengine.api import taskqueue
taskqueue.Task(name='create-waybill', url='/_api/createWaybill',params = {'key':url_key}).add()
just this one
and
path ('createWaybill', csrf_exempt(views.CreateWaybill.as_view()), name='createWaybill'),
To use the bundled services in Python 3, you first have to enable them.
See documentation from Google for doing that
This has been plaguing me for quite a while now. I've set up a basic set of apis in Django and am building an angularJS based front end. However for some weird reason the following code results in a CORS error.
var req = {
method: 'POST',
url: url,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
withCredentials: true,
param: data,
data: data
}
return $http(req).then(
function(response){
callbackSuccess(response);
},
function(response){
callbackError(response);
}
);
I found out two things that when I do a post an OPTIONS request is made and secondly none of what I post is even posted. I try to out put the request.POST contents and its empty.
Internal Server Error: /api/users/auth/
Traceback (most recent call last):
File "/home/ali/eb-virt/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 149, in get_response
response = self.process_exception_by_middleware(e, request)
File "/home/ali/eb-virt/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 147, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/ali/eb-virt/local/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
return view_func(*args, **kwargs)
File "/home/ali/eb-virt/local/lib/python2.7/site-packages/django/utils/decorators.py", line 149, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "/home/ali/Projects/api.project.local/project/api/views.py", line 50, in loginUser
emailAddress = request.POST["emailAddress"]
File "/home/ali/eb-virt/local/lib/python2.7/site-packages/django/utils/datastructures.py", line 85, in __getitem__
raise MultiValueDictKeyError(repr(key))
MultiValueDictKeyError: "'emailAddress'"
[21/Nov/2016 07:56:59] "OPTIONS /api/users/auth/ HTTP/1.1" 500 81083
And this is my server code:
def loginUser(request):
emailAddress = ''
password = ''
emailAddress = request.POST["emailAddress"]
password = request.POST["password"]
data = auth.login(emailAddress, password)
return data
I've installed the django-cors-headers and followed all the instructions to the core but its still not working...
The problem is in Line :
emailAddress = request.POST["emailAddress"]
In the place of this line,use this code:
def loginUser(request):
if request.method == 'POST':
emailAddress = request.POST.get('emailAddress')
password = request.POST.get('password')
data = auth.login(emailAddress, password)
return data
request.POST["emailAddress"] will raise a KeyError exception if 'emailAddress' is not in request.POST.
While request.POST.get('emailAddress') will return None if 'emailAddress' is not in request.POST.
OPTION request is doing by your browser for a safety whether it can send POST request(in case of cross domain). It should return a 200 with some headers(will take care of cors-headers middleware if you added it).
So In server, accept POST request this way(assume function based views).
if request.method == 'POST':
#access POST variables here.
Found the issue - was a total noob mistake.
My version of Django in my virtual environment was 1.9 whereas I had generated the project from a version 1.10 so in the settings the MIDDLEWARE option had to be named as MIDDLEWARE_CLASSES - silly mistake had me stuck for two days - thanks everyone for all your answers :)
I have used the getting started guide of app engine.But I am unable to use the datastore.
While running the simple code provided in the guide, i am getting "cannot access apps data" error.
my code :
import cgi
import datetime
import urllib
import webapp2
from google.appengine.ext import db
from google.appengine.api import users
MAIN_PAGE_FOOTER_TEMPLATE = """\
<form action="/sign?%s" method="post">
<div><textarea name="content" rows="3" cols="60"></textarea></div>
<div><input type="submit" value="Sign Guestbook"></div>
</form>
<hr>
<form>Guestbook name: <input value="%s" name="guestbook_name">
<input type="submit" value="switch"></form>
</body>
</html>
"""
class Greeting(db.Model):
"""Models an individual Guestbook entry with author, content, and date."""
author = db.StringProperty()
content = db.StringProperty(multiline=True)
date = db.DateTimeProperty(auto_now_add=True)
def guestbook_key(guestbook_name=None):
"""Constructs a Datastore key for a Guestbook entity with guestbook_name."""
return db.Key.from_path('Guestbook', guestbook_name or 'default_guestbook')
class MainPage(webapp2.RequestHandler):
def get(self):
self.response.write('<html><body>')
guestbook_name = self.request.get('guestbook_name')
# Ancestor Queries, as shown here, are strongly consistent with the High
# Replication Datastore. Queries that span entity groups are eventually
# consistent. If we omitted the ancestor from this query there would be
# a slight chance that Greeting that had just been written would not
# show up in a query.
greetings = db.GqlQuery("SELECT * "
"FROM Greeting "
"WHERE ANCESTOR IS :1 "
"ORDER BY date DESC LIMIT 10",
guestbook_key(guestbook_name))
for greeting in greetings:
if greeting.author:
self.response.write(
'<b>%s</b> wrote:' % greeting.author)
else:
self.response.write('An anonymous person wrote:')
self.response.write('<blockquote>%s</blockquote>' %
cgi.escape(greeting.content))
# Write the submission form and the footer of the page
sign_query_params = urllib.urlencode({'guestbook_name': guestbook_name})
self.response.write(MAIN_PAGE_FOOTER_TEMPLATE %
(sign_query_params, cgi.escape(guestbook_name)))
class Guestbook(webapp2.RequestHandler):
def post(self):
# We set the same parent key on the 'Greeting' to ensure each greeting
# is in the same entity group. Queries across the single entity group
# will be consistent. However, the write rate to a single entity group
# should be limited to ~1/second.
guestbook_name = self.request.get('guestbook_name')
greeting = Greeting(parent=guestbook_key(guestbook_name))
if users.get_current_user():
greeting.author = users.get_current_user().nickname()
greeting.content = self.request.get('content')
greeting.put()
query_params = {'guestbook_name': guestbook_name}
self.redirect('/?' + urllib.urlencode(query_params))
app = webapp2.WSGIApplication([('/', MainPage),
('/sign', Guestbook)],
debug=True)
I have uploaded the app on the server, but still getting the same error.
Traceback (most recent call last):
File "/home/laxman/google_appengine/lib/webapp2/webapp2.py", line 1535, in __call__
rv = self.handle_exception(request, response, e)
File "/home/laxman/google_appengine/lib/webapp2/webapp2.py", line 1529, in __call__
rv = self.router.dispatch(request, response)
File "/home/laxman/google_appengine/lib/webapp2/webapp2.py", line 1278, in default_dispatcher
return route.handler_adapter(request, response)
File "/home/laxman/google_appengine/lib/webapp2/webapp2.py", line 1102, in __call__
return handler.dispatch()
File "/home/laxman/google_appengine/lib/webapp2/webapp2.py", line 572, in dispatch
return self.handle_exception(e, self.app.debug)
File "/home/laxman/google_appengine/lib/webapp2/webapp2.py", line 570, in dispatch
return method(*args, **kwargs)
File "/home/laxman/helloworld/helloworld.py", line 51, in get
for greeting in greetings:
File "/home/laxman/google_appengine/google/appengine/ext/db/__init__.py", line 2326, in next
return self.__model_class.from_entity(self.__iterator.next())
File "/home/laxman/google_appengine/google/appengine/datastore/datastore_query.py", line 2892, in next
next_batch = self.__batcher.next()
File "/home/laxman/google_appengine/google/appengine/datastore/datastore_query.py", line 2754, in next
return self.next_batch(self.AT_LEAST_ONE)
File "/home/laxman/google_appengine/google/appengine/datastore/datastore_query.py", line 2791, in next_batch
batch = self.__next_batch.get_result()
File "/home/laxman/google_appengine/google/appengine/api/apiproxy_stub_map.py", line 604, in get_result
return self.__get_result_hook(self)
File "/home/laxman/google_appengine/google/appengine/datastore/datastore_query.py", line 2528, in __query_result_hook
self._batch_shared.conn.check_rpc_success(rpc)
File "/home/laxman/google_appengine/google/appengine/datastore/datastore_rpc.py", line 1224, in check_rpc_success
raise _ToDatastoreError(err)
BadRequestError: app "dev~helloworld" cannot access app "dev~hellolxmn"'s data
For the dev server the answer is in your the last line of your stacktrace.
app "dev~helloworld" cannot access app "dev~hellolxmn"'s data
You probably have an app.yaml which has changed it's appid, over time and you haven't
created a new datastore. You should show us you current app.yaml.
My guess is your error will be a little different in product, so show the trace for the error in production.
I copied and pasted your code and it seems to be working (I had to change formatting)
What is in your app.yaml? (I named my file aaa.py) this is what i used
application: somename
version: 1
runtime: python27
api_version: 1
threadsafe: true
handlers:
- url: /.*
script: aaa.app
I am using south, and I have syncdb but alas i get stuck with this database error, can you help me fix this and maybe tell me how to fix something like this in the future.
this missing database table error is comming up in a couple of different places dealing with something called salesflow_contact I have a folder salesflow with a models.py file with a class of Contact with a capitol,
the error shown is from trying to post some content to the table, but i also get an error with the pagination view browsecontacts
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/addacontact
Django Version: 1.4.2
Python Version: 2.7.3
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'django.contrib.admindocs',
'south',
'sekizai')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware')
Traceback:
File "/home/brian/virt_env/virt_step/local/lib/python2.7/site-packages/Django-1.4.2-py2.7.egg/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "/home/brian/projects/steprider/steprider/views.py" in Add_a_contact
36. new_contact = form.save(request.user)
File "/home/brian/projects/steprider/salesflow/forms.py" in save
23. contact.save()
File "/home/brian/virt_env/virt_step/local/lib/python2.7/site-packages/Django-1.4.2-py2.7.egg/django/db/models/base.py" in save
463. self.save_base(using=using, force_insert=force_insert, force_update=force_update)
File "/home/brian/virt_env/virt_step/local/lib/python2.7/site-packages/Django-1.4.2-py2.7.egg/django/db/models/base.py" in save_base
551. result = manager._insert([self], fields=fields, return_id=update_pk, using=using, raw=raw)
File "/home/brian/virt_env/virt_step/local/lib/python2.7/site-packages/Django-1.4.2-py2.7.egg/django/db/models/manager.py" in _insert
203. return insert_query(self.model, objs, fields, **kwargs)
File "/home/brian/virt_env/virt_step/local/lib/python2.7/site-packages/Django-1.4.2-py2.7.egg/django/db/models/query.py" in insert_query
1593. return query.get_compiler(using=using).execute_sql(return_id)
File "/home/brian/virt_env/virt_step/local/lib/python2.7/site-packages/Django-1.4.2-py2.7.egg/django/db/models/sql/compiler.py" in execute_sql
909. for sql, params in self.as_sql():
File "/home/brian/virt_env/virt_step/local/lib/python2.7/site-packages/Django-1.4.2-py2.7.egg/django/db/models/sql/compiler.py" in as_sql
872. for obj in self.query.objs
File "/home/brian/virt_env/virt_step/local/lib/python2.7/site-packages/django_extensions-0.9-py2.7.egg/django_extensions/db/fields/__init__.py" in pre_save
135. value = unicode(self.create_slug(model_instance, add))
File "/home/brian/virt_env/virt_step/local/lib/python2.7/site-packages/django_extensions-0.9-py2.7.egg/django_extensions/db/fields/__init__.py" in create_slug
122. while not slug or queryset.filter(**kwargs):
File "/home/brian/virt_env/virt_step/local/lib/python2.7/site-packages/Django-1.4.2-py2.7.egg/django/db/models/query.py" in __nonzero__
130. iter(self).next()
File "/home/brian/virt_env/virt_step/local/lib/python2.7/site-packages/Django-1.4.2-py2.7.egg/django/db/models/query.py" in _result_iter
118. self._fill_cache()
File "/home/brian/virt_env/virt_step/local/lib/python2.7/site-packages/Django-1.4.2-py2.7.egg/django/db/models/query.py" in _fill_cache
892. self._result_cache.append(self._iter.next())
File "/home/brian/virt_env/virt_step/local/lib/python2.7/site-packages/Django-1.4.2-py2.7.egg/django/db/models/query.py" in iterator
291. for row in compiler.results_iter():
File "/home/brian/virt_env/virt_step/local/lib/python2.7/site-packages/Django-1.4.2-py2.7.egg/django/db/models/sql/compiler.py" in results_iter
763. for rows in self.execute_sql(MULTI):
File "/home/brian/virt_env/virt_step/local/lib/python2.7/site-packages/Django-1.4.2-py2.7.egg/django/db/models/sql/compiler.py" in execute_sql
818. cursor.execute(sql, params)
File "/home/brian/virt_env/virt_step/local/lib/python2.7/site-packages/Django-1.4.2-py2.7.egg/django/db/backends/util.py" in execute
40. return self.cursor.execute(sql, params)
File "/home/brian/virt_env/virt_step/local/lib/python2.7/site-packages/Django-1.4.2-py2.7.egg/django/db/backends/sqlite3/base.py" in execute
344. return Database.Cursor.execute(self, query, params)
Exception Type: DatabaseError at /addacontact
Exception Value: no such table: salesflow_contact
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# steprider.salesflow.forms.py
#
# Copyright 2012 BRIAN SCOTT CARPENTER <KlanestroTalisman#gmail.com>
from django.forms import ModelForm
from salesflow import models
from django import forms
from django.template.defaultfilters import slugify
class ContactForm(ModelForm):
description = forms.CharField(widget=forms.Textarea)
class Meta:
model = models.Contact
exclude = ("user","slug")
def save(self, user):
contact = super(ContactForm, self).save(commit=False)
contact.user = user
contact.save()
return contact
class Contact_History_Form:
class Meta:
model = models.Contact_History
exclude = ("user","slug")
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# views.py
#
# Copyright 2012 BRIAN SCOTT CARPENTER <KlanestroTalisman#gmail.com>
from django.shortcuts import render_to_response,get_object_or_404
from django.template import RequestContext
from salesflow.forms import *
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from salesflow.models import Contact
def home (request):
""" This is the Home view"""
return render_to_response(('index.html') ,context_instance=RequestContext(request))
def server_error(request, template_name='templates/500.html'):
"""
500 error handler.
Templates: `500.html`
Context:
STATIC_URL
Path of static media (e.g. "media.example.org")
"""
t = loader.get_template(template_name)
return HttpResponseServerError(
t.render(Context({'STATIC_URL': settings.STATIC_URL})))
def Add_a_contact(request):
"""give them a page so they can donate and save it to a database."""
if request.method == 'POST':
form = ContactForm(request.POST,request.FILES)
if form.is_valid():
new_contact = form.save(request.user)
return HttpResponseRedirect(reverse(item, args=(new_contact.slug,)))
else:
form = ContactForm()
return render_to_response('salesflow/addacontact.html',{'form': form},context_instance=RequestContext(request))
def browse_contacts(request):
contact_list = Contact.objects.all()
paginator = Paginator(contact_list,15)
page = request.GET.get('page')
try:
contacts = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
contacts = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
contacts = paginator.page(paginator.num_pages)
return render_to_response('salesflow/browsecontacts.html',
{"contacts":contacts,
"site":settings.SITE_DOMAIN},
context_instance=RequestContext(request))
The error is pretty straight forward; you have no table called salesflow_contact.
You'd need to run migrate assuming it has the initial schemamigration salesflow --initial first table creation migration.
syncdb will not create tables for south-managed models, which is most likely your problem. You can bypass this with syncdb --all but if it's truly south-managed, you should run migrate salesflow and it should create the tables assuming you have the schemamigration salesflow --initial migration in there.
I try a simple HelloWorld with gdata, appengine and OAuth2. I read this post and the official post from Google.
Problem 1
According to the first post post, my app fails at the part 7 "Use the code to get an access token" :
Traceback (most recent call last):
File "[$PATH]/dev/outils/google_appengine/google/appengine/ext/webapp/_webapp25.py", line 701, in __call__
handler.get(*groups)
File "[$PATH]/dev/outils/google_appengine/google/appengine/ext/webapp/util.py", line 68, in check_login
handler_method(self, *args)
File "[$PATH]/dev/projets/xxx/main.py", line 76, in get
token.get_access_token(url.query)
File "[$PATH]/dev/projets/xxx/gdata/gauth.py", line 1296, in get_access_token
'redirect_uri': self.redirect_uri,
AttributeError: 'OAuth2Token' object has no attribute 'redirect_uri'
I provide the redirect_uri in the method generate_authorize_url() and i filled 2 "Redirect URIs" on Google APIs console :
http://localhost:8080/oauth2callback
http://example.com/oauth2callback
Why the redirect_uri is loosed ?
Solution : See #bossylobster answer.
Problem 2
Now, i want to save this new access token like this :
access_token_key = 'access_token_%s' % current_user.user_id()
gdata.gauth.ae_save(token, access_token_key)
Theses lines throw this exception :
Traceback (most recent call last):
File "[$PATH]/dev/outils/google_appengine/google/appengine/ext/webapp/_webapp25.py", line 701, in __call__
handler.get(*groups)
File "[$PATH]/dev/outils/google_appengine/google/appengine/ext/webapp/util.py", line 68, in check_login
handler_method(self, *args)
File "[$PATH]/dev/projets/xxx/main.py", line 89, in get
gdata.gauth.ae_save(token, access_token_key)
File "[$PATH]/dev/projets/xxx/gdata/gauth.py", line 1593, in ae_save
return gdata.alt.app_engine.set_token(key_name, token_to_blob(token))
File "[$PATH]/dev/projets/xxx/gdata/alt/app_engine.py", line 92, in set_token
if Token(key_name=unique_key, t=token_str).put():
File "[$PATH]/dev/outils/google_appengine/google/appengine/ext/db/__init__.py", line 973, in __init__
prop.__set__(self, value)
File "[$PATH]/dev/outils/google_appengine/google/appengine/ext/db/__init__.py", line 613, in __set__
value = self.validate(value)
File "[$PATH]/dev/outils/google_appengine/google/appengine/ext/db/__init__.py", line 2779, in validate
(self.name, self.data_type.__name__, err))
BadValueError: Property t must be convertible to a Blob instance (Blob() argument should be str instance, not unicode)
But gdata.gauth.access_token calls gdata.gauth.upgrade_to_access_token which return the token with some modification.
If i try with token_to_blob, i have this exception UnsupportedTokenType: Unable to serialize token of type <type 'unicode'>
** How save the new access Token ?**
main.py :
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app, login_required
from google.appengine.api import users
import gdata.gauth
import atom.http_core
SETTINGS = {
'APP_NAME': 'xxx',
'CLIENT_ID':'xxx.apps.googleusercontent.com',
'CLIENT_SECRET':'xxx',
'SCOPES': ['https://www.google.com/m8/feeds/', 'https://docs.google.com/feeds/', 'https://www.google.com/calendar/feeds/'],
'USER_AGENT' : 'xxxs',
'OAUTH2CALLBACK':'http://localhost:8080/oauth2callback'
#'OAUTH2CALLBACK':'http://example.com/oauth2callback'
}
class Home(webapp.RequestHandler):
def get(self):
"""Home"""
if users.get_current_user():
self.redirect("/step1")
else:
self.response.out.write("<a href='/step1'>Sign in google</a><br />")
class Fetcher(webapp.RequestHandler):
#login_required
def get(self):
"""This handler is responsible for fetching an initial OAuth
request token and redirecting the user to the approval page."""
current_user = users.get_current_user()
#create token
token = gdata.gauth.OAuth2Token(client_id = SETTINGS['CLIENT_ID'],
client_secret = SETTINGS['CLIENT_SECRET'],
scope = ' '.join(SETTINGS['SCOPES']),
user_agent = SETTINGS['USER_AGENT'])
url = token.generate_authorize_url(redirect_uri = SETTINGS['OAUTH2CALLBACK'])
#save token to datastore
gdata.gauth.ae_save(token, current_user.user_id())
message = """<a href="%s">
Request token for the Google Documents Scope</a>"""
self.response.out.write(message % url)
self.response.out.write(" ; redirect uri : %s" % token.redirect_uri)
class RequestTokenCallback(webapp.RequestHandler):
#login_required
def get(self):
"""When the user grants access, they are redirected back to this
handler where their authorized request token is exchanged for a
long-lived access token."""
current_user = users.get_current_user()
#get token from callback uri
url = atom.http_core.Uri.parse_uri(self.request.uri)
# get token from datastore
token = gdata.gauth.ae_load(current_user.user_id())
# SOLUTION 1
token.redirect_uri = SETTINGS['OAUTH2CALLBACK']
if isinstance(token, gdata.gauth.OAuth2Token):
if 'error' in url.query:
pass
else:
token.get_access_token(url.query)
gdata.gauth.ae_save(gdata.gauth.token_to_blob(token), "access_token_" + current_user.user_id())
def main():
application = webapp.WSGIApplication([('/', Home),
('/step1', Fetcher),
('/oauth2callback', RequestTokenCallback)],
debug = True)
run_wsgi_app(application)
if __name__ == '__main__':
main()
app.yaml :
application: xxx
version: 2
runtime: python
api_version: 1
handlers:
- url: .*
script: main.py
When you call AeLoad, you need to look at AeSave. You'll notice in the source code that token_to_blob is called.
However, in the source for token_to_blob, the redirect_uri is not saved to the blob, so you'll need to keep it around and call:
token = gdata.gauth.ae_load(current_user.user_id())
token.redirect_uri = SETTINGS['OAUTH2CALLBACK']
For reference, see another related post.
Answer to Question 2: Read the traceback: Blob() argument should be str instance, not unicode. Which version of Python are you using locally?