I am trying to import from a folder named template which is structured like
controller/
/__init__.py
/login.py # <- I'm here
template/
/__init__.py # from template import *
/template.py # contains class Template
python seems to be able to see the need class but fail to import it, this is login.py code
import webapp2
import template
class Login(webapp2.RequestHandler):
#class Login(template.Template):
def get(self):
self.response.out.write(dir(template))
prints
['Template', 'Users', '__builtins__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', 'jinja2', 'os', 'template', 'urllib', 'webapp2']
switched import line
import webapp2
import template
#class Login(webapp2.RequestHandler):
class Login(template.Template):
def get(self):
self.response.out.write(dir(template))
prints
class Login(template.Template):
AttributeError: 'module' object has no attribute 'Template'
what am I doing wrong? thanks
Edit: I have created another folder named index which contains
index/
/__init__.py # from index import *
/index.py # class Index
/index.html
the code inside index.py is
from template import Template
class Index(Template):
def get(self):
self.render("/index/index.html")
this code just worked without any errors, but the one index controller folder fails
The problem is that when template/__init__.py does:
from template import *
It isn't importing from where you think - it is importing everything from itself, since having a folder called 'template' with an __init__.py defines a module called 'template' - which gets priority over the module inside it also called 'template'. You need to tell Python explicitly that you want the inner module, which you can do like this:
from .template import *
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With