Advertisement
Guest User

Untitled

a guest
Jul 24th, 2017
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.27 KB | None | 0 0
  1. from flask import Flask, request, redirect, render_template, session, flash
  2. from flask_sqlalchemy import SQLAlchemy
  3. from helpers import valid_input, verify_pass
  4.  
  5. app = Flask(__name__)
  6. app.config['DEBUG'] = True
  7. app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://rw_blogz:launchcode@localhost:8889/rw_blogz'
  8. app.config['SQLALCHEMY_ECHO'] = True
  9. app.secret_key = "Kw74Jnx0pSsD86bc9"
  10.  
  11.  
  12. # Note: the connection string after :// contains the following info:
  13. # user:password@server:portNumber/databaseName
  14.  
  15. db = SQLAlchemy(app)
  16.  
  17. class Blog(db.Model):
  18. ''' creates a database record for each blog post '''
  19. id = db.Column(db.Integer, primary_key=True)
  20. title = db.Column(db.String(200))
  21. body = db.Column(db.String(5000))
  22. author_id = db.Column(db.Integer, db.ForeignKey('user.id'))
  23.  
  24. def __init__(self, title, body, author):
  25. self.title = title
  26. self.body = body
  27. self.author = author
  28.  
  29. # TODO - add Blog helper functions to /newpost
  30. # def has_content(self):
  31. # if self.title and self.content:
  32. # return True
  33.  
  34. # return False
  35.  
  36. class User(db.Model):
  37. ''' creates a database record for each blog user '''
  38. id = db.Column(db.Integer, primary_key=True)
  39. username = db.Column(db.String(50), unique=True)
  40. password = db.Column(db.String(40))
  41. blogs = db.relationship('Blog', backref='author')
  42.  
  43. def __init__(self, username, password):
  44. self.username = username
  45. self.password = password
  46.  
  47.  
  48. ### SARAH COMMENT: All templates with a specific route needs to have action = "/routename" in the form tag ###
  49.  
  50. # TODO:
  51. # - add 3 new templates: *signup.html, *login.html, **index.html
  52. # - add singleUser.html to display only blogs associated with a particular author
  53. # - add logout function that: a) handles a post request to /logout, b) redirects user to /blog after deleting username from session
  54.  
  55.  
  56. # requires user to login for particular routes
  57.  
  58.  
  59. @app.route("/blog", methods=['GET'])
  60. def index():
  61. # check for query parameters, indicating a single post needs to be displayed
  62. # assign any id params to a variable
  63. blog_id = request.args.get('id')
  64. if blog_id:
  65. single_post = Blog.query.filter_by(id = blog_id).all()
  66. #render blog template with contents of the single post only
  67. return render_template('main.html', pagetitle ="Blog Posts", mainheader = single_post[0].title, blogs = single_post)
  68.  
  69. # otherwise, display all blog posts
  70. blogs = Blog.query.all()
  71. mainheader = "Hi there - welcome to my blog!"
  72. return render_template('main.html', pagetitle = "Blog Posts", mainheader = mainheader, blogs = blogs)
  73.  
  74. @app.route("/login", methods=['GET','POST'])
  75. def login():
  76. #TODO - check that validation is working
  77. if request.method == 'POST':
  78. print("This function is running!")
  79. username = request.form['username']
  80. password = request.form['password']
  81. session['username'] = username
  82. user_login = User.query.filter_by(username=username).first()
  83. # check for existing username and password, then redirect to /newpost
  84.  
  85. ### SARAH COMMENT: session may need to start before this if statement ###
  86. if user_login and user_login.password == password:
  87. return redirect('/newpost')
  88. # otherwise, display error message
  89. # flash('The username or password you entered did not match our system, please try again', 'error')
  90. print('error!')
  91. return render_template('login.html')
  92.  
  93. @app.route('/signup', methods=['GET','POST'])
  94. def signup():
  95. if request.method == 'POST':
  96. # user inputs submitted through the signup form
  97. username = request.form['username']
  98. password = request.form['pass1']
  99. verify = request.form['pass2']
  100.  
  101. # if username exists in the db, assign it to this variable
  102. existing_user = User.query.filter_by(username = username).first()
  103. # increment this variable to check for errors on page during user validation
  104. total_errors = 0
  105.  
  106. # Validate the information submitted and generate error messages
  107. if username == '' or password == '' or verify == '':
  108. # flash('Sorry, one or more fields are invalid. A username, password, and password verification are required.', 'error')
  109. total_errors += 1
  110. if valid_input(username) == False:
  111. # flash('Sorry, that username won\'t work! Please enter a username between 3 and 40 characters, with no spaces.', 'error')
  112. total_errors += 1
  113. if valid_input(password) == False:
  114. # flash('Sorry, that password won\'t work! Please enter a password between 3 and 40 characters, with no spaces.', 'error')
  115. total_errors += 1
  116. if verify_pass(password, verify) == False:
  117. # flash('These passwords don\'t match! Please enter your passwords again.', 'error')
  118. total_errors += 1
  119. if existing_user:
  120. # flash('This username is already taken. If you would like to sign in as this user, click <a href=\'/login\'>here.</a>', 'error')
  121. total_errors += 1
  122.  
  123. # if error messages are generated, re-render the signup form to display messages
  124. if total_errors > 0:
  125. return render_template('signup.html')
  126.  
  127. # if validation passes with 0 errors, update the db with the new user information
  128. if total_errors == 0:
  129. new_user = User(username, password)
  130. db.session.add(new_user)
  131. db.session.commit()
  132.  
  133. # add username to session and redirect to /newpost
  134. session['username']= username
  135. return redirect('/newpost')
  136.  
  137.  
  138. return render_template('signup.html')
  139.  
  140. ### SARAH COMMENT: Try getting all of your error cases out of the way first as an "if",
  141. # and then do "else: commit a new user to db" ###
  142.  
  143. # increment this variable to check for errors on page during user validation
  144.  
  145. #Validate the information submitted and generate error messages
  146.  
  147. @app.route('/newpost', methods = ['GET', 'POST'])
  148. def new_post():
  149.  
  150. if request.method == 'POST':
  151.  
  152. blog_title = request.form['title']
  153. blog_content = request.form['blogpost']
  154. author_id = User.query.filter_by(username=session['username']).first()
  155.  
  156. # new post error validation starts here - both fields on form must be filled in
  157.  
  158. if blog_title == '' or blog_content == '':
  159. if blog_title == '':
  160. flash("Please enter a title for this blog post!", 'error')
  161. if blog_content == '':
  162. flash("Please add content to the body of your post!", 'error')
  163. # return new post template with error messages
  164. return render_template('newpost.html', pagetitle="Add a Blog Post", title = blog_title, blogpost = blog_content)
  165.  
  166. # if no errors, then assign information and update db
  167. new_post = Blog(blog_title, blog_content, author_id)
  168. db.session.add(new_post)
  169. db.session.commit()
  170.  
  171. # after db update, redirect user to main page, but display only the newly created post
  172. return redirect('/blog?id=' + str(new_post.id))
  173.  
  174. # in the case of a get request, render an empty new post template
  175. return render_template('newpost.html', pagetitle = "Add a Blog Post")
  176.  
  177.  
  178. if __name__ == '__main__':
  179. app.run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement