Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from flask import Flask, render_template, g, request, jsonify
- from werkzeug import check_password_hash, generate_password_hash
- import sqlite3
- app = Flask(__name__)
- ### Database stuff ###
- def get_db():
- db = getattr(g, '_database', None)
- if db is None:
- db = g._database = connect_to_database()
- return db
- def connect_to_database():
- conn = sqlite3.connect('db.sqlite3')
- conn.row_factory = sqlite3.Row
- return conn
- def init_db():
- db = get_db()
- with app.open_resource('schema.sql', mode='r') as f:
- db.cursor().executescript(f.read())
- db.commit()
- def query_db(query, args=(), one=False):
- """Queries the database and returns a list of dictionaries."""
- cur = get_db().execute(query, args)
- rv = cur.fetchall()
- return (rv[0] if rv else None) if one else rv
- @app.teardown_appcontext
- def close_database(exception):
- if hasattr(g, '_database'):
- g._database.close()
- @app.cli.command('initdb')
- def init_db_command():
- init_db()
- print('Initialized the database.')
- ### API ###
- @app.route('/api/v1/tweet/', methods=['POST'])
- def create_tweet():
- error = None
- if 'message' not in request.form:
- error = 'You must provide a message.'
- elif 'author_id' not in request.form:
- error = 'You must provide an author ID'
- if error:
- return jsonify(
- status='error',
- error=error
- )
- db = get_db()
- db.execute('''insert into tweet (message, author_id) values (?, ?)''', [request.form['message'], request.form['author_id']])
- db.commit()
- return jsonify(
- status='success'
- )
- @app.route('/api/v1/tweet/<int:tweet_id>', methods=['GET'])
- def get_tweet(tweet_id):
- tweet = query_db('''select * from tweet where tweet_id = ?''', [tweet_id], one=True)
- if not tweet:
- return jsonify(
- status='error',
- error='Tweet not found'
- )
- return jsonify(
- status='success',
- tweet_id=tweet_id,
- message=tweet['message'],
- author_id=tweet['author_id']
- )
- @app.route('/api/v1/tweet/<int:tweet_id>', methods=['PUT'])
- def update_tweet(tweet_id):
- tweet = query_db('''select * from tweet where tweet_id = ?''', [tweet_id], one=True)
- if not tweet:
- return jsonify(
- status='error',
- error='Tweet not found'
- )
- message = tweet['message']
- author_id = tweet['author_id']
- if 'message' in request.form:
- message = request.form['message']
- if 'author_id' in request.form:
- author_id = request.form['author_id']
- db = get_db()
- db.execute('''update tweet set message = ?, author_id = ? WHERE tweet_id = ?''', [message, author_id, tweet_id])
- db.commit()
- return jsonify(
- status='success',
- tweet_id=tweet_id,
- message=message,
- author_id=author_id
- )
- @app.route('/api/v1/tweet/<int:tweet_id>', methods=['DELETE'])
- def delete_tweet(tweet_id):
- tweet = query_db('''select * from tweet where tweet_id = ?''', [tweet_id], one=True)
- if not tweet:
- return jsonify(
- status='error',
- error='Tweet not found'
- )
- db = get_db()
- db.execute('''delete from tweet where tweet_id=?''', [tweet['tweet_id']])
- db.commit()
- return jsonify(
- status='success',
- tweet_id=tweet_id,
- )
- ### Pages ###
- @app.route("/")
- def index():
- # TODO: check if user is logged in
- return render_template('index.html')
- @app.route("/profile")
- def profile():
- return "Profile page"
- @app.route("/login")
- def login():
- return render_template('login.html')
- @app.route("/register", methods=['GET', 'POST'])
- def register():
- error = None
- if request.method == 'POST':
- if 'username' not in request.form:
- error = 'You must provide a username.'
- elif 'password' not in request.form:
- error = 'You must provide a password.'
- elif 'email' not in request.form:
- error = 'You must provide an email address.'
- else: # All fields valid
- db = get_db()
- db.execute('''insert into user (username, email, pw_hash) values (?, ?, ?)''', [
- request.form['username'], request.form['email'], generate_password_hash(request.form['password'])
- ])
- db.commit()
- return "Successfully created user"
- return error
- return render_template('register.html')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement