Skip to content
Snippets Groups Projects
Commit f81b2a85 authored by Clancy Turlagh's avatar Clancy Turlagh
Browse files

Flask app and request python file

parent 9ece145f
No related branches found
No related tags found
No related merge requests found
# Write a python code which creates a server which guesses a number between 1 and 11, and then responds to https requests to say if they got the guess right or wrong.
# It should be a server that can handle http requests and understand json data.
import random
from flask import Flask, request, jsonify
app = Flask(__name__)
# Generate a random number between 1 and 11
secret_number = random.randint(1, 11)
@app.route('/guess', methods=['POST'])
def guess_number():
data = request.get_json()
if 'guess' not in data:
return jsonify({"error": "Please provide a 'guess' in your request"}), 400
user_guess = data['guess']
if not isinstance(user_guess, int) or user_guess < 1 or user_guess > 11:
return jsonify({"error": "Guess must be an integer between 1 and 11"}), 400
if user_guess == secret_number:
return jsonify({"result": "Correct! You guessed the right number."}), 200
else:
return jsonify({"result": "Wrong guess. Try again!"}), 200
if __name__ == '__main__':
app.run(debug=True)
import requests
import random
# The URL of your Flask app
url = "http://localhost:5000/guess"
def make_guess(guess):
# Prepare the JSON payload
payload = {"guess": guess}
# Send POST request
response = requests.post(url, json=payload)
# Print the response
print(f"Guess: {guess}")
print(f"Status Code: {response.status_code}")
print(f"Response: {response.json()}")
print()
# Make 5 random guesses
for _ in range(12):
# Generate a random guess between 1 and 11
guess = random.randint(1, 11)
make_guess(guess)
# Try an invalid guess (string instead of integer)
make_guess("invalid")
# Try an out-of-range guess
make_guess(15)
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment