Add random, amnesiac method #10

Merged
tyler merged 3 commits from memecount-random-meme into master 2023-02-24 16:42:02 +00:00
3 changed files with 71 additions and 2 deletions

View File

@ -1,6 +1,7 @@
from flask_restx import Api
from .search import api as searchNamespace
from .get import api as getNamespace
from .util import api as utilNamespace
api = Api(
title='Memes',
@ -10,3 +11,4 @@ api = Api(
api.add_namespace(searchNamespace)
api.add_namespace(getNamespace)
api.add_namespace(utilNamespace)

View File

@ -3,12 +3,13 @@ from flask_restx import reqparse
from flask import make_response
from api.clientGetter import getClientSafely
import logging
import random
# Exported namespace
api = Namespace('resource', description='Interact with the raw underlying resource')
api = Namespace('resource', description='Interact with the raw underlying files. This namespace does NOT speak json, just raw files')
@api.route('/exact/<string:file_name>')
@api.doc(description="Returns the raw file. This endpoint expects exact files, NOT json")
@api.doc(description="Interact with exact raw files.")
class getExactFile(Resource):
@api.doc('get')
@api.response(200, 'Sucess')
@ -26,3 +27,47 @@ class getExactFile(Resource):
return {
"message": "Requested file '" + file_name + "' not found"
}, 404
@api.route('/random')
@api.doc(description="Returns a random meme")
class getRandomFile(Resource):
@api.doc('get')
@api.response(200, 'Sucess')
@api.response(500, 'S3 Error')
def get(self):
client = getClientSafely()
if client is None:
return {
"message" : "Error connecting to S3"
}, 500
choice = random.choice(tuple(client.getCurrentMemeList()))
return make_response(client.getMeme(choice))
@api.route('/psuedorandom')
@api.doc(description="Returns a psuedorandom meme. Will not return the same meme for a set number of requests")
class getRandomFile(Resource):
cache = []
maxSize = 100
@api.doc('get')
@api.response(200, 'Sucess')
@api.response(500, 'S3 Error')
def get(self):
client = getClientSafely()
if client is None:
return {
"message" : "Error connecting to S3"
}, 500
choice = random.choice(tuple(client.getCurrentMemeList()))
while choice in self.cache:
choice = random.choice(tuple(client.getCurrentMemeList()))
self.cache.append(choice)
if len(self.cache) > self.maxSize:
self.cache.pop()
logging.debug("Contents of cache : " + str(self.cache))
return make_response(client.getMeme(choice))

22
src/api/util.py Normal file
View File

@ -0,0 +1,22 @@
from flask_restx import Namespace, Resource, fields
from flask_restx import reqparse
from api.clientGetter import getClientSafely
import logging
# Exported namespace
api = Namespace('util', description='Misc Utilities')
@api.route('/count')
@api.doc(description="Get number of memes in store")
class getCount(Resource):
def get(self):
client = getClientSafely()
if client is None:
return {
"message": "Error connecting to S3"
}, 500
return {
"count" : len(client.getCurrentMemeList())
}, 200