GAE Simple Request Handler only run once - python

Good day!
https://developers.google.com/appengine/docs/python/gettingstarted/helloworld
this is the hello world that I'm trying to run.
I can seeing the
Hello, world!
Status: 500
message. however it will be turned to a "HTTP Error 500" after I hit the refresh.
and... it seems that the appengine only shows me the good result once after I re-save either app.yaml or helloworld.py
This is the trace for the good result
Traceback (most recent call last):
File "C:\Program Files\Google\google_appengine\google\appengine\runtime\wsgi.py", line 187, in Handle
handler = _config_handle.add_wsgi_middleware(self._LoadHandler())
File "C:\Program Files\Google\google_appengine\google\appengine\runtime\wsgi.py", line 239, in _LoadHandler
raise ImportError('%s has no attribute %s' % (handler, name))
ImportError: <module 'helloworld' from 'D:\work\[GAE] tests\helloworld\helloworld.pyc'> has no attribute app
INFO 2012-06-23 01:47:28,522 dev_appserver.py:2891] "GET /hello HTTP/1.1" 200 -
ERROR 2012-06-23 01:47:30,040 wsgi.py:189]
and this is the trace for the Error 500
Traceback (most recent call last):
File "C:\Program Files\Google\google_appengine\google\appengine\runtime\wsgi.py", line 187, in Handle
handler = _config_handle.add_wsgi_middleware(self._LoadHandler())
File "C:\Program Files\Google\google_appengine\google\appengine\runtime\wsgi.py", line 239, in _LoadHandler
raise ImportError('%s has no attribute %s' % (handler, name))
ImportError: <module 'helloworld' from 'D:\work\[GAE] tests\helloworld\helloworld.pyc'> has no attribute app
INFO 2012-06-23 01:47:30,127 dev_appserver.py:2891] "GET /hello HTTP/1.1" 500 -
here's my helloworld.py
print 'Content-Type: text/plain'
print ''
print 'Hello, world!'
my main.py. (app is used instead of application)
import webapp2
class hello(webapp2.RequestHandler):
def get(self):
self.response.out.write('normal hello')
app = webapp2.WSGIApplication([
('/', hello),
], debug = True)
and the app.yaml
application: helloworld
version: 1
runtime: python27
api_version: 1
threadsafe: true
handlers:
- url: /favicon\.ico
static_files: favicon.ico
upload: favicon\.ico
- url: /hello
script: helloworld.app
- url: /.*
script: main.app
libraries:
- name: webapp2
version: "2.5.1"
any clue what's causing this?
Regards,

You aren't creating a helloworld.app object in your helloworld.py module.
See the lines
app = webapp2.WSGIApplications([...
in your main.py file? That creates the main.app object that's referenced by the script: main.app handler in your app.yaml.
You're referencing a helloworld.app object a couple of lines above; that object doesn't exist. Python 2.7 in App Engine doesn't support the simple module model -- no WSGI handler, just a simple script -- that's used in the 2.5 "Hello World" demo.
As presveva said, use the 2.7 Getting Started guide for less confusion.

Related

python annoy library import error in GAE project

I am working on GAE using python jinja2 framework, while importing third party library "annoy" I am getting import error.
I am following the GAE Installing a third-party library method.
My project structure like
*projectfolder/
*lib/
*annoy/
main.py
app.yaml
appengine_config.py
Here is my main.py code
import os
import jinja2
from google.appengine.api import users
import webapp2
import csv
from jinja2 import Template
import ann_utils
JINJA_ENVIRONMENT = jinja2.Environment(
# TODO: to add other directories here that contains the templates.
loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
extensions=['jinja2.ext.autoescape'],
autoescape=True)
class Sent2Vec(webapp2.RequestHandler):
"""docstring for ."""
def get(self):
template = JINJA_ENVIRONMENT.get_template('sent2vec.html')
self.response.headers['Content-Type'] = 'text/html'
self.response.write(template.render()
ann_utils.py library
from annoy import AnnoyIndex
import random
f = 40
t = AnnoyIndex(f)
for i in xrange(1000):
v = [random.gauss(0, 1) for z in xrange(f)]
t.add_item(i, v)
t.build(10)
t.save('test.ann')
u = AnnoyIndex(f)
u.load('test.ann')
print(u.get_nns_by_item(0, 1000))
app.yaml
runtime: python27
threadsafe: ture
libraries:
- name: webapp2
version: latest
- name: jinja2
version: latest
- name: annoy
version: latest
handlers:
- url: /.*
script: main.app
appengine_config.py
from google.appengine.ext import vendor
vendor.add('lib')
Here is the tracetrack:
INFO 2017-01-24 08:33:27,378 devappserver2.py:769] Skipping SDK update check.
INFO 2017-01-24 08:33:27,435 api_server.py:205] Starting API server at: http://localhost:60106
INFO 2017-01-24 08:33:27,451 dispatcher.py:197] Starting module "default" running at: http://localhost:8080
INFO 2017-01-24 08:33:27,451 admin_server.py:116] Starting admin server at: http://localhost:8000
ERROR 2017-01-24 08:34:53,286 wsgi.py:263]
Traceback (most recent call last):
File "/home/affine/google-cloud-sdk/platform/google_appengine/google/appengine/runtime/wsgi.py", line 240, in Handle
handler = _config_handle.add_wsgi_middleware(self._LoadHandler())
File "/home/affine/google-cloud-sdk/platform/google_appengine/google/appengine/runtime/wsgi.py", line 299, in _LoadHandler
handler, path, err = LoadObject(self._handler)
File "/home/affine/google-cloud-sdk/platform/google_appengine/google/appengine/runtime/wsgi.py", line 85, in LoadObject
obj = __import__(path[0])
File "/home/affine/ML-Visualization/main.py", line 8, in <module>
from ann_utils import create_tree
File "/home/affine/ML-Visualization/ann_utils.py", line 1, in <module>
from annoy import AnnoyIndex
File "/home/affine/ML-Visualization/lib/annoy/__init__.py", line 15, in <module>
from annoylib import *
File "/home/affine/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/python/sandbox.py", line 963, in load_module
raise ImportError('No module named %s' % fullname)
ImportError: No module named annoy.annoylib
INFO 2017-01-24 08:34:53,290 module.py:788] default: "GET / HTTP/1.1" 500 -

Google AppEngine with Service Account but invalid Credentials

I have tried to get a group settings with group settings API using Google App Engine 1.7.5 with python 2.5 following a simple example here.
this is my app.yaml:
application: {{APP_ID}}
version: 1
runtime: python
api_version: 1
handlers:
- url: /.*
script: main.py
and my main.py is like following:
def main():
application = webapp.WSGIApplication([('/', TestHandler)])
run_wsgi_app(application)
class TestHandler(webapp.RequestHandler):
"""Handles a request for the query page."""
def get(self):
self.response.out.write(Test())
def Test():
credentials = AppAssertionCredentials(scope='https://www.googleapis.com/auth/apps.groups.settings')
http = credentials.authorize(httplib2.Http(memcache))
service = build('groupssettings', 'v1', http=http)
group = service.groups().get(groupUniqueId='{{GROUP_ID}}').execute()
logging.error(group)
if __name__=="__main__":
main()
and this is the stacktrace telling me invalid credentials!
Traceback (most recent call last):
File "C:\Program Files (x86)\Google\google_appengine\google\appengine\ext\webapp\_webapp25.py", line 714, in __call__
handler.get(*groups)
File "D:\Projets\GS\main.py", line 26, in get
self.response.out.write(Test())
File "D:\Projets\GS\main.py", line 41, in Test
group = service.groups().get(groupUniqueId='{{GROUP_ID}}').execute()
File "D:\Projets\GS\oauth2client\util.py", line 132, in positional_wrapper
return wrapped(*args, **kwargs)
File "D:\Projets\GS\apiclient\http.py", line 723, in execute
raise HttpError(resp, content, uri=self.uri)
HttpError: <HttpError 401 when requesting https://www.googleapis.com/groups/v1/groups/{{GROUP_ID}}?alt=json returned "Invalid Credentials">
INFO 2014-11-21 15:51:45,423 dev_appserver.py:3104] "GET / HTTP/1.1" 500 -
INFO 2014-11-21 15:51:45,611 dev_appserver.py:3104] "GET /favicon.ico HTTP/1.1" 404 -
Have anyone got this error before or have an idea of the root cause?
Have you turned on access to the groups API through the developer console for the project? This is a simple step that is often missed by people trying to get APIs going.
Also, I'd recommend using the decorator patterns for OAuth as described here to simplify the reasoning around authorization flows.
In addition, your app.yaml should specify python27 rather than just python. App Engine runs python27.

TemplateNotFound for 404 error page jinja2

I have a Google App Engine app with jinja2, when I force 404 error I have this error:
errors/default_error.html
Traceback (most recent call last):
File "/base/python27_runtime/python27_lib/versions/third_party/webapp2-2.5.1/webapp2.py", line 1536, in __call__
rv = self.handle_exception(request, response, e)
File "/base/python27_runtime/python27_lib/versions/third_party/webapp2-2.5.1/webapp2.py", line 1596, in handle_exception
return handler(request, response, e)
File "/base/data/home/apps/s~sandengine/latest.360189283466406656/main.py", line 28, in handle_404
t = jinja2.get_jinja2(app=app).render_template(template, **c)
File "/base/python27_runtime/python27_lib/versions/third_party/webapp2-2.5.1/webapp2_extras/jinja2.py", line 158, in render_template
return self.environment.get_template(_filename).render(**context)
File "/base/python27_runtime/python27_lib/versions/third_party/jinja2-2.6/jinja2/environment.py", line 719, in get_template
return self._load_template(name, self.make_globals(globals))
File "/base/python27_runtime/python27_lib/versions/third_party/jinja2-2.6/jinja2/environment.py", line 693, in _load_template
template = self.loader.load(self, name, globals)
File "/base/python27_runtime/python27_lib/versions/third_party/jinja2-2.6/jinja2/loaders.py", line 115, in load
source, filename, uptodate = self.get_source(environment, name)
File "/base/python27_runtime/python27_lib/versions/third_party/jinja2-2.6/jinja2/loaders.py", line 180, in get_source
raise TemplateNotFound(template)
TemplateNotFound: errors/default_error.html
Here my yaml file:
application: sandengine
version: latest
runtime: python27
api_version: 1
threadsafe: true
default_expiration: "30d"
skip_files:
- ^(.*/)?app\.yaml
- ^(.*/)?app\.yml
- ^(.*/)?index\.yaml
- ^(.*/)?index\.yml
- ^(.*/)?#.*#
- ^(.*/)?.*~
- ^(.*/)?.*\.py[co]
- ^(.*/)?.*/RCS/.*
- ^(.*/)?\..*
- ^(.*/)?tests$
- ^(.*/)?test$
- ^Makefile
- ^COPYING.LESSER
- ^README.rdoc
- \.gitignore
- ^\.git/.*
- \.*\.lint$
builtins:
- appstats: on #/_ah/stats/
- remote_api: on #/_ah/remote_api/
handlers:
- url: /favicon\.ico
mime_type: image/vnd.microsoft.icon
static_files: static/favicon.ico
upload: static/favicon.ico
- url: /apple-touch-icon\.png
static_files: static/apple-touch-icon.png
upload: static/apple-touch-icon.png
- url: /(robots\.txt|humans\.txt|crossdomain\.xml)
static_files: static/\1
upload: static/(robots\.txt|humans\.txt|crossdomain\.xml)
- url: /img/(.*\.(gif|png|jpg))
static_files: static/img/\1
upload: static/img/(.*\.(gif|png|jpg))
- url: /css
mime_type: text/css
static_dir: static/css
- url: /js
mime_type: text/javascript
static_dir: static/js
- url: /.*
script: main.app
libraries:
- name: jinja2
version: "2.6"
- name: webapp2
version: "2.5.1"
- name: markupsafe
version: "0.15"
error_handlers:
- file: templates/errors/default_error.html
- error_code: over_quota
file: templates/errors/over_quota.html
- error_code: dos_api_denial
file: templates/errors/dos_api_denial.html
- error_code: timeout
file: templates/errors/timeout.html
the code:
def handle_404(request, response, exception):
c = { 'exception': exception.status }
template = config.error_templates[404]
t = jinja2.get_jinja2(app=app).render_template(template, **c)
response.write(t)
response.set_status(exception.status_int)
app = webapp2.WSGIApplication(debug = os.environ['SERVER_SOFTWARE'].startswith('Dev'), config=config.webapp2_config)
app.error_handlers[404] = handle_404
routes.add_routes(app)
The config file:
error_templates = {
404: 'errors/default_error.html',
500: 'errors/default_error.html',
}
Here is the folder structure
Another important thing is that it works without problem in local machine (SDK), but the problem appear in production
You can explore the complete code, because this is an open source code
Thanks in advance for your help
I fixed it by removing the "default_error" on app.yaml
And the error handlers now only have:
error_handlers:
- error_code: over_quota
file: templates/errors/over_quota.html
- error_code: dos_api_denial
file: templates/errors/dos_api_denial.html
- error_code: timeout
file: templates/errors/timeout.html
I improved the code for control 404 errors, adding 500 error, with:
def handle_error(request, response, exception):
c = { 'exception': str(exception) }
status_int = hasattr(exception, 'status_int') and exception.status_int or 500
template = config.error_templates[status_int]
t = jinja2.get_jinja2(app=app).render_template(template, **c)
response.write(t)
response.set_status(status_int)
app = webapp2.WSGIApplication(debug = os.environ['SERVER_SOFTWARE'].startswith('Dev'), config=config.webapp2_config)
app.error_handlers[404] = handle_error
app.error_handlers[500] = handle_error

google app engine: upload throws "TemplateDoesNotExist: index.html" error

i have made an application using python and google app engine, the app works ok so far on localhost but when i deploy it using the google app engine launcher i get the following:
Traceback (most recent call last):
File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/webapp/_webapp25.py", line 701, in __call__
handler.get(*groups)
File "/base/data/home/apps/s~legacyexample01/1.357212630820400434/legacyexample.py", line 78, in get
self.response.out.write(template.render(path, template_values))
File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/webapp/template.py", line 91, in render
t = _load_user_django(template_path, debug)
File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/webapp/template.py", line 113, in _load_user_django
template = django.template.loader.get_template(file_name)
File "/base/python_runtime/python_lib/versions/third_party/django-0.96/django/template/loader.py", line 79, in get_template
source, origin = find_template_source(template_name)
File "/base/python_runtime/python_lib/versions/third_party/django-0.96/django/template/loader.py", line 72, in find_template_source
raise TemplateDoesNotExist, name
TemplateDoesNotExist: index.html
my code for rendering the pages is the following:
class MainPage(webapp.RequestHandler):
def get(self):
template_values = {}
path = os.path.join(os.path.dirname(__file__), "files/page/index.html")
self.response.out.write(template.render(path, template_values))
class RegisterPage(webapp.RequestHandler):
def get(self):
currentYear = datetime.datetime.now().year
firstYear = currentYear-100
template_values = {
"currentYear" : currentYear,
"firstYear" : firstYear,
}
path = os.path.join(os.path.dirname(__file__), "files/page/register.html")
self.response.out.write(template.render(path, template_values))
application = webapp.WSGIApplication( [('/', MainPage),('/registration', RegisterPage),('/sign',RegistrationProccess) ], debug=True)
i use django 1.3 and python 2.7 is that the cause of the problem ? please help
UPDATE
here is also my yaml configutration
application: legacyexample01
version: 1
runtime: python
api_version: 1
handlers:
- url: /files/image
static_dir: files/image
- url: /files/css
static_dir: files/css
- url: /files/javascript
static_dir: files/javascript
- url: /files/page
static_dir: files/page
- url: /.*
script: legacyexample.py
is the index.html template in files/page ?
edit:
remove
- url: /files/page
static_dir: files/page
this declaration from the yaml file.
you need the html template files accessible from the .py files and not as static files.

Python. Error with remote_api, google app engine [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
Following this guide:
http://code.google.com/appengine/articles/remote_api.html
I edited my app.yaml, updated the app, and tried to connect using api_remote. Then I got this error. Why?
c:\python25\python "C:\Program Files
\Google\google_appengine\remote_api_shell.py" -s medmcqs.appspot.com
Traceback (most recent call last):
File "C:\Program Files\Google\google_appengine\remote_api_shell.py", line 99,
in <module>
run_file(__file__, globals())
File "C:\Program Files\Google\google_appengine\remote_api_shell.py", line 95,
in run_file
execfile(script_path, globals_)
File "C:\Program Files\Google\google_appengine\google\appengine\tools\remote_a
pi_shell.py", line 140, in <module>
main(sys.argv)
File "C:\Program Files\Google\google_appengine\google\appengine\tools\remote_a
pi_shell.py", line 136, in main
appengine_rpc.HttpRpcServer)
File "C:\Program Files\Google\google_appengine\google\appengine\tools\remote_a
pi_shell.py", line 76, in remote_api_shell
rpc_server_factory=rpc_server_factory)
File "C:\Program Files\Google\google_appengine\google\appengine\ext\remote_api
\remote_api_stub.py", line 645, in ConfigureRemoteApi
app_id = GetRemoteAppIdFromServer(server, path, rtok)
File "C:\Program Files\Google\google_appengine\google\appengine\ext\remote_api
\remote_api_stub.py", line 501, in GetRemoteAppIdFromServer
'Invalid response recieved from server: %s' % response)
google.appengine.ext.remote_api.remote_api_stub.ConfigurationError: Invalid resp
onse recieved from server: <!DOCTYPE html PUBLIC "-//W3C//
This is what my app.yaml looks like...
application: medmcqs
version: 2
runtime: python
api_version: 1
inbound_services:
- mail
handlers:
- url: /static
static_dir: static
- url: /options
script: main.py
- url: /send
script: main.py
login: required
- url: /history
script: main.py
login: required
- url: /suggest
script: main.py
login: required
- url: .*
script: main.py
builtins:
- remote_api: on
UPDATE: Here are the log details:
2012-01-18 01:40:33.659 /_ah/remote_api?rtok=252529974978 200 48ms 1kb Google-remote_api/1.0 win32/6.1.7601.2 Python/2.5.4.final.0
109.224.29.101 - - [18/Jan/2012:01:40:33 -0800] "GET /_ah/remote_api?rtok=252529974978 HTTP/1.1" 200 1605 - "Google-remote_api/1.0 win32/6.1.7601.2 Python/2.5.4.final.0" "medmcqs.appspot.com" ms=49 cpu_ms=23 api_cpu_ms=0 cpm_usd=0.000855 instance=00c61b117cf891196f8b484d5951471ac52ac0
Some suggestions:
modify the .* handler
from :
-url: .*
script: main.py
To:
-url: /.*
script: main.py
Or: Maybe you can manually add the handler and try again to see if there are any differences.
- url: /_ah/remote_api
script: $PYTHON_LIB/google/appengine/ext/remote_api/handler.py
login: admin
EDIT1
There is another version of remote console code that you may want to try try. It is also from google app engine official website.
#remote_console.py
#!/usr/bin/python
import code
import getpass
import sys
sys.path.append(r"C:\Program Files\Google\google_appengine")
sys.path.append(r"C:\Program Files\Google\google_appengine\lib\yaml\lib")
sys.path.append(r"C:\Program Files\Google\google_appengine\lib\fancy_urllib")
from google.appengine.ext.remote_api import remote_api_stub
from google.appengine.ext import db
def auth_func():
return raw_input('Username:'), getpass.getpass('Password:')
if len(sys.argv) < 2:
print "Usage: %s app_id [host]" % (sys.argv[0],)
app_id = sys.argv[1]
if len(sys.argv) > 2:
host = sys.argv[2]
else:
host = '%s.appspot.com' % app_id
remote_api_stub.ConfigureRemoteDatastore(app_id, '/remote_api', auth_func, host)
code.interact('App Engine interactive console for %s' % (app_id,), None, locals())
Usage:
remote_console.py YOUR_APP_ID YOUR_APP_ID.appspot.com
or
remote_console.py s~YOUR_APP_ID YOUR_APP_ID.appspot.com
For some reason, some app id will begin with s~.

Categories