Advertisement
Guest User

Untitled

a guest
Sep 25th, 2017
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.06 KB | None | 0 0
  1. from flask import Flask, render_template, g, request, jsonify
  2. from werkzeug import check_password_hash, generate_password_hash
  3.  
  4. import sqlite3
  5.  
  6. app = Flask(__name__)
  7.  
  8. ### Database stuff ###
  9. def get_db():
  10. db = getattr(g, '_database', None)
  11. if db is None:
  12. db = g._database = connect_to_database()
  13. return db
  14.  
  15. def connect_to_database():
  16. conn = sqlite3.connect('db.sqlite3')
  17. conn.row_factory = sqlite3.Row
  18. return conn
  19.  
  20. def init_db():
  21. db = get_db()
  22. with app.open_resource('schema.sql', mode='r') as f:
  23. db.cursor().executescript(f.read())
  24. db.commit()
  25.  
  26. def query_db(query, args=(), one=False):
  27. """Queries the database and returns a list of dictionaries."""
  28. cur = get_db().execute(query, args)
  29. rv = cur.fetchall()
  30. return (rv[0] if rv else None) if one else rv
  31.  
  32. @app.teardown_appcontext
  33. def close_database(exception):
  34. if hasattr(g, '_database'):
  35. g._database.close()
  36.  
  37. @app.cli.command('initdb')
  38. def init_db_command():
  39. init_db()
  40. print('Initialized the database.')
  41.  
  42. ### API ###
  43. @app.route('/api/v1/tweet/', methods=['POST'])
  44. def create_tweet():
  45. error = None
  46. if 'message' not in request.form:
  47. error = 'You must provide a message.'
  48. elif 'author_id' not in request.form:
  49. error = 'You must provide an author ID'
  50.  
  51. if error:
  52. return jsonify(
  53. status='error',
  54. error=error
  55. )
  56.  
  57. db = get_db()
  58. db.execute('''insert into tweet (message, author_id) values (?, ?)''', [request.form['message'], request.form['author_id']])
  59. db.commit()
  60.  
  61. return jsonify(
  62. status='success'
  63. )
  64.  
  65. @app.route('/api/v1/tweet/<int:tweet_id>', methods=['GET'])
  66. def get_tweet(tweet_id):
  67. tweet = query_db('''select * from tweet where tweet_id = ?''', [tweet_id], one=True)
  68. if not tweet:
  69. return jsonify(
  70. status='error',
  71. error='Tweet not found'
  72.  
  73. )
  74.  
  75. return jsonify(
  76. status='success',
  77. tweet_id=tweet_id,
  78. message=tweet['message'],
  79. author_id=tweet['author_id']
  80. )
  81.  
  82. @app.route('/api/v1/tweet/<int:tweet_id>', methods=['PUT'])
  83. def update_tweet(tweet_id):
  84. tweet = query_db('''select * from tweet where tweet_id = ?''', [tweet_id], one=True)
  85. if not tweet:
  86. return jsonify(
  87. status='error',
  88. error='Tweet not found'
  89.  
  90. )
  91.  
  92. message = tweet['message']
  93. author_id = tweet['author_id']
  94. if 'message' in request.form:
  95. message = request.form['message']
  96. if 'author_id' in request.form:
  97. author_id = request.form['author_id']
  98.  
  99. db = get_db()
  100. db.execute('''update tweet set message = ?, author_id = ? WHERE tweet_id = ?''', [message, author_id, tweet_id])
  101. db.commit()
  102. return jsonify(
  103. status='success',
  104. tweet_id=tweet_id,
  105. message=message,
  106. author_id=author_id
  107. )
  108.  
  109. @app.route('/api/v1/tweet/<int:tweet_id>', methods=['DELETE'])
  110. def delete_tweet(tweet_id):
  111. tweet = query_db('''select * from tweet where tweet_id = ?''', [tweet_id], one=True)
  112. if not tweet:
  113. return jsonify(
  114. status='error',
  115. error='Tweet not found'
  116.  
  117. )
  118.  
  119. db = get_db()
  120. db.execute('''delete from tweet where tweet_id=?''', [tweet['tweet_id']])
  121. db.commit()
  122. return jsonify(
  123. status='success',
  124. tweet_id=tweet_id,
  125. )
  126.  
  127. ### Pages ###
  128. @app.route("/")
  129. def index():
  130. # TODO: check if user is logged in
  131. return render_template('index.html')
  132.  
  133. @app.route("/profile")
  134. def profile():
  135. return "Profile page"
  136.  
  137. @app.route("/login")
  138. def login():
  139. return render_template('login.html')
  140.  
  141. @app.route("/register", methods=['GET', 'POST'])
  142. def register():
  143. error = None
  144. if request.method == 'POST':
  145. if 'username' not in request.form:
  146. error = 'You must provide a username.'
  147. elif 'password' not in request.form:
  148. error = 'You must provide a password.'
  149. elif 'email' not in request.form:
  150. error = 'You must provide an email address.'
  151. else: # All fields valid
  152. db = get_db()
  153. db.execute('''insert into user (username, email, pw_hash) values (?, ?, ?)''', [
  154. request.form['username'], request.form['email'], generate_password_hash(request.form['password'])
  155. ])
  156. db.commit()
  157.  
  158. return "Successfully created user"
  159.  
  160. return error
  161.  
  162. return render_template('register.html')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement