Skip to content

Instantly share code, notes, and snippets.

@clamytoe
Created July 24, 2018 13:43
Show Gist options
  • Save clamytoe/63124ba1da3848da6fe9bb66889359b4 to your computer and use it in GitHub Desktop.
Save clamytoe/63124ba1da3848da6fe9bb66889359b4 to your computer and use it in GitHub Desktop.
Quick proof of concept with using API Star to generate random questions.
from functools import lru_cache
from random import choice
import requests
from apistar import App, Route
@lru_cache(maxsize=1)
def get_questions():
"""Retrieve questions from online resource"""
default = ['Tell us something interesting about you.']
resource = 'https://projects.bobbelderbos.com/welcome_questions.txt'
try:
page = requests.get(resource)
except requests.exceptions.ConnectionError:
return default
if not page.ok:
return default
questions = [line for line in page.text.split('\n') if valid(line)]
return questions
def question():
"""Returns a random question"""
q = choice(get_questions())
# print(get_questions.cache_info())
return {'question': q}
def valid(line):
"""Validates the line"""
return True if line and not line.startswith('#') else False
routes = [
Route('/question', method='GET', handler=question),
]
app = App(routes=routes)
if __name__ == '__main__':
app.serve('127.0.0.1', 5000, debug=False)
name: randomizer
channels:
- conda-forge
- defaults
dependencies:
- apistar=0.5.40
- requests=2.19.1
- python=3.6.6
apistar==0.5.40
requests==2.19.1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment