daily pastebin goal
33%
SHARE
TWEET

app.py

lamiastella Oct 13th, 2017 708 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. ######################################
  2. # author ben lawson <balawson@bu.edu>
  3. # Edited by: Baichuan Zhou (baichuan@bu.edu) and Craig Einstein <einstein@bu.edu>
  4. ######################################
  5. # Some code adapted from
  6. # CodeHandBook at http://codehandbook.org/python-web-application-development-using-flask-and-mysql/
  7. # and MaxCountryMan at https://github.com/maxcountryman/flask-login/
  8. # and Flask Offical Tutorial at  http://flask.pocoo.org/docs/0.10/patterns/fileuploads/
  9. # see links for further understanding
  10. ###################################################
  11.  
  12. import flask
  13. from flask import Flask, Response, request, render_template, redirect, url_for
  14. from flaskext.mysql import MySQL
  15. import flask.ext.login as flask_login
  16.  
  17. # for image uploading
  18. # from werkzeug import secure_filename
  19. import os, base64
  20.  
  21. mysql = MySQL()
  22. app = Flask(__name__)
  23. app.secret_key = 'super secret string'  # Change this!
  24.  
  25. # These will need to be changed according to your creditionals
  26. app.config['MYSQL_DATABASE_USER'] = 'root'
  27. app.config['MYSQL_DATABASE_PASSWORD'] = 'hello'
  28. app.config['MYSQL_DATABASE_DB'] = 'photoshare'
  29. app.config['MYSQL_DATABASE_HOST'] = 'localhost'
  30. mysql.init_app(app)
  31.  
  32. # begin code used for login
  33. login_manager = flask_login.LoginManager()
  34. login_manager.init_app(app)
  35.  
  36. conn = mysql.connect()
  37. cursor = conn.cursor()
  38. cursor.execute("SELECT email FROM Users")
  39. users = cursor.fetchall()
  40.  
  41.  
  42. def getUserList():
  43.     cursor = conn.cursor()
  44.     cursor.execute("SELECT email FROM Users")
  45.     return cursor.fetchall()
  46.  
  47.  
  48. class User(flask_login.UserMixin):
  49.     pass
  50.  
  51.  
  52. @login_manager.user_loader
  53. def user_loader(email):
  54.     users = getUserList()
  55.     if not (email) or email not in str(users):
  56.         return
  57.     user = User()
  58.     user.id = email
  59.     return user
  60.  
  61.  
  62. @login_manager.request_loader
  63. def request_loader(request):
  64.     users = getUserList()
  65.     email = request.form.get('email')
  66.     if not (email) or email not in str(users):
  67.         return
  68.     user = User()
  69.     user.id = email
  70.     cursor = mysql.connect().cursor()
  71.     cursor.execute("SELECT password FROM Users WHERE email = '{0}'".format(email))
  72.     data = cursor.fetchall()
  73.     pwd = str(data[0][0])
  74.     user.is_authenticated = request.form['password'] == pwd
  75.     return user
  76.  
  77.  
  78. '''
  79. A new page looks like this:
  80. @app.route('new_page_name')
  81. def new_page_function():
  82.     return new_page_html
  83. '''
  84.  
  85.  
  86. @app.route('/login', methods=['GET', 'POST'])
  87. def login():
  88.     if flask.request.method == 'GET':
  89.         return '''
  90.                <form action='login' method='POST'>
  91.                 <input type='text' name='email' id='email' placeholder='email'></input>
  92.                 <input type='password' name='password' id='password' placeholder='password'></input>
  93.                 <input type='submit' name='submit'></input>
  94.                </form></br>
  95.            <a href='/'>Home</a>
  96.                '''
  97.     # The request method is POST (page is recieving data)
  98.     email = flask.request.form['email']
  99.     cursor = conn.cursor()
  100.     # check if email is registered
  101.     if cursor.execute("SELECT password FROM Users WHERE email = '{0}'".format(email)):
  102.         data = cursor.fetchall()
  103.         pwd = str(data[0][0])
  104.         if flask.request.form['password'] == pwd:
  105.             user = User()
  106.             user.id = email
  107.             flask_login.login_user(user)  # okay login in user
  108.             return flask.redirect(flask.url_for('protected'))  # protected is a function defined in this file
  109.  
  110.     # information did not match
  111.     return "<a href='/login'>Try again</a>\
  112.             </br><a href='/register'>or make an account</a>"
  113.  
  114.  
  115. @app.route('/logout')
  116. def logout():
  117.     flask_login.logout_user()
  118.     return render_template('hello.html', message='Logged out')
  119.  
  120.  
  121. @login_manager.unauthorized_handler
  122. def unauthorized_handler():
  123.     return render_template('unauth.html')
  124.  
  125.  
  126. # you can specify specific methods (GET/POST) in function header instead of inside the functions as seen earlier
  127. @app.route("/register", methods=['GET'])
  128. def register():
  129.     return render_template('register.html', supress='True')
  130.  
  131.  
  132. @app.route("/register", methods=['POST'])
  133. def register_user():
  134.     try:
  135.         email = request.form.get('email')
  136.         password = request.form.get('password')
  137.     except:
  138.         print(
  139.             "couldn't find all tokens")  # this prints to shell, end users will not see this (all print statements go to shell)
  140.         return flask.redirect(flask.url_for('register'))
  141.     cursor = conn.cursor()
  142.     test = isEmailUnique(email)
  143.     if test:
  144.         print(cursor.execute("INSERT INTO Users (email, password) VALUES ('{0}', '{1}')".format(email, password)))
  145.         conn.commit()
  146.         # log user in
  147.         user = User()
  148.         user.id = email
  149.         flask_login.login_user(user)
  150.         return render_template('hello.html', name=email, message='Account Created!')
  151.     else:
  152.         print("couldn't find all tokens")
  153.         return flask.redirect(flask.url_for('register'))
  154.  
  155.  
  156. def getUsersPhotos(uid):
  157.     cursor = conn.cursor()
  158.     cursor.execute("SELECT imgdata, picture_id, caption FROM Pictures WHERE user_id = '{0}'".format(uid))
  159.     return cursor.fetchall()  # NOTE list of tuples, [(imgdata, pid), ...]
  160.  
  161.  
  162. def getUserIdFromEmail(email):
  163.     cursor = conn.cursor()
  164.     cursor.execute("SELECT user_id  FROM Users WHERE email = '{0}'".format(email))
  165.     return cursor.fetchone()[0]
  166.  
  167.  
  168. def isEmailUnique(email):
  169.     # use this to check if a email has already been registered
  170.     cursor = conn.cursor()
  171.     if cursor.execute("SELECT email  FROM Users WHERE email = '{0}'".format(email)):
  172.         # this means there are greater than zero entries with that email
  173.         return False
  174.     else:
  175.         return True
  176.  
  177.  
  178. # end login code
  179.  
  180. @app.route('/profile')
  181. @flask_login.login_required
  182. def protected():
  183.     return render_template('hello.html', name=flask_login.current_user.id, message="Here's your profile")
  184.  
  185.  
  186. # begin photo uploading code
  187. # photos uploaded using base64 encoding so they can be directly embeded in HTML
  188. ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])
  189.  
  190.  
  191. def allowed_file(filename):
  192.     return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
  193.  
  194.  
  195. @app.route('/upload', methods=['GET', 'POST'])
  196. @flask_login.login_required
  197. def upload_file():
  198.     if request.method == 'POST':
  199.         uid = getUserIdFromEmail(flask_login.current_user.id)
  200.         imgfile = request.files['photo']
  201.         caption = request.form.get('caption')
  202.         print(caption)
  203.         photo_data = base64.standard_b64encode(imgfile.read())
  204.         cursor = conn.cursor()
  205.         cursor.execute(
  206.             "INSERT INTO Pictures (imgdata, user_id, caption) VALUES (photo_data, uid, caption)")
  207.         conn.commit()
  208.         return render_template('hello.html', name=flask_login.current_user.id, message='Photo uploaded!',
  209.                                photos=getUsersPhotos(uid))
  210.     # The method is GET so we return a  HTML form to upload the a photo.
  211.     else:
  212.         return render_template('upload.html')
  213.  
  214.  
  215. # end photo uploading code
  216.  
  217.  
  218. # default page
  219. @app.route("/", methods=['GET'])
  220. def hello():
  221.     return render_template('hello.html', message='Welecome to Photoshare')
  222.  
  223.  
  224. if __name__ == "__main__":
  225.     # this is invoked when in the shell  you run
  226.     # $ python app.py
  227.     app.run(port=5000, debug=True)
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top