Reputation: 4735
I am learning web application development, and am trying out the separating of modules just to keep my program more obviously object oriented and easy to navigate / understand.
My first import in Main.py is working fine:
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)
My second import in main_page.py isn't working:
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))
I get this error in the terminal:
File "/Users/James/Developer/Google-App-Engine/Cookies/main_page.py", line 6, in class MainPage(BaseHandler): NameError: name 'BaseHandler' is not defined
I've tried changing file names and class names inc ase they were getting confused with other modules. The files are all in the same folder.
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)
Upvotes: 0
Views: 576
Reputation: 3834
When you import "main_handler", you can use it like this:
main_handler.make_secure_val
Not like this:
make_secure_val
Upvotes: 1