You can download this code by clicking the button below.
This code is now available for download.
This function creates a Flask application that uses Flask-SQLAlchemy to randomly query a user from an SQLite database and returns the user's ID, username, and email. If there are no users in the database or an error occurs during the query, an error message will be returned.
Technology Stack : Flask, Flask-SQLAlchemy, SQLite
Code Type : Flask API Function
Code Difficulty : Intermediate
from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
import random
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///example.db'
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
def get_random_user():
try:
user = User.query.order_by(random.random()).first()
if user:
return jsonify({"id": user.id, "username": user.username, "email": user.email})
else:
return jsonify({"error": "No user found"}), 404
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route('/random_user', methods=['GET'])
def random_user():
return get_random_user()
if __name__ == '__main__':
app.run(debug=True)