login-ex.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. # Warning: This app is long, so for your case I recommend you to put the db and the User definition into anotehr file
  2. # Also I recommend you to use templates, see 'app.py' for more informations
  3. from flask import Flask, request
  4. from flask_login import UserMixin
  5. from flask_sqlalchemy import SQLAlchemy
  6. from login import *
  7. app = Flask(__name__)
  8. app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'
  9. app.config['SECRET_KEY'] = 'aghzi vnguierhtrutizo hard to guess indeeed'
  10. db = SQLAlchemy(app)
  11. # Define the User database using login.py
  12. User = initLogin(app, db)
  13. db.create_all()
  14. @app.route('/login')
  15. def renderLogin():
  16. return """<form action='/login/post' method='post'><p>Username: <input type="text" name="username"></p><p>Password: <input type="password" name="password"></p><p><button type="submit">Login</button></p></form>"""
  17. @app.route('/register')
  18. def renderRegister():
  19. return """<form action='/register/post' method='post'><p>Username: <input type="text" name="username"></p><p>Password: <input type="password" name="password"></p><p><button type="submit">Register</button></p></form>"""
  20. @app.route('/login/post', methods=['POST'])
  21. def login():
  22. try:
  23. loginUser(request.form['username'], request.form['password'], User)
  24. return "You are now logged in as " + current_user.username
  25. except: return "Invalid username or password"
  26. @app.route('/register/post', methods=['POST'])
  27. def register():
  28. try:
  29. createUser(request.form['username'], request.form['password'], db, User)
  30. return "New user created you are now logged in as " + current_user.username
  31. except: return "This username is already taken"
  32. @app.route('/logout') # Logout the current user is simpple
  33. def logout():
  34. logout_user()
  35. return "You are now logged out."
  36. @app.route('/locked')
  37. @login_required # Using login_required to make a page private
  38. def locked(): return "Hello " + current_user.username + " welcome to your private page."
  39. # Run the app in mode debug
  40. app.run(debug=True)