controleurs.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. from urllib.parse import parse_qs
  2. home_html = """<h1>Home</h1>
  3. <h2>Registered Users</h2>
  4. <ul>
  5. {users}
  6. </ul>
  7. """
  8. login_html = """<h1>Home</h1>
  9. <form action="/login" method="POST">
  10. <input name="email" placeholder="email" /><br>
  11. <input type="password" placeholder="password" name="pw" /><br>
  12. <input type="submit" value="Submit" />
  13. </form>
  14. """
  15. users = [
  16. { 'name': 'Jon Snow', 'email': 'jonsnow@winterfell.com', 'pw': 'dany' },
  17. { 'name': 'Arya Stark', 'email': 'arya@winterfell.com', 'pw': 'dagger' },
  18. { 'name': 'Sansa Stark', 'email': 'sansa@winterfell.com', 'pw': 'killramsay' },
  19. { 'name': 'Bran Stark', 'email': 'bran@winterfell.com', 'pw': 'raven' }
  20. ]
  21. def make_user_list_item(user):
  22. return '<li><a href="mailto:' + user['email'] + '">' + user['name'] + '</a></li>'
  23. class HomeController:
  24. def do_GET(self):
  25. items = [make_user_list_item(user) for user in users]
  26. items_joined = "\n".join(items)
  27. return home_html.replace("{users}", items_joined)
  28. class LoginController:
  29. def do_GET(self):
  30. return login_html
  31. def do_POST(self, raw_body):
  32. body = parse_qs(raw_body)
  33. print("LoginController.do_POST body", raw_body, body)
  34. matching_users = [user for user in users if user['email'] == body['email'][0] and user['pw'] == body['pw'][0]]
  35. # # print(matching_users)
  36. # for u in users:
  37. # if(u['email'] == body['email'][0] and u['pw'] == body['pw'][0]):
  38. # return "<ul>" + make_user_list_item(matching_users[0]) + "</ul>"
  39. # else:
  40. # print("no match", u['email'], u['pw'], body['email'], body['pw'])
  41. return "<ul>" + make_user_list_item(matching_users[0]) + "</ul>" if matching_users else "bad credentials"
  42. class RegisterController:
  43. def do_GET(self):
  44. print('I am RegisterController')