新手python导入错误
我刚开始学Python,正在使用Bottle这个网页框架在Google App Engine上搭建项目。我在尝试一个超级简单的“你好,世界”示例时遇到了一些问题。哈哈。最后我终于让代码运行起来了...
import bottle
from bottle import route
from google.appengine.ext.webapp import util
@route('/')
def index():
return "Hello World!"
util.run_wsgi_app(bottle.default_app())
我想问的是,我以为只要写' import bottle '就可以了,不需要第二行。但是如果我把第二行去掉,就会出现一个NameError错误。即使我写' from bottle import * ',还是会出现这个错误。bottle其实就是一个叫'bottle.py'的文件,放在我网站的根目录下。所以这两种方式都不行....
import bottle
from google.appengine.ext.webapp import util
@route('/')
def index():
return "Hello World!"
util.run_wsgi_app(bottle.default_app())
或者
from bottle import *
from google.appengine.ext.webapp import util
@route('/')
def index():
return "Hello World!"
util.run_wsgi_app(bottle.default_app())
我收到的错误信息是...
追踪记录(最近的调用在最前面):
文件 "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver.py", 第3180行,在_HandleRequest中 self._Dispatch(dispatcher, self.rfile, outfile, env_dict) 文件 "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver.py", 第3123行,在_Dispatch中 base_env_dict=env_dict) 文件 "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver.py", 第515行,在Dispatch中 base_env_dict=base_env_dict) 文件 "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver.py", 第2382行,在Dispatch中 self._module_dict) 文件 "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver.py", 第2292行,在ExecuteCGI中 reset_modules = exec_script(handler_path, cgi_path, hook) 文件 "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver.py", 第2188行,在ExecuteOrImportScript中 exec module_code in script_module.dict 文件 "/Users/tyler/Dropbox/sites/dietgrid/code2.py", 第4行,在 @route('/') NameError: name 'route' is not defined
所以我是不是想错了,认为应该可以用其他方式来实现呢?
5 个回答
route
是 bottle
模块的一部分。
下面的内容应该能解决这个问题。
import bottle
...
@bottle.route('/hello')
def hello():
return "Hello World!"
...
关于为什么
from bottle import *
不起作用:当你这样导入时,只有在bottle的_____all_____列表中指定的名称才会被导入。所以,如果route不在这个列表里,你就需要明确地指定导入:
from bottle import route
在你的代码中,有两种不同的方式来调用bottle这个包里的方法。
route('/hello')
还有
bottle.default_app()
第一种调用方式需要你写 from bottle import route
或者 from bottle import *
,而第二种方式则需要写 import bottle
。
from foo import bar
让你可以在代码中使用方法或参数 bar
,而不需要在每次调用时都指定它属于哪个包。