我正在学习 Web 应用程序开发,并且正在尝试分离模块只是为了让我的程序更明显地面向对象并且易于导航/理解。
我在Main.py中的第一次导入工作正常:
import jinja2
import main_page # <<<- This import of my module works
import os
import webapp2
from string import letters
# loads templates to make our life easier
template_dir = os.path.join(os.path.dirname(__file__), 'templates')
jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir),
autoescape = True)
######## Main App Function ########
app = webapp2.WSGIApplication([('/', MainPage)], debug=True)
我在main_page.py中的第二次导入不起作用:
import main_handler # <<< -- This import is not working
######## Implementation ########
# main page handler
class MainPage(BaseHandler):
def get(self):
self.response.headers['Content-Type'] = 'text/plain'
visits = 0
visit_cookie_str = self.request.cookies.get('visits')
if visit_cookie_str:
cookie_val = check_secure_val(visit_cookie_str)
if cookie_val:
visits = int(cookie_val)
visits += 1
new_cookie_val = make_secure_val(str(visits))
self.response.headers.add_header('Set-Cookie', 'visits=%s' % new_cookie_val)
self.write("You've been here %s times and this is the cookie: \n %s" % (visits, new_cookie_val))
我在终端中收到此错误:
文件“/Users/James/Developer/Google-App-Engine/Cookies/main_page.py”,第 6 行,在 MainPage(BaseHandler) 类中:NameError: name 'BaseHandler' is not defined
我尝试更改文件名和类名,以防它们与其他模块混淆。这些文件都在同一个文件夹中。
This is the **main_handler.py**:
import webapp2
import string
import jinja2
import hashlib
import hmac
SECRET = "test secret"
# global hash functions
def hash_str(s):
return hmac.new(SECRET, s).hexdigest()
def make_secure_val(s):
return "%s|%s" % (s, hash_str(s))
def check_secure_val(h):
val = h.split('|')[0]
if h == make_secure_val(val):
return val
# this is a template with convenience methods
class BaseHandler(webapp2.RequestHandler):
def write(self, *a, **kw):
self.response.out.write(*a, **kw)
def render(self, template, **kw):
self.write(self.render_str(template, **kw))
def render_str(self, template, **params):
t = jinja_env.get_template(template)
return t.render(params)