Skip to content

Instantly share code, notes, and snippets.

@costrouc
Created January 22, 2018 14:59
Show Gist options
  • Save costrouc/82782b955bdd0f62b7c796a42b211c92 to your computer and use it in GitHub Desktop.
Save costrouc/82782b955bdd0f62b7c796a42b211c92 to your computer and use it in GitHub Desktop.
Questions Simple Python Server
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Question Example</title>
<meta name="description" content="Simple Questions Asked">
<meta name="author" content="Chris Ostrouchov">
</head>
<body>
<form id="questions">
<input type="submit" value="Submit Answers"/>
</form>
<div id="sentence"></div>
<script>
var form = document.querySelector('#questions');
function handleGetQuestions() {
fetch('/questions').then(function(response) {
return response.json()
}).then(function(data) {
let htmlString = '';
for (let question of data.data) {
htmlString += `<div><label>${question}</label><input type="text"/></div>`;
}
htmlString += '<input type="submit" value="Submit Answers" onsubmit="handlePostAnswers()">';
form.innerHTML = htmlString;
})
}
function handlePostAnswers(event) {
event.preventDefault();
let answers = [];
for (let input of document.querySelectorAll('input[type="text"]')) {
answers.push(input.value);
}
fetch('/answers', {
method: 'POST',
body: JSON.stringify({data: answers}),
headers: new Headers({'Content-Type': 'application/json'})
}).then(function(response) {
return response.json()
}).then(function(data) {
let sentence = document.querySelector('#sentence');
sentence.innerText = data.data;
})
}
form.onsubmit = handlePostAnswers;
handleGetQuestions();
</script>
</body>
</html>
import random
from flask import Flask, jsonify, request, send_from_directory
app = Flask(__name__)
APP_QUESTIONS = [
"Where were you born?",
"What is the capitol of Tennessee?",
"What is 1 + 2?"
]
def generate_sentance(answers):
# crude way to get all the words from answers
words = []
for answer in answers:
words.extend(answer.split())
# randomly pick 5 words to create sentence
sentence = []
for i in range(5):
sentence.append(random.choice(words))
return ' '.join(sentence)
@app.route('/')
def index():
return send_from_directory('./', 'index.html')
@app.route("/questions")
def questions():
return jsonify({'data': APP_QUESTIONS})
@app.route("/answers", methods=['POST'])
def answers():
data = request.get_json()
sentence = generate_sentance(data['data'])
return jsonify({'data': sentence})
if __name__ == "__main__":
app.run()
@costrouc
Copy link
Author

costrouc commented Jan 22, 2018

image of result

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment