Equivalent of a 'While True' loop in Flask: how to do it? - loops

Spending my evenings hobby coding a topography quiz for my daughter. Leveraging the web and Stack Overflow resources, I got an API running on https://ac1976.pythonanywhere.com/api/wereld Hit it and the server will respond with a JSON object comprised of a random country / capital combination, together with a list of 'wrong' answers for the capital. The wrong answers are based on distance to the (correct) capital and are also randomized. So Tokyo won't show up as an answer for the capital of Belgium, but Paris and London may.
On topic: now building a flask app that fetches a response from the aforementioned API, and creates a multiple choice quiz game asking for the capital of the random country, and giving the user 4 multiple choice options.
My main route to do all of this works, and looks like this:
#app.route('/api/continent/', methods=['GET', 'POST'])
def quiz():
if request.method == "GET":
quiz = Game('wereld')
country = quiz.country
answers = quiz.answers
session['capital'] = quiz.capital
return render_template('quiz.html', a1=answers[0], a2=answers[1], a3=answers[2], a4=answers[3], country=country)
else:
answer = request.form['subject']
if answer == session.get('capital'):
return render_template('antwoord.html', answer="Jaaaaa...")
else:
return render_template('antwoord.html', answer="Neee..")
So on hitting the route initially, the server initializes the class Game, which is essentially a wrapper to catch the response from the API and parcel the response with methods for each of the data points we need: country, answers, and capital. These quiz items are stored in similarly named variables country, answers and capital. Country (in the form of a question) and answers (as 4 separate buttons) are used in the HTML template file, presented on hitting the route.
If the user presses one of the four buttons, the second part of the route logic figures out whether the answer was right, or wrong, and sends back a new html view telling the user the answer was right....or wrong.
Okay. All makes sense, right?
Here's my question. How do I autodirect, after say 1 second, back to the 'top of the if loop' so that the code auto refetches a new response from the API, to play another round? I tried to put a simple "While True:" on top of the if / else loop, which works my original terminal version of this quiz...but Flask is not having it. I understand why (it needs a 'GET') but....how to cause a new one?
thanks for your thoughts / guidance / pointing me in the right direction
Arie

How about a meta refresh tag within the header of the HTML page.
After the defined time has expired, you will be redirected to the specified URL.
It would then look something like this.
<meta http-equiv="refresh" content="1; url={{url_for('quiz', _external=True)}}" />
If you want to use JavaScript, a variant with a timeout would also be possible.
const uri = {{url_for('quiz') | tojson}};
setTimeout(() => window.location.replace(uri), 1000);

Related

how to store likes data in flutter

I'm developing an app in which I need to show come "coupons" I get from the API. I also have a "liked coupons" page where I need to show the ones the user has liked. I'm facing 2 problems here:
1- I don't know how to store likes, should I implement a local database for everything or should I ask our back-end team to save the liked/not liked state on the server?
2- I have a model class for coupons, and I have a coupon_list widget which is a horizontal listview.builder(). the problem is that some coupons are being showed in 2 or 3 different lists and I need them to all turn to liked when user likes an instance from a single list. how can I do that? (I want to do something like working with pointers in c++, passing the ACTUAL variable instead of it's value so it changes globally)
I would like to suggest you to store it in server as well. (Ask to your back-end team to add parameter) So that if user logout or sign in from different device "liked coupons" data will be available in all cases.
And for 2) multiple coupon entry you have to manage it via unique id. Like every coupon has its unique series no / pattern num. So you can put condition on that. i.e. Add "unique_no" to liked_list from all available list of coupon
Solution
Use Shared Preferences! This is something like a database on the device you are currently running. So if the user makes a like you can save that on their device!
To add Shared Preferences to your app look this video
Hope it helps!

Use query string in URL or use multiple URL?

If I want to display many posts in my web application but every post have its own type and I want to display each type in single page so, What's the best method to do that? Is put all all posts in one url and use query string to filter the posts upon the type and display it in the page?
For example : axios.get('/posts?type =sport')
Or I have to put every single type in separate Url
For example: axios.get('/posts/sport')
Also one more question please?
use one reducer to manage every posts or create one reducer for each post type?
you can add a dynamic route to every new type.
Ex:
'/transaction' -> component-1
'/transaction/:type' -> component-any (multiple)
welcome to Stackoverflow!
I can imagine you have a web API of some sort serving a URL /posts. You want to consume that endpoint from your web application, and you are using axios to do that. I can assume you are using JSON to return that data. Correct me if I'm wrong.
Now that the basic information is "clear", what data you serve from the endpoint, and how it is requested from the client is up to you. Do you want to ask the server what types are there first, and then do one AJAX request per type? Ok. Do you want to serve all posts independent of their type? Ok. Do you want to accept POST data in your controller so you can filter the results before returning a response? Ok.
If you are looking for a more specific answer, you must give more details, or specify more. But I hope I could be of help.
Edit: complete answer.
If you want to filter the results, you have to send some additional data in your POST request, in this case, your post type. In axios, this could be done like this:
axios.post('https://example.com/posts', {
type: 'sports'
}).then((data) => {
console.log(data);
});
You can obviously get the "type" value from a select input, other variable, even the current router page. I don't know your exact setup, but you can always come back and ask ;)
THEN, in your API controller you have to get that POST parameter type, and use it to filter the results. Again, I don't know your exact setup, but for MySQL if would be a WHERE statement in your query, or similar.

how to validate answers for quiz app, values which is fetched from json in reactjs?

I am developing a ReactJs quiz app in which I am having problem with validating the answers that is in the json.
I did this quiz app using react version 16.8 using state components and fetched the json data and stored in state using map function I have the completed the view part, now I started to validate the quiz and I am struggling in that part.
here is the full code:https://codesandbox.io/s/mystifying-firefly-2d2x5
and also ill add my json link: http://myjson.com/kpop9
I want the answer should be validated, and if user clicks the submit button before attempting all the questions it should show that you have unanswered questions and if user clicks submit after attempting all the quiz it should display the total marks that user got.
Replying to your comment from above, here is your sandbox code slightly edited. You can submit an answer at any time and these are the alerts you should see:
When you don't select an answer: Alert with message No nulls
When answer is wrong: Alert with message wrong
When answer is correct: Alert with message correct
Here is your edited sandbox
The solution provided is only example, and should not be treated as a perfect solution, it's only to give you an idea of how this may work (you may still want to implement the bit, when after submitting the last answer, scores are calculated - for that you may want to store scores)
Explanation:
In this example I decided to add selected_answer variable in the index.js that stores currently selected answer on the form.
Next, I created setAnswer function in index.js which accepts a selected answer as parameter and sets the selected_answer in state to whatever is passed in. You are welcome to implement as many checks for the value that is passed in as you want
setAnswer function is then passed to your Answer component, so when the value is changed, it can be saved inside index.js state
Result component receives the index.js state as a prop. This allows it to have access to current question, the array of all questions and currently selected value
Inside Result component there is a validateAnswer function that is triggered when submit button is clicked. Inside that function I use the props.current_question (which is the index of a question) to extract the whole question object from your JSON file. Next I filter over the array of answers from previously created question object, and I extract the one that has is_right set to 1. Finally, I check if the props.selected_answer is empty, and display a message if so. If it isn't, I check if it equals to the value of previously extracted correct answer object. And voila!
As mentioned before, this is not the best solution, but one that works on top of your code without changing much. Please let me know if you have any further questions, but hope that helps a bit.

List in custom Alexa skills

I'm new to Alexa Skills but meanwhile I've read tons of information and tutorials.
Fortunately, I'm currently able to create my own custom skill (based on PHP) on my own server and it already works using different intents, utterances, slots etc..
Now, I want Alexa to read a list of items (I send via JSON) in PlainText but I can't find any information how to do this.
I assume there are two options (please correct me if I'm wrong):
Sending a JSON answer including one item - Alexa reads this item - the user says e.g. "next" - Alexa requests my server for the next item - my server sends the next JSON answer ... and so on.
Sending a JSON answer including all items in an array - Alexa reads each item one after another.
I'm not sure which solution is possible and how it can be solved.
So, can anyone help me on this or point me to some information?
Both ways are possible and which one to choose depends on what you are listing.
Using AMAZON.NextIntent
If a single list item include item name and some details about it, then reading out it in one go won't be a good user experience. In this case you can use AMAZON.NextIntent to handle users "next" request.
When the user asks for the list, give the first item in your response and keep a track of the item index in response sessionAttributes. You can also set a STATE attribute too, so that you can check this state in AMAZON.NextIntent handler before you give the next item.
"sessionAttributes": {
"index": 1,
"STATE": "LIST_ITEMS"
}
When the user say "next"
check whether the state is LIST_ITEMS and based on the index give the next item from your list. And in sessionAttributes increment the index
More on sessionAttributes and Response Parameters here
Now, if your items are just names then you can read it one after the other.
In both these solutions it is always good to use SSML rather than just PlainText. SSML gives you more control on how your response is spoken.
More on SSML here

Manipulating Soundcloud Stream with Chrome Extension Content Script

I am writing a Chrome extension using AngularJS to add functionality to the Soundcloud stream page. I want to allow the user to create groups of artists so that they may only see a stream with tracks/shares/playlists from that group of artists.
For example, I follow 500 artists, but I want to quickly see a stream from my favorite 10 artists or from the artists I follow that are on the same label.
I am looking for advice on how I could go about making this as seamless as possible. As of right now, my approach involves getting the tracks with the Soundcloud API and using angular's ng-repeat to display the tracks in a view injected into where the stream normally goes. I realized using the Soundcloud widget was too slow and can't be customized to resemble the native stream items, so I copy/pasted the HTML that an actual stream item uses, but obviously the waveform/comment canvas and button functionality don't work.
What are my options as far as how I can approach this? Am I going to need to write my own players that look like the native Soundcloud ones? Any suggestions would be greatly appreciated.
You should use the SoundCloud API which is very well documented.
If you have already the id's of the tracks / artist, you just have to request the url
GET
http://api.soundcloud.com/tracks/ID_OF_TRACK.json?client_id=YOUR_CLIENT_ID
to get all the informations you need about this track, like the waveform_url, and for the comments you was talking about :
GET
http://api.soundcloud.com/tracks/ID_OF_TRACK/comments.json?client_id=YOUR_CLIENT_ID
To reproduce the behaviour of the comments :
POST http://api.soundcloud.com/tracks/ID_OF_TRACK/comments.json?client_id=YOUR_CLIENT_ID
(with a body param which represents the text and a timestamp in ms since the beginnin of the song, note that you must be connected)
If you don't have the id of the track, you could also use the resolve which give you all the info about a ressource if you have only the URL :
GET
http://api.soundcloud.com/resolve.json?url=https://soundcloud.com/poldoore/pete-rock-c-l-smooth-they&client_id=YOUR_CLIENT_ID

Resources