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
Related
Currently we use Docker Compose to start up services but we need secrets to secure passwords and the like, therefore the use of Docker Swarm & secrets is required.
Everything works perfectly with Compose but when we switch to Swarm a templating issue appears when loading the UI.
docker-compose.yml stripped down for simplicity
version: '3.7'
services:
postgresql:
image: docker.io/bitnami/postgresql:12.11.0
volumes:
- 'postgresql_data:/bitnami/postgresql'
environment:
#- ALLOW_EMPTY_PASSWORD=yes
- POSTGRESQL_USERNAME=user
- POSTGRESQL_DATABASE=user
- POSTGRESQL_PASSWORD_FILE=/path/to/docker/secret
secrets:
- secret
keycloak:
image: docker.io/bitnami/keycloak:16.1.1
depends_on:
- postgresql
environment:
- KEYCLOAK_ADMIN_USER=user
- KEYCLOAK_ADMIN_PASSWORD_FILE=/path/to/docker/secret
- KEYCLOAK_DATABASE_PORT=5432
- KEYCLOAK_DATABASE_HOST=postgresql
- KEYCLOAK_DATABASE_NAME=user
- KEYCLOAK_DATABASE_USER=user
- KEYCLOAK_DATABASE_PASSWORD_FILE=/path/to/docker/secret
- KEYCLOAK_HTTP_PORT=8083
- KEYCLOAK_HTTPS_PORT=8443
- KEYCLOAK_ENABLE_TLS=true
- KEYCLOAK_TLS_KEYSTORE_FILE=/path/to/keystore.jks
- KEYCLOAK_TLS_KEYSTORE_PASSWORD_FILE=/path/to/docker/secret
- KEYCLOAK_TLS_TRUSTSTORE_FILE=/path/to/truststore.jks
- KEYCLOAK_TLS_TRUSTSTORE_PASSWORD_FILE=/path/to/docker/secret
volumes:
- ".path/to/keycloak.jks:/opt/bitnami/keycloak/certs/keystore.jks"
- ".path/to/keycloak.jks:/opt/bitnami/keycloak/certs/truststore.jks"
networks:
default:
aliases:
- keycloak.host.net
ports:
- 8083:8083
- 8443:8443
secrets:
- secret
ui:
image: <image from AWS ECR>
labels:
COMPOSE_PATH: ${PWD}
depends_on:
- keycloak
ports:
- 8000:8000
restart: always
environment:
- HOSTNAME=ui
- NAME=UI
- PORT=8000
- REGISTER_WITH_KEYCLOAK=True
- ENVIRONMENT=prod
- CONSUL_URL=http://consul-server-bootstrap:8500
- MONGO_URI=mongodb://user:password#mongodb:27017/db
- QUEUE_HOSTNAME=queue
UI code from config.py
# Landing page
#app.route("/")
def index():
try:
current_app.logger.info(f"public/index.html page being displayed")
return Response(render_template("public/index.html"), mimetype="text/html")
except exception_with_data as ex:
return ex.repr_as_dict(), 400
The error
2022-07-26T08:21:03.252452 Thread-83 UI app ERROR Exception on / [GET]
Traceback (most recent call last):
File "/usr/local/lib/python3.9/site-packages/flask/app.py", line 2070, in wsgi_app
response = self.full_dispatch_request()
File "/usr/local/lib/python3.9/site-packages/flask/app.py", line 1515, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/local/lib/python3.9/site-packages/flask/app.py", line 1513, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/local/lib/python3.9/site-packages/flask/app.py", line 1499, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
File "/usr/local/lib/python3.9/site-packages/ui/main/config.py", line 209, in index
return Response(render_template("public/index.html"), mimetype="text/html")
File "/usr/local/lib/python3.9/site-packages/flask/templating.py", line 148, in render_template
ctx.app.jinja_env.get_or_select_template(template_name_or_list),
File "/usr/local/lib/python3.9/site-packages/jinja2/environment.py", line 1068, in get_or_select_template
return self.get_template(template_name_or_list, parent, globals)
File "/usr/local/lib/python3.9/site-packages/jinja2/environment.py", line 997, in get_template
return self._load_template(name, globals)
File "/usr/local/lib/python3.9/site-packages/jinja2/environment.py", line 958, in _load_template
template = self.loader.load(self, name, self.make_globals(globals))
File "/usr/local/lib/python3.9/site-packages/jinja2/loaders.py", line 125, in load
source, filename, uptodate = self.get_source(environment, name)
File "/usr/local/lib/python3.9/site-packages/flask/templating.py", line 59, in get_source
return self._get_source_fast(environment, template)
File "/usr/local/lib/python3.9/site-packages/flask/templating.py", line 95, in _get_source_fast
raise TemplateNotFound(template)
jinja2.exceptions.TemplateNotFound: public/index.html
Code tree
ui
/main
app.py
config.py
/templates
/admin
<all admin html pages>
/public
index.html
<all other public html pages>
All the files are in the correct location in the docker container.
The only difference between the yml files is the one for swarm has secrets.
docker-compose up -d works as expected and the UI pages render but when
docker stack deploy -c docker-compose-swarm.yml name is ran, the UI pages do not render.
The pages that do not use render_template (debugging pages) work fine and the UI registers with consul as expected.
Any help is appreciated!
Versions:
Flask==2.0.1
Werkzeug==2.0.1
Jinja2==3.0.1
itsdangerous==2.0.1
I am learning Flask and am attempting to work through the uploading files.
I get the following [Errno 2] No such file or directory with flask.
see
How can I tell Flask to look in the right place?
See my app.html
from flask import render_template, jsonify, Flask, redirect, url_for, request
from app import app
import random
import os
from keras.applications.resnet50 import ResNet50
from keras.preprocessing import image
from keras.applications.resnet50 import preprocess_input, decode_predictions
import numpy as np
#app.route('/')
#app.route('/index')
def index():
return render_template('index.html', title='Home')
#app.route('/upload.php', methods = ['GET', 'POST'])
def upload():
if request.method == 'POST':
f = request.files['file']
model= ResNet50(weights='imagenet')
img = image.load_img(f.filename)
preds = model.predict(img)
return render_template('uploaded.html', predictions=preds_decoded)
#app.route('/map')
def map():
return render_template('map.html', title='Map')
#app.route('/map/refresh', methods=['POST'])
def map_refresh():
points = [(random.uniform(48.8434100, 48.8634100),
random.uniform(2.3388000, 2.3588000))
for _ in range(random.randint(2, 9))]
return jsonify({'points': points})
#app.route('/contact')
def contact():
return render_template('contact.html', title='Contact')
I defined my UPLOADED_FOLDER in my config.py
/Users/name/Desktop/flaskSaaS-master/app/forms
my config.py
import logging
from app.config_common import *
from flask import Flask
from flask_debugtoolbar import DebugToolbarExtension
app = Flask(__name__)
# the toolbar is only enabled in debug mode:
app.debug = True
# set a 'SECRET_KEY' to enable the Flask session cookies app.config['SECRET_KEY'] = 'houdini' app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = False toolbar = DebugToolbarExtension(app)
# DEBUG can only be set to True in a development environment for security reasons DEBUG = True
# Secret key for generating tokens SECRET_KEY = 'houdini'
# Admin credentials ADMIN_CREDENTIALS = ('admin', 'pa$$word')
# Database choice SQLALCHEMY_DATABASE_URI = 'sqlite:///app.db' SQLALCHEMY_TRACK_MODIFICATIONS = True
# Configuration of a Gmail account for sending mails MAIL_SERVER = 'smtp.googlemail.com' MAIL_PORT = 465 MAIL_USE_TLS = False MAIL_USE_SSL = True MAIL_USERNAME = 'flask.boilerplate' MAIL_PASSWORD
= 'flaskboilerplate123' ADMINS = ['flask.boilerplate#gmail.com']
# Number of times a password is hashed BCRYPT_LOG_ROUNDS = 12
LOG_LEVEL = logging.DEBUG LOG_FILENAME = 'activity.log' LOG_MAXBYTES = 1024 LOG_BACKUPS = 2
UPLOAD_FOLDER = '/Users/name/Desktop/flaskSaaS-master/app/forms'
Debug:
* Debugger is active!
* Debugger PIN: 127-013-508
127.0.0.1 - - [29/Sep/2019 20:48:36] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [29/Sep/2019 20:48:36] "GET /_debug_toolbar/static/css/toolbar.css?0.5076085944288159 HTTP/1.1" 200 -
127.0.0.1 - - [29/Sep/2019 20:49:04] "POST /upload.php HTTP/1.1" 500 -
Traceback (most recent call last):
File "/anaconda3/envs/tensorflow/lib/python3.6/site-packages/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "/anaconda3/envs/tensorflow/lib/python3.6/site-packages/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/anaconda3/envs/tensorflow/lib/python3.6/site-packages/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "/anaconda3/envs/tensorflow/lib/python3.6/site-packages/flask/_compat.py", line 33, in reraise
raise value
File "/anaconda3/envs/tensorflow/lib/python3.6/site-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/anaconda3/envs/tensorflow/lib/python3.6/site-packages/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/anaconda3/envs/tensorflow/lib/python3.6/site-packages/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/anaconda3/envs/tensorflow/lib/python3.6/site-packages/flask/_compat.py", line 33, in reraise
raise value
File "/anaconda3/envs/tensorflow/lib/python3.6/site-packages/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "/anaconda3/envs/tensorflow/lib/python3.6/site-packages/flask_debugtoolbar/__init__.py", line 125, in dispatch_request
return view_func(**req.view_args)
File "/anaconda3/envs/tensorflow/lib/python3.6/cProfile.py", line 109, in runcall
return func(*args, **kw)
File "/Users/lorenzocastagno/Desktop/flaskSaaS-master/app/views/main.py", line 27, in upload
img = image.load_img(f.filename)
File "/anaconda3/envs/tensorflow/lib/python3.6/site-packages/keras_preprocessing/image/utils.py", line 110, in load_img
img = pil_image.open(path)
File "/anaconda3/envs/tensorflow/lib/python3.6/site-packages/PIL/Image.py", line 2770, in open
fp = builtins.open(filename, "rb")
FileNotFoundError: [Errno 2] No such file or directory: 'mmm.jpg'
127.0.0.1 - - [29/Sep/2019 20:49:04] "GET /upload.php?__debugger__=yes&cmd=resource&f=style.css HTTP/1.1" 200 -
127.0.0.1 - - [29/Sep/2019 20:49:04] "GET /upload.php?__debugger__=yes&cmd=resource&f=jquery.js HTTP/1.1" 200 -
127.0.0.1 - - [29/Sep/2019 20:49:04] "GET /upload.php?__debugger__=yes&cmd=resource&f=debugger.js HTTP/1.1" 200 -
127.0.0.1 - - [29/Sep/2019 20:49:04] "GET /upload.php?__debugger__=yes&cmd=resource&f=console.png HTTP/1.1" 200 -
127.0.0.1 - - [29/Sep/2019 20:49:04] "GET /upload.php?__debugger__=yes&cmd=resource&f=ubuntu.ttf HTTP/1.1" 200 -
The issue is with img = image.load_img(f.filename)
The load_img will try to read the file from the server. But in your case the file is not present in the file system of the server and is available in the request.files
In order to solve this, first you need to write the file present in request.files to some location and then use that location to load the file
I set up a most basic structure of an API in python wit the stack
flask - connexion - flaskInjector
according to the code shown below. When the API is run and FlaskInjector is initialized, it fails with the error message:
injector.CallError: Call to RequestScope.init() failed: init() missing 1 required positional argument: 'injector' (injection stack: [])
My system is Ubuntu 18.04, packages in the conda environment as follows:
Relevant excerpt from conda list:
# Name Version Build Channel
...
connexion 2.2.0 pypi_0 pypi
...
elasticsearch 7.0.1 pypi_0 pypi
fastavro 0.21.23 pypi_0 pypi
flask 1.0.2 pypi_0 pypi
flask-cors 3.0.7 pypi_0 pypi
flask-injector 0.12.0 pypi_0 pypi
flask-opentracing 1.0.0 pypi_0 pypi
flask-restplus 0.9.2 pypi_0 pypi
flask-script 2.0.6 pypi_0 pypi
flask-sqlalchemy 2.3.2 pypi_0 pypi
...
injector 0.12.0 pypi_0 pypi
...
swagger-ui-bundle 0.0.3 pypi_0 pypi
...
The project is organized as follows:
./app.py:
from injector import Binder
from flask_injector import FlaskInjector
from connexion.resolver import RestyResolver
import connexion
from providers.provider import ItemsProvider
def configure(binder: Binder) -> Binder:
binder.bind(
ItemsProvider,
ItemsProvider([{'Name': 'Test 1'}])
)
return binder
if __name__ == '__main__':
app = connexion.App(__name__, specification_dir='./swagger/')
app.add_api('app.yaml', resolver=RestyResolver('api'))
FlaskInjector(app=app.app, modules=[configure])
app.run(port=9090, debug=True)
./api/items.py:
from flask_injector import inject
from providers.provider import ItemsProvider
#inject(data_provider=ItemsProvider)
def search(data_provider) -> list:
return data_provider.get()
./providers/provider.py:
class ItemsProvider(object):
def __init__(self, items: list = []):
self._items = items
def get(self, number_of_items: int = 5) -> list:
if not self._items:
return []
if number_of_items > len(self._items):
number_of_items = len(self._items)
return self._items[0:number_of_items]
./swagger/app.yaml:
swagger: "2.0"
info:
title: "My first API"
version: "1.0"
basePath: /api
paths:
/items/:
get:
responses:
'200':
description: 'Fetch a list of items'
schema:
type: array
items:
$ref: '#/definitions/Item'
definitions:
Item:
type: object
properties:
id:
type: integer
format: int64
name: { type: string }
On running the app with python app.py, the api server starts as expected:
* Serving Flask app "app" (lazy loading)
* Environment: production
WARNING: Do not use the development server in a production environment.
Use a production WSGI server instead.
* Debug mode: on
* Running on http://0.0.0.0:9090/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: 498-670-595
However, addressing the server or the items endpoint in the browser, the following failure stack appears:
127.0.0.1 - - [21/May/2019 08:16:31] "GET / HTTP/1.1" 500 -
Traceback (most recent call last):
File "/home/christian/.conda/envs/miccroservice/lib/python3.6/site-packages/flask/app.py", line 2309, in __call__
return self.wsgi_app(environ, start_response)
File "/home/christian/.conda/envs/miccroservice/lib/python3.6/site-packages/flask/app.py", line 2295, in wsgi_app
response = self.handle_exception(e)
File "/home/christian/.conda/envs/miccroservice/lib/python3.6/site-packages/flask/app.py", line 1741, in handle_exception
reraise(exc_type, exc_value, tb)
File "/home/christian/.conda/envs/miccroservice/lib/python3.6/site-packages/flask/_compat.py", line 35, in reraise
raise value
File "/home/christian/.conda/envs/miccroservice/lib/python3.6/site-packages/flask/app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "/home/christian/.conda/envs/miccroservice/lib/python3.6/site-packages/flask/app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/christian/.conda/envs/miccroservice/lib/python3.6/site-packages/flask/app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/home/christian/.conda/envs/miccroservice/lib/python3.6/site-packages/flask/_compat.py", line 35, in reraise
raise value
File "/home/christian/.conda/envs/miccroservice/lib/python3.6/site-packages/flask/app.py", line 1811, in full_dispatch_request
rv = self.preprocess_request()
File "/home/christian/.conda/envs/miccroservice/lib/python3.6/site-packages/flask/app.py", line 2087, in preprocess_request
rv = func()
File "/home/christian/.conda/envs/miccroservice/lib/python3.6/site-packages/flask_injector.py", line 327, in reset_request_scope_before
injector_not_null.get(request_scope_class).prepare()
File "/home/christian/.conda/envs/miccroservice/lib/python3.6/site-packages/injector.py", line 738, in get
result = scope_instance.get(key, binding.provider).get(self)
File "/home/christian/.conda/envs/miccroservice/lib/python3.6/site-packages/injector.py", line 144, in get
return injector.create_object(self._cls)
File "/home/christian/.conda/envs/miccroservice/lib/python3.6/site-packages/injector.py", line 789, in create_object
(), additional_kwargs, e, self._stack,)
File "/home/christian/.conda/envs/miccroservice/lib/python3.6/site-packages/injector.py", line 73, in reraise
raise exception.with_traceback(tb)
File "/home/christian/.conda/envs/miccroservice/lib/python3.6/site-packages/injector.py", line 782, in create_object
init(instance, **additional_kwargs)
injector.CallError: Call to RequestScope.__init__() failed: __init__() missing 1 required positional argument: 'injector' (injection stack: [])
127.0.0.1 - - [21/May/2019 08:16:31] "GET /?__debugger__=yes&cmd=resource&f=style.css HTTP/1.1" 200 -
127.0.0.1 - - [21/May/2019 08:16:31] "GET /?__debugger__=yes&cmd=resource&f=debugger.js HTTP/1.1" 200 -
127.0.0.1 - - [21/May/2019 08:16:31] "GET /?__debugger__=yes&cmd=resource&f=jquery.js HTTP/1.1" 200 -
127.0.0.1 - - [21/May/2019 08:16:31] "GET /?__debugger__=yes&cmd=resource&f=console.png HTTP/1.1" 200 -
thank you for your answers. I cam meanwhile to a working solution. The #inject decorator can, at least in my current versions, not be used with parameters. It works if I change the function to:
#inject
def search(dataprovider=ItemsProvider_()) -> list:
data = dataprovider.get(0)
return data
Thanks!
Updating the injector version from injector-0.12.0 to injector-0.17.0 resolved my problem.
I got this error in the following situation:
I defined the to-be-inject class in the module where I instantiate my flask application and configure the injector:
app.py
class MyClass:
def __init__(bar)
self.bar = bar
# ... instantiate flask app and injector
I inject the class in a different module:
controller.py
from app import MyClass
#inject
def foo(my_object: MyClass):
return 'Something'
For me the solution was to create a separate module where I define MyClass that is different from the one where I instantiate the injector.
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.
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.