KeyError: 'PATH_INFO' when using Pydev and Google App Engine - python

I've just started with GAE with Eclipse under Ubuntu 12.10 and when I try to run a sample app, I've stuck with an error that I can't solve:
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
class MainPage(webapp.RequestHandler):
def get(self):
self.response.headers['Content-Type'] = 'text/plain'
self.response.out.write('Hello, webapp World!')
application = webapp.WSGIApplication([('/', MainPage)], debug=True)
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main()
I got this error:
Traceback (most recent call last):
File "/home/mordrec/workspace/helloworld/helloworld.py", line 20, in <module>
main()
File "/home/mordrec/workspace/helloworld/helloworld.py", line 17, in main
run_wsgi_app(application)
File "/opt/google_appengine/google/appengine/ext/webapp/util.py", line 98, in run_wsgi_app
run_bare_wsgi_app(add_wsgi_middleware(application))
File "/opt/google_appengine/google/appengine/ext/webapp/util.py", line 116, in run_bare_wsgi_app
result = application(env, _start_response)
File "/opt/google_appengine/google/appengine/ext/webapp/_webapp25.py", line 688, in __call__
match = regexp.match(request.path)
File "/opt/google_appengine/lib/webob_1_1_1/webob/request.py", line 303, in path
urllib.quote(self.path_info, PATH_SAFE))
File "/opt/google_appengine/lib/webob_1_1_1/webob/descriptors.py", line 23, in fget
return req.environ[key]
KeyError: 'PATH_INFO'

I was facing the exact same issue (but on mac) an hour or two ago. Step #5 ("Deploy It Locally") on the below instructions worked for me.
You can follow these same instructions, more or less, to get debugging to work (just do "Debug As").
http://www.mkyong.com/google-app-engine/google-app-engine-python-hello-world-example-using-eclipse/
To run it locally, right click on the helloworld.py, choose “Run As” –> “Run Configuration”, create a new “PyDev Google App Run“.
In Main tab -> Main module, manually type the directory path of “dev_appserver.py“. “Browse” button is not able to help you, type manually.
In Arguments tab -> Program arguments, put "${project_loc}/src".
Run it. By default, it will deploy to localhost:8080.
Done.

Related

IIS Flask Server: IPython- ValueError: underlying buffer has been detached

I have deployed Flask Server on IIS. I'm getting below error while importing IPython module in my code.
I have tried IPython version: 5.0, 6.0, 7.16.3 but still
When i run my code through cmd it works and server on localhost starts. But when hosted through IIS Server below issue remains If I keep import IPython line in code.
My python config:
python 3.6
Flask==1.1.2
Keras==2.1.3
scikit-learn==0.23.2
scipy==1.4.1
tensorflow==1.14.0
wfastcgi==3.0.0
Heres my code:
from flask import Flask
import IPython
app = Flask(__name__)
#app.route("/flaskapi2/")
def hello():
return "Hello from FastCGI via IIS!"
if __name__ == "__main__":
app.run()
Error:
Error occurred while reading WSGI handler:
Traceback (most recent call last):
File "E:\deploy_car_damage\wfastcgi.py", line 791, in main
env, handler = read_wsgi_handler(response.physical_path)
File "E:\deploy_car_damage\wfastcgi.py", line 633, in read_wsgi_handler
handler = get_wsgi_handler(os.getenv("WSGI_HANDLER"))
File "E:\deploy_car_damage\wfastcgi.py", line 600, in get_wsgi_handler
handler = __import__(module_name, fromlist=[name_list[0][0]])
File ".\main.py", line 2, in <module>
import IPython
File "E:\deploy_car_damage\venv36\lib\site-packages\IPython\__init__.py", line 56, in <module>
from .terminal.embed import embed
File "E:\deploy_car_damage\venv36\lib\site-packages\IPython\terminal\embed.py", line 15, in <module>
from IPython.core.interactiveshell import DummyMod, InteractiveShell
File "E:\deploy_car_damage\venv36\lib\site-packages\IPython\core\interactiveshell.py", line 63, in <module>
from IPython.utils import io
File "E:\deploy_car_damage\venv36\lib\site-packages\IPython\utils\io.py", line 94, in <module>
stdin = IOStream(sys.stdin, fallback=devnull)
File "E:\deploy_car_damage\venv36\lib\site-packages\IPython\utils\io.py", line 38, in __init__
for meth in filter(clone, dir(stream)):
File "E:\deploy_car_damage\venv36\lib\site-packages\IPython\utils\io.py", line 37, in clone
return not hasattr(self, meth) and not meth.startswith('_')
File "E:\deploy_car_damage\venv36\lib\site-packages\IPython\utils\io.py", line 81, in closed
return self.stream.closed
ValueError: underlying buffer has been detached
StdOut:
StdErr:
What does underlying buffer has been detached mean and how can I resolve it.

django.template.exceptions.TemplateDoesNotExist:

I have a python program that uses django and it generates the error django.template.exceptions.TemplateDoesNotExist. I made a sample of code to illustrate my problem. I created two files a test_file.py and HelloTemplate.txt, located in the same directory C:\Games\Game1.
#file name: test_file.py
from django.template.loader import get_template
from django.conf import settings
settings.configure(DEBUG=True,TEMPLATE_DIRS=('.', ))
#I also tried TEMPLATE_DIRS=('C:\Games\Game1', ), didn't solve the problem
import sys
def main():
myTemplate = get_template("HelloTemplate.txt")
if __name__ == '__main__':
main()
The second file is a txt file with a line Hello as fellow:
filename: HelloTemplate.txt
Hello Template
Here's the error that I got
Traceback (most recent call last):
File "test_file.py", line 17, in <module>
main()
File "test_file.py", line 13, in main
myTemplate = get_template("HelloTemplate.txt")
File "C:\WinPython-32bit-2.7.5.3\python-2.7.5\lib\site-packages\django\template\loader.py", line 25, in get_template
raise TemplateDoesNotExist(template_name, chain=chain)
django.template.exceptions.TemplateDoesNotExist: HelloTemplate.txt
Thanks for your help to fix this error.
I guess get_template searches the file's concrete path which you define in the django project settings.py.

Error in Tumblelog Application development using Flask and MongoEngine

I am trying to follow below tutorial but I am facing few issue, when i run manage.py. Any help could be great help.
http://docs.mongodb.org/ecosystem/tutorial/write-a-tumblelog-application-with-flask-mongoengine/#id1
manage.py run output:
(Tumbler)afiz Tumbler $ python manage.py
Traceback (most recent call last):
File "manage.py", line 6, in <module>
from tumblelog import app
File "/home/afiz/.virtualenvs/tumblelog/__init__.py", line 18, in <module>
register_blueprints(app)
File "/home/afiz/.virtualenvs/tumblelog/__init__.py", line 13, in register_blueprints
from tumblelog.views import posts
File "/home/afiz/.virtualenvs/tumblelog/views.py", line 5, in <module>
from tumblelog.models import Post, Comment
File "/home/afiz/.virtualenvs/tumblelog/models.py", line 6, in <module>
class Post(db.DynamicDocument):
File "/home/afiz/.virtualenvs/Tumbler/local/lib/python2.7/site-packages/mongoengine/base/metaclasses.py", line 361, in __new__
meta['index_specs'] = new_class._build_index_specs(meta['indexes'])
File "/home/afiz/.virtualenvs/Tumbler/local/lib/python2.7/site-packages/mongoengine/base/document.py", line 722, in _build_index_specs
unique_indices = cls._unique_with_indexes()
File "/home/afiz/.virtualenvs/Tumbler/local/lib/python2.7/site-packages/mongoengine/base/document.py", line 861, in _unique_with_indexes
field.document_type != cls):
File "/home/afiz/.virtualenvs/Tumbler/local/lib/python2.7/site-packages/mongoengine/fields.py", line 563, in document_type
self.document_type_obj = get_document(self.document_type_obj)
File "/home/afiz/.virtualenvs/Tumbler/local/lib/python2.7/site-packages/mongoengine/base/common.py", line 25, in get_document
""".strip() % name)
mongoengine.errors.NotRegistered: `Comment` has not been registered in the document registry.
Importing the document class automatically registers it, has it
been imported?
manage.py file:
#set the path
import os, sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from flask.ext.script import Manager, Server
from tumblelog import app
manager = Manager(app)
# Turn on debugger by default and reloader
manager.add_command("runserver", Server(
use_debugger = True,
use_reloader = True,
host = '0.0.0.0')
)
if __name__ == "__main__":
manager.run()
I had the same problem as you are facing now. In models.py file I just wrote
class Comment(db.EmbeddedDocument):
and it's content first then added
class Post(db.Document):
and then it's content. In other words, I first wrote Comment class then Post class and problem got solved ;) :) Cheers!!
Inside Post, when EmbeddedDocumentField is assigned to a variable, it needs to be pre-registered. Therefore, always register such field i.e. Comments before they are used.

PyUnit error in PyDev

I am trying to Use PyUnit within PyDev for the first time. I created a unittest.py module. When I did run as -> Python unit-test, I got the following error:
Finding files... done.
Importing test modules ... done.
======================================================================
Traceback (most recent call last):
File "/Applications/eclipse/plugins/org.python.pydev_2.7.5.2013052819/pysrc/runfiles.py", line 163, in
main()
File "/Applications/eclipse/plugins/org.python.pydev_2.7.5.2013052819/pysrc/runfiles.py", line 77, in main
pydev_runfiles.main(configuration)
File "/Applications/eclipse/plugins/org.python.pydev_2.7.5.2013052819/pysrc/pydev_runfiles.py", line 761, in main
PydevTestRunner(configuration).run_tests()
File "/Applications/eclipse/plugins/org.python.pydev_2.7.5.2013052819/pysrc/pydev_runfiles.py", line 747, in run_tests
runner.run(test_suite)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/runner.py", line 158, in run
result.printErrors()
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/runner.py", line 108, in printErrors
self.printErrorList('ERROR', self.errors)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/runner.py", line 114, in printErrorList
self.stream.writeln("%s: %s" % (flavour,self.getDescription(test)))
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/runner.py", line 46, in getDescription
return '\n'.join((str(test), doc_first_line))
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/case.py", line 1060, in __str__
self._testFunc.__name__)
AttributeError: 'str' object has no attribute '__name__'
My unit test is just the PyDev-generated default:
import unittest
class Test(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def testName(self):
pass
print "hello test"
if __name__ == "__main__":
#import sys;sys.argv = ['', 'Test.testName']
unittest.main()
I expected it to print hello test. What am I missing?
Ok, I realized your problem, after having a similar issue for several minutes. You need to rename your file. Name it anything other than unittest.py. This causes the compiler to confuse between your module and the unittest module that you are importing.
Second, even after you change the name of your file, you may run into the same error. That is caused by the unittest.pyc file not being removed from your project. Rename the file, delete the previously generated unittest.pyc file, and the test should run just fine.

Inheritance in web.py?

I am currently developing wep.py application. This is my web application which is binded with web.py and wsgi.
root/main.py
import web
import sys
import imp
import os
sys.path.append(os.path.dirname(__file__))
#from module import module
from exam import exam
urls = (
'/exam', 'exam'
)
application = web.application(urls, globals(), autoreload = True).wsgifunc()
My application has an abstract class called module in module.py in root directory and its purpose is to be inherited by modules.
root/module.py
class module:
def fetchURL(self, url):
# ...
return content
The lower level module called "exam" would inherits module
root/exam/init.py
from module import module
class exam(module):
def getResults(self):
# error occurs here
self.fetchURL('math.json')
When I call the parent method, web.py raises an exception
WalkerError: ('unexpected node type', 339)
Environment: Python 2.5
How can I resolve the problem? Thanks
// EDIT 03 July 10:22 GMT+0
The stack trace is as follows
mod_wsgi (pid=1028): Exception occurred processing WSGI script 'D:/py/labs_library/index.py'.
Traceback (most recent call last):
File "D:\csvn\Python25\lib\site-packages\web\application.py", line 277, in wsgi
result = self.handle_with_processors()
File "D:\csvn\Python25\lib\site-packages\web\application.py", line 247, in handle_with_processors
return process(self.processors)
File "D:\csvn\Python25\lib\site-packages\web\application.py", line 244, in process
raise self.internalerror()
File "D:\csvn\Python25\lib\site-packages\web\application.py", line 467, in internalerror
return debugerror.debugerror()
File "D:\csvn\Python25\lib\site-packages\web\debugerror.py", line 305, in debugerror
return web._InternalError(djangoerror())
File "D:\csvn\Python25\lib\site-packages\web\debugerror.py", line 290, in djangoerror
djangoerror_r = Template(djangoerror_t, filename=__file__, filter=websafe)
File "D:\csvn\Python25\lib\site-packages\web\template.py", line 845, in __init__
code = self.compile_template(text, filename)
File "D:\csvn\Python25\lib\site-packages\web\template.py", line 924, in compile_template
ast = compiler.parse(code)
File "D:\csvn\Python25\lib\compiler\transformer.py", line 51, in parse
return Transformer().parsesuite(buf)
File "D:\csvn\Python25\lib\compiler\transformer.py", line 128, in parsesuite
return self.transform(parser.suite(text))
File "D:\csvn\Python25\lib\compiler\transformer.py", line 124, in transform
return self.compile_node(tree)
File "D:\csvn\Python25\lib\compiler\transformer.py", line 167, in compile_node
raise WalkerError, ('unexpected node type', n)
WalkerError: ('unexpected node type', 339)
If it is possible I would like to turn off the template functionality as I use python only for JSON output for mobile app.
if you create python module you should add __init__.py in top of your hierarchy:
dvedit/
__init__.py
clipview.py
filters/
__init__.py
it means that in every directory which will be imported via from ... import ... should have __init__.py file.
further info available: http://wiki.cython.org/PackageHierarchy

Categories

Resources