Guest User

app.py

a guest
Oct 28th, 2020
931
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. from flask import Flask, render_template, request, redirect, url_for
  2. from flask_sqlalchemy import SQLAlchemy
  3. import sqlite3
  4. from covid import covid_obj
  5. import random
  6. from datetime import datetime
  7.  
  8. from werkzeug.security import generate_password_hash
  9.  
  10. from flask_login import LoginManager, login_required
  11.  
  12. app = Flask(__name__)
  13. app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
  14. db = SQLAlchemy(app)
  15.  
  16. login_manager = LoginManager() # Login manage for flask-login
  17. login_manager.init_app(app)
  18.  
  19. # User.query.all()
  20. # User.query.filter_by(username="James").first()
  21. class User(db.Model):
  22.     """Create columns to store our data"""
  23.  
  24.     id = db.Column(db.Integer, primary_key=True)
  25.     username = db.Column(db.String(60), unique=True, nullable=False)
  26.     password = db.Column(db.String(20), unique=True, nullable=False)
  27.     email = db.Column(db.String(60), unique=True, nullable=False)
  28.  
  29.     def __repr__(self):
  30.         return '<User %r>' % self.username
  31.  
  32.  
  33. class Course(db.Model):
  34.     """Create this course table to store course details"""
  35.  
  36.     id = db.Column(db.Integer,
  37.                     primary_key=True)
  38.     title = db.Column(db.String(120),
  39.                       nullable=False)
  40.     description = db.Column(db.Text,
  41.                             nullable=False)
  42.     price = db.Column(db.Integer,
  43.                       nullable=False)
  44.     duration = db.Column(db.Integer,
  45.                          nullable=False)
  46.     instructor = db.Column(db.String(80),
  47.                            nullable=False)
  48.     date_created = db.Column(db.DateTime(),
  49.                              default=datetime.utcnow)
  50.  
  51.  
  52. @login_manager.user_loader
  53. def load_user(user_id):
  54.  
  55.     return User.query.get(int(user_id))
  56.  
  57.  
  58. # Only test
  59. @app.route('/test')
  60. def home_test():
  61.  
  62.     name = "Son"
  63.     return render_template("home-test.html", name=name)  
  64.  
  65.  
  66. @app.route('/about')
  67. @login_required
  68. def about():
  69.     return render_template("about.html")
  70.  
  71.  
  72. @app.route('/script')
  73. def test_script():
  74.     return render_template("test-script.html")
  75.  
  76.  
  77. @app.route('/covid-table')
  78. def covid_table():
  79.     """Return covid19 data to show in a table"""
  80.  
  81.     covid_data = covid_obj
  82.  
  83.     return render_template("covid-table.html", covid_data=covid_data)
  84.  
  85.  
  86. @app.route('/covid-dashboard')
  87. def covid_dashboard():
  88.     """Return covid19 data to display in a dashboard"""
  89.  
  90.     data = covid_obj
  91.     confirmed_case = data["Confirmed"]
  92.     recovered_case = data["Recovered"]
  93.     hospitalized_case = data["Hospitalized"]
  94.     new_deaths_case = data["NewDeaths"]
  95.     new_confirmed_case = data["NewConfirmed"]
  96.     last_updated = data["UpdateDate"]
  97.  
  98.     return render_template("covid-dashboard.html", confirmed_case=confirmed_case,
  99.                                                     recovered_case=recovered_case,
  100.                                                     hospitalized_case=hospitalized_case,
  101.                                                     new_deaths_case=new_deaths_case,
  102.                                                     new_confirmed_case=new_confirmed_case,
  103.                                                     last_updated=last_updated)
  104.  
  105.  
  106.  
  107. @app.route('/random-menu')
  108. def random_menu():
  109.  
  110.     random_list = ["กะเพราหมู", "ไข่เจียวหมูสับ", "หมูทอดกระเทียม", "ก๋วยเตี๋ยว", "ผัดซีอิ๊ว"]
  111.     menu_data = random.choice(random_list)
  112.  
  113.     return render_template("random-menu.html", menu_data=menu_data)
  114.  
  115.  
  116. @app.route('/create', methods=["GET", "POST"])
  117. @login_required
  118. def create():
  119.     """Create a new course"""
  120.  
  121.     # Check if method that being sent is "POST"
  122.     if request.method == "POST":
  123.  
  124.         # Create variables to get input attributes from form
  125.         title = request.form["title"]
  126.         instructor = request.form["instructor"]
  127.         price = request.form["price"]
  128.         duration = request.form["duration"]
  129.         description = request.form["description"]
  130.  
  131.         # Create an object, then pass variables into the class(Course)
  132.         obj = Course(title=title,
  133.                      instructor=instructor,
  134.                      price=price,
  135.                      duration=duration,
  136.                      description=description)
  137.  
  138.         # Add the object to SQlAlchemy session
  139.         # then submit it into our database
  140.         db.session.add(obj)
  141.         db.session.commit()
  142.  
  143.         # Redirect to home page after submitting form
  144.         return redirect(url_for('home'))
  145.                
  146.     return render_template("create-course.html")
  147.  
  148.  
  149.  
  150. @app.route('/')
  151. def home():
  152.     """Retrieve all courses from the database"""
  153.  
  154.     all_courses = Course.query.all()
  155.  
  156.     return render_template("home.html", all_courses=all_courses)
  157.  
  158.  
  159. @app.route('/post-details/<int:id>')
  160. def post_details(id):
  161.     """Retrieve only one course(by id)"""
  162.  
  163.     single_course = Course.query.get(id)
  164.  
  165.     return render_template("post-details.html", single_course=single_course)
  166.  
  167.  
  168. @app.route('/update/<int:id>', methods=["GET", "POST"])
  169. def update(id):
  170.     """Update an existing post"""
  171.  
  172.     data = Course.query.get(id)
  173.  
  174.     # Check if method that being sent is "POST"
  175.     if request.method == "POST":
  176.  
  177.         # Create variables to get input attributes from form
  178.         title = request.form["title"]
  179.         instructor = request.form["instructor"]
  180.         price = request.form["price"]
  181.         duration = request.form["duration"]
  182.         description = request.form["description"]
  183.  
  184.         data.title = title
  185.         data.instructor = instructor
  186.         data.price = price
  187.         data.duration = duration
  188.         data.description = description
  189.  
  190.         # Submit an updated post into the database
  191.         db.session.commit()
  192.  
  193.         # Redirect to home page after finishing update
  194.         return redirect(url_for('home'))
  195.  
  196.     return render_template('update.html', data=data)
  197.  
  198.  
  199. @app.route('/delete/<int:id>', methods=["GET", "POST"])
  200. def delete(id):
  201.     """Delete a post"""
  202.  
  203.     data = Course.query.get(id)
  204.  
  205.     db.session.delete(data)
  206.     db.session.commit()
  207.  
  208.     return redirect(url_for('home'))
  209.  
  210.  
  211. @app.route('/sign-up', methods=["GET", "POST"])
  212. def sign_up():
  213.     """Sign up user account"""
  214.  
  215.     # Check if method that being sent is "POST"
  216.     if request.method == "POST":
  217.  
  218.         # Create variables to get input attribute values from our form
  219.         username = request.form["username"]
  220.         password = request.form["password"]
  221.         email = request.form["email"]
  222.  
  223.         # Create an object, then pass variables
  224.         # into the User class
  225.         obj = User(username=username,
  226.                    password=generate_password_hash(password, method='sha256'),
  227.                    email=email)
  228.  
  229.         # Add an object to SQLAlchemy session
  230.         # then submit into our database
  231.         db.session.add(obj)
  232.         db.session.commit()
  233.  
  234.         # Redirect to home page after submitting form
  235.         return redirect(url_for('home'))
  236.  
  237.     return render_template('sign-up.html')
  238.  
  239.  
  240. @app.route('/login', methods=['GET', 'POST'])
  241. def login():
  242.  
  243.     # Do nothing, only render HTML now
  244.     return render_template("login.html")
  245.  
  246.  
  247. if __name__ =="__main__":
  248.     app.run(debug=True)
  249.  
RAW Paste Data