![]() |
Questions about the GET and POST submission form Functions in Python for a Trivia Gam - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Homework (https://python-forum.io/forum-9.html) +--- Thread: Questions about the GET and POST submission form Functions in Python for a Trivia Gam (/thread-12004.html) |
Questions about the GET and POST submission form Functions in Python for a Trivia Gam - martin28 - Aug-04-2018 Hey guys! I'm Martin and I'm new to the forum. I was wondering if you could answer my question and possibly solve it for me because I'm really getting depressed over not being able to do it. I'm taking a software development course at the moment and I'm stuck on a Python related assignment. Any and all help would be amazing. Let me explain my problem: I'm building a trivia game using Python for an assignment. It's being built with a Flask application so that I can open my Python/HTML in a browser (make it more user friendly). My quiz is a multiple choice question quiz, however, I need to create it using a submission form style of answering, not a multiple choice button. I'm using a template I found online for now until I understand the full in and outs but I need to ask: How do I use the GET and POST functions to allow a user to answer the question in a form in the browser and send their answer through my Python logic (the if or else statements) to send them back either a correct or incorrect response? To clarify, what I would like to be able to do with the code below is get rid of my multiple choice answer system and instead have a system where the user can submit their answer through a form and the logic will return them with a correct/incorrect answer. I'm not plagiarising this code for my assignment, I'm simply using it as a template to trying and explain myself better. Thanks. from flask import Flask, render_template, request import random, copy app = Flask(__name__) original_questions = { #Format is 'question':[options] 'Taj Mahal':['Agra','New Delhi','Mumbai','Chennai'], 'Great Wall of China':['China','Beijing','Shanghai','Tianjin'], 'Petra':['Ma\'an Governorate','Amman','Zarqa','Jerash'], 'Machu Picchu':['Cuzco Region','Lima','Piura','Tacna'], 'Egypt Pyramids':['Giza','Suez','Luxor','Tanta'], 'Colosseum':['Rome','Milan','Bari','Bologna'], 'Christ the Redeemer':['Rio de Janeiro','Natal','Olinda','Betim'] } questions = copy.deepcopy(original_questions) def shuffle(q): """ This function is for shuffling the dictionary elements. """ selected_keys = [] i = 0 while i < len(q): current_selection = random.choice(q.keys()) if current_selection not in selected_keys: selected_keys.append(current_selection) i = i+1 return selected_keys @app.route('/') def quiz(): questions_shuffled = shuffle(questions) for i in questions.keys(): random.shuffle(questions[i]) return render_template('main.html', q = questions_shuffled, o = questions) @app.route('/quiz', methods=['POST']) def quiz_answers(): correct = 0 for i in questions.keys(): answered = request.form[i] if original_questions[i][0] == answered: correct = correct+1 return '<h1>Correct Answers: <u>'+str(correct)+'</u></h1>' if __name__ == '__main__': app.run(debug=True)<html> <h1>7 Wonders of the World</h1> <form action='/quiz' method='POST'> <ol> {% for i in q %} <li>Where is <u>{{i}}</u> located?</li> {% for j in o[i] %} <input type='radio' value='{{j}}' name='{{i}}' />{{j}} {% endfor %} {% endfor %} </ol> <input type="submit" value="submit" /> </form> </html> EDIT ----- Sincerest apologies, I'm not sure how the indent works on this forum. Apologies again. RE: Questions about the GET and POST submission form Functions in Python for a Trivia Gam - martin28 - Aug-04-2018 Just read the rules for this part of the forum and, again, I would like to clarify that I am NOT plagiarizing the code above for my assignment. The code above is not my work and I take no credit for it. Here's a link for the source which I credit fully with creating the code above (http://radiusofcircle.blogspot.com/2016/03/making-quiz-website-with-python.html). Also, please let me specify that I do not wish anybody to do my work for me, I simply hope that somebody can demonstrate to me, even through a separate example, how I can incorporate Python logic into my HTML and send and return information between both parts. It's something which I really can't get my head around and I just really need a demonstration. RE: Questions about the GET and POST submission form Functions in Python for a Trivia Gam - snippsat - Aug-05-2018 (Aug-04-2018, 10:22 PM)martin28 Wrote: It's something which I really can't get my head around and I just really need a demonstration.You should start with more basic stuff like understanding how to get values from radio-button in POST with a more simpel setup. Here is some fixes so you at least get a choice back when submit. Also fix so it work Python 3.6 -->(as you should use) and indentation fix PEP-8. from flask import Flask, render_template, request import random import copy app = Flask(__name__) original_questions = { # Format is 'question':[options] 'Taj Mahal': ['Agra', 'New Delhi', 'Mumbai', 'Chennai'], 'Great Wall of China': ['China', 'Beijing', 'Shanghai', 'Tianjin'], 'Petra': ['Ma\'an Governorate', 'Amman', 'Zarqa', 'Jerash'], 'Machu Picchu': ['Cuzco Region', 'Lima', 'Piura', 'Tacna'], 'Egypt Pyramids': ['Giza', 'Suez', 'Luxor', 'Tanta'], 'Colosseum': ['Rome', 'Milan', 'Bari', 'Bologna'], 'Christ the Redeemer': ['Rio de Janeiro', 'Natal', 'Olinda', 'Betim'] } questions = copy.deepcopy(original_questions) def shuffle(q): """ This function is for shuffling the dictionary elements. """ selected_keys = [] i = 0 while i < len(q): current_selection = random.choice(list(q.keys())) # Python 3 add list if current_selection not in selected_keys: selected_keys.append(current_selection) i = i + 1 return selected_keys @app.route('/') def quiz(): questions_shuffled = shuffle(questions) for i in questions.keys(): random.shuffle(questions[i]) return render_template('main.html', q=questions_shuffled, o=questions) @app.route('/quiz', methods=['POST']) def quiz_answers(): correct = 0 # Now will choice from radio-button work answered = request.form['option'] return f'<h1>Correct Answers: <u>{answered}</u></h1>' if __name__ == '__main__': app.run(debug=True) <html> <h1>7 Wonders of the World</h1> <form action='/quiz' method='POST'> <ol> {% for i in q %} <li>Where is <u>{{i}}</u> located?</li> {% for j in o[i] %} <!-- add name as option --> <input type='radio' name='option' value='{{j}}' id='{{i}}' />{{j}} {% endfor %} {% endfor %} </ol> <input type="submit" value="submit" /> </form> </html> RE: Questions about the GET and POST submission form Functions in Python for a Trivia Gam - martin28 - Aug-05-2018 Thank you! Could you possibly give me more basic examples of how I can use the POST function so I can send and retrieve answers between the HTNL and Python pages? I'm confusing myself with this code I've provided and I feel like this whole problem is more straightforward than I'm making it out to be. The only example of POST and GET I was ever taught was the submission form for contact forms on website pages, and I have no idea how the logic is used in those forms. RE: Questions about the GET and POST submission form Functions in Python for a Trivia Gam - snippsat - Aug-05-2018 A more basic example. # app.py from flask import Flask, render_template, request, redirect, url_for app = Flask(__name__) @app.route('/') def quiz(): return render_template('index.html') @app.route('/python') def python(): '''Example of redirect''' return "<h1 style='color:blue;text-align: center;'>You're the boss</h1>" @app.route('/quiz', methods=['POST']) def quiz_answers(): answer = request.form['option'] # print(answer) if answer in ['C++', 'Java']: return f"<h1><u>{answer}</u> This can't be right try again</h1>" if answer == 'Python': return redirect(url_for('python')) if __name__ == '__main__': app.run(debug=True) # index.html <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Page Title</title> </head> <body> <form action='/quiz' method='POST'> <p>Please select your preferred language:</p> <div> <input type="radio" id="choice1" name="option" value="C++"> <label for="choice1">C++</label> <input type="radio" id="choice2" name="option" value="Python"> <label for="choice2">Python</label> <input type="radio" id="choice3" name="option" value="Java"> <label for="choice3">Java</label> </div> <div> <button type="submit">Submit</button> </div> </form> </body> </html>So From POST getting value back eg Python. Then on server side do something based on value from POST,then send it back to client side(Browser). RE: Questions about the GET and POST submission form Functions in Python for a Trivia Gam - martin28 - Aug-05-2018 Hey! Thanks so much. I won't bother you again, but can you show me what this looks like using a submission form style, just so I have a reference point for what I'm aiming for? RE: Questions about the GET and POST submission form Functions in Python for a Trivia Gam - snippsat - Aug-05-2018 <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Page Title</title> </head> <body> <p>Please select your preferred language</p> <ul> <li>C++</li> <li>Python</li> <li>Java</li> </ul> <form action="/quiz" method='POST'> Language: <br> <input type="text" name="language" value=""> <br> <br> <input type="submit" value="Submit"> </form> </body> </html>Change this line in app.py: answer = request.form['language'] RE: Questions about the GET and POST submission form Functions in Python for a Trivia Gam - martin28 - Aug-05-2018 Thank you so much! I just ask: I'm getting an error on this line: return f"<h1><u>{answer}</u> This can't be right try again</h1>"Is the f a typo or did I do something wrong. Apologies again, I don't mean to contradict you and you've been an amazing help, but I just wanna get this right. Oh crap! Now I'm getting a "The requested URL /quiz was not found on this server" when I type I submit. RE: Questions about the GET and POST submission form Functions in Python for a Trivia Gam - snippsat - Aug-05-2018 (Aug-05-2018, 05:12 PM)martin28 Wrote: Is the f a typo or did I do something wrong.It's string formatting f-string you need Python 3.6 or 3.7 as you should use. Can use this for earlier versions. return "<h1><u>{}</u> This can't be right try again</h1>".format(answer) Quote:Oh crap! Now I'm getting a "The requested URL /quiz was not found on this server" when I type I submit.Copy code as it are. Folder setup. foo\ |-- app.py templates\ |-- index.htmlRun python app.py In browser address over.
|