inoreader2readwise/database/main.py

74 lines
2.6 KiB
Python
Raw Normal View History

2024-01-24 12:29:35 +01:00
from flask import Flask, jsonify, request
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///tokens.db' # Use SQLite for simplicity
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
class Token(db.Model):
id = db.Column(db.Integer, primary_key=True)
access_token = db.Column(db.String(255), nullable=False)
refresh_token = db.Column(db.String(255), nullable=False)
expiration_seconds = db.Column(db.Integer, nullable=False)
2024-01-30 07:02:03 +01:00
is_logged_in = db.Column(db.Boolean, default=True)
2024-01-24 12:29:35 +01:00
timestamp = db.Column(db.DateTime, default=datetime.utcnow)
def __repr__(self):
return f'<Token {self.id}>'
2024-01-24 13:12:45 +01:00
# Create an application context
with app.app_context():
db.create_all()
2024-01-24 12:29:35 +01:00
# API to create a new token entry
@app.route('/token', methods=['POST'])
def create_token():
data = request.get_json()
access_token = data.get('access_token')
refresh_token = data.get('refresh_token')
expiration_seconds = data.get('expiration_seconds')
2024-01-24 14:29:37 +01:00
if not access_token or not refresh_token or not expiration_seconds:
return 'Missing required fields', 400
2024-01-24 12:29:35 +01:00
new_token = Token(access_token=access_token, refresh_token=refresh_token, expiration_seconds=expiration_seconds)
db.session.add(new_token)
db.session.commit()
return ('', 204)
# API to get the latest token entry
@app.route('/token/latest', methods=['GET'])
def get_latest_token():
latest_token = Token.query.order_by(Token.timestamp.desc()).first()
if latest_token:
token_info = {
2024-01-30 07:02:03 +01:00
'id': latest_token.id,
2024-01-24 12:29:35 +01:00
'access_token': latest_token.access_token,
'refresh_token': latest_token.refresh_token,
'expiration_seconds': latest_token.expiration_seconds,
2024-01-30 07:04:44 +01:00
'is_logged_in': latest_token.is_logged_in,
2024-01-24 14:52:08 +01:00
'timestamp': int(latest_token.timestamp.timestamp())
2024-01-24 12:29:35 +01:00
}
return jsonify({'token': token_info}), 200
else:
return '', 204
2024-01-30 07:02:03 +01:00
# API to update the token based on the id
@app.route('/token/<id>', methods=['PUT'])
def update_token(id):
token = Token.query.get_or_404(id)
data = request.get_json()
token.access_token = data.get('access_token') or token.access_token
token.refresh_token = data.get('refresh_token') or token.refresh_token
token.expiration_seconds = data.get('expiration_seconds') or token.expiration_seconds
token.is_logged_in = data.get('is_logged_in')
db.session.commit()
return '', 204
2024-01-24 12:29:35 +01:00
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000, debug=True)