Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import os
- from flask import Flask, render_template, request
- from flask_sqlalchemy import SQLAlchemy
- from sqlalchemy.sql import func # REMOVE &
- # To keep track of when what was added was added.
- from datetime import datetime
- # A little trick that says turn this file into a flask application.
- app = Flask('My Flask App') # you can also specify the name of the app
- # Adding data base
- # Using use the os.path.abspath() function to get the absolute path of the current file’s directory. ##UNNECESSARY
- # DB IS AUTO CREATED IN SAME DIR AS FILE
- app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.db'
- # + os.path.join("Users/Ude-Ohanta/Desktop/flask project", "froshims.db) ##REMOVE
- # Creating an SQLAlchemy instance
- db = SQLAlchemy(app)
- # Models
- class Users(db.Model):
- # id : Field which stores unique id for every row in
- # database table.
- # first_name: Used to store the first name if the user
- # last_name: Used to store last name of the user
- # Age: Used to store the age of the user
- id = db.Column(db.Integer, primary_key=True)
- name = db.Column(db.String(10), nullable=False)
- sports = db.Column(db.String(10), nullable=False)
- created_at = db.Column(db.DateTime, default=datetime.utcnow)
- # repr method represents how one object of this datatable
- # will look like
- def __repr__(self):
- return f"Name : {self.name}, Sports: {self.sports}"
- SPORTS = [
- "Basketball",
- "Soccer",
- "Ulitimate Frisbee"
- ]
- @app.route("/")
- def index():
- return render_template("index.html", sports=SPORTS)
- @app.route("/register", methods=['POST'])
- def register():
- if not db.engine.has_table('user'): #CHECKS IF THE TABLE EXISTS IN DB
- db.create_all() #CREATES IT IF IT DOESN'T
- # validates submission
- name = request.form.get("name")
- sports = request.form.get("sports")
- if not name and sports not in SPORTS:
- return render_template("failure.html")
- user = Users(
- name = name,
- sports = sports,
- created_at =datetime.now()
- )
- db.session.add(user)
- db.session.commit()
- # remeber registrant
- # ("INSERT INTO registrants (name, sport) VALUES(?, ?)", name, sport #REMOVE
- # index into the dict the students name and set it equal to sport.
- RESGISTRANTS[name] = sport
- return render_template("success.html")
- @app.route("/registrants")
- def registrants():
- users = Users.query.all()
- for i,user in enumerate(users):
- print(f"index: {i} User: {user}")
- return render_template("registrants.html", registrants=RESGISTRANTS)
- app.run(debug=True) #TO RUN THE APP BY SIMPLY EXECUTING THE FILE OR WITH python filename.py, where filename is the name of this file
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement