ソースを参照

Enable sessions, login, logout

https
jakobsn 6年前
コミット
d9f54b0235
2個のファイルの変更57行の追加17行の削除
  1. +48
    -12
      src/app/main.py
  2. +9
    -5
      src/app/templates/index.html

+ 48
- 12
src/app/main.py ファイルの表示

@@ -2,13 +2,19 @@ import web
from web import form
import mysql.connector

# Define application routes
urls = (
'/', 'index'
'/', 'index',
'/logout', 'logout',
)

db2 = mysql.connector.connect(user='root', password='root',
host='10.5.0.5',
database='db')
# Access datavase using mysql connector package
db = mysql.connector.connect(
user='root',
password='root',
host='10.5.0.5',
database='db'
)
# Initialize application using the web py framework
app = web.application(urls, globals())
@@ -16,22 +22,52 @@ app = web.application(urls, globals())
# Get html templates
render = web.template.render('templates/')

login_form = form.Form(
form.Textbox("username", description="Username"),
form.Password("password", description="Password"),
form.Button("submit", type="submit", description="Login"),
)
# Workaround to use sessions with reloader (debugger) http://webpy.org/cookbook/session_with_reloader
if web.config.get('_session') is None:
session = web.session.Session(app, web.session.DiskStore("sessions"), initializer={"username": None})
web.config._session = session
else:
session = web.config._session

# Add session to global variables
render._add_global(session, 'session')


class index():

login_form = form.Form(
form.Textbox("username", description="Username"),
form.Password("password", description="Password"),
form.Button("submit", type="submit", description="Login"),
)

def GET(self):
cursor = db2.cursor()
cursor = db.cursor()
query = ("SELECT userid, username from users")
cursor.execute(query)
friends = cursor.fetchall()
return render.index(login_form, friends)
friends = cursor.fetchall()
cursor.close()
return render.index(self.login_form, friends)

def POST(self):
cursor = db.cursor()
query = ("SELECT userid, username, password from users")
cursor.execute(query)
friends = cursor.fetchall()
cursor.close()
data = web.input()
print("name:", data.username)
for user in friends:
if data.username == user[1] and data.password == user[2]:
session.username = data.username
return render.index(self.login_form, friends[:2])


class logout:

def GET(self):
session.kill()
return "Logged out"

if __name__ == "__main__":
app.run()


+ 9
- 5
src/app/templates/index.html ファイルの表示

@@ -19,10 +19,14 @@ $def with (login_form, friends)
$:login_form.render()
</form>

<h3>Registered friends:</h3>
<ul>
$for user in friends:
<li id="user[0]">$user[1]</li>
</ul>
$if session.username:
<h1>Logged in as $session.username</h1>
<a href="logout">Logout</a>

<h3>Registered friends:</h3>
<ul>
$for user in friends:
<li id="user[0]">$user[1]</li>
</ul>

</body>

読み込み中…
キャンセル
保存