Create Logon Screen - Python 3 Web Development
Our first task is to create a small applicati on that does litt le more than present the user with a logon screen. It will be the starti ng point of our tasklist applicati on and many others as well. The code for this example as well as most other examples in this book is available from the Packt website. If you have not downloaded it yet, this might be a good ti me to do so. Enter the following pieces of code and save it in a fi le called logonapp.py in the same directory as the other fi les distributed with this chapter (Chapter 3 in the sample code): Chapter3/logonapp.py
import cherrypy
import logon
class Root(object): logon = logon.Logon(path="/logon",
authenticated="/",
not_authenticated="/goaway") @cherrypy.expose def index(self):
username=logon.checkauth('/logon')
return '''
<html><body>
<p>Hello user <b>%s</b></p>
</body>
</html>'''%username @cherrypy.expose def goaway(self): return '''
<html>
<body>
<h1>Not authenticated, please go away.</h1>
</body>
</html>''' @cherrypy.expose def somepage(self):
username=logon.checkauth('/logon',returntopage=True)
return '''<html> <body><h1>This is some page.</h1> </body> </html>'''
if __name__ == "__main__":
import os.path current_dir = os.path.dirname(os.path.abspath(__file__))
cherrypy.quickstart(Root(),config={ '/': {'tools.sessions.on': True } } )
If you now run logonapp.py, a very simple application is available on port 8080. It presents the user with a logon screen when the top level page http://localhost:8080/ is accessed.
If a correct username/password combinati on is entered, a welcome message is shown. If an unknown username or wrong password is entered, the user is redirected to http://localhost:8080/goaway.
The somepage() method (highlighted) returns a page with (presumably) some useful content. If the user is not yet authenti cated, the logon screen is shown and upon entering the correct credenti als, the user is directed back to http://localhost:8080/somepage.