How to send JSON data with form data using Flask - flask

I'm making a system to track entries to a sports day event and I can get the data from the form to the Python back-end but I don't know how to get the data for the event entries to the back-end too.
I have a form I've already created using Flask and WTForms and I can submit all the data relating to the user but since they can enter from just a single event all the way up to every event they are able to enter the form will have a variable number of selection fields, I want to pack this data from the selection fields into a JSON string and then have Python process it since that is very easy. My only problem is, how can I get this data into a JSON string then send it in a single request to the back-end with the other data, like first name, last name etc.
Screenshot showing the user interface of the form

from flask import jsonify
#app.route('/selects')
def selects():
selects = ['one', 'two']
return jsonify(selects)

I have the same question and found answer in this tutorial. If you already use WTForm to make the form, the content can be access via methods. This should be straightforward. https://pythonspot.com/category/pro/web/page/2/

Related

how to make list as a parameter in the [GET, POST] methods

I'm working on a data set of 'Human activity recognition using smart phones'
would like to link the data with an API using flask, which can be reflected on a web page.
so I want to create a list to take all the human body movements in the data set as a parameters in a list which If I pass it to the predict route in the flask through a web page enables the model to predict the human body activity.
Put the list in a JSON object. You can use jsonify for this.
#app.route('/get_fruits')
def get_fruits():
response = {"fruits": ["apple", "banana"]}
return jsonify(response)

How to make filtering non model data in flask-admin

I have to make dashboard like view in flask-admin that will use data retrieved from external API. I have already written a functions that get date ranges and return data from that range. I should use BaseView probably but I don't know how to actually write it to make filters work. This is example function that i have to use: charts = generate_data_for_dashboard('164', '6423FACA-FC71-489D-BF32-3A671AB747E3', '2018-03-01', '2018-09-01'). Those params should be chosen from 3 different dropdowns. So far I know only how to render views with pre coded data like this :
class DashboardView(BaseView):
kwargs = {}
#expose('/', methods=('GET',))
def statistics_charts(self):
user = current_user
company = g.company
offices = Office.query.filter_by(company_id=company.id)
self.kwargs['user'] = user
self.kwargs['company'] = company
charts = generate_data_for_dashboard('164', '6423FACA-FC71-489D-BF32-3A671AB747E3', '2018-03-01', '2018-09-01')
self.kwargs['chart1'] = charts[0]
self.kwargs['chart2'] = charts[1]
return self.render('stats/dashboard.html', **self.kwargs)
But I need some kind of form to filter it. In addition date filter dropdown should have dynamic options : current_week, last_week, current_month, last_month, last_year. Don't know where to start.
You should use WTForms to build a form. You then have to decide if you want the data to be fetched on Submit or without a reload of the page. In the former case, you can just return the fetched information on the response page in your statistics_charts view. But if you want the data to update without a reload, you'll need to use JavaScript to track the form field changes, send the AJAX request to the API, and then interpret the resulting JSON and update your dashboard graphs and tables as needed.
I have not used it, but this tutorial says you can use Dash for substantial parts of this task, while mostly writing in Python. So that could be something to check out. There is also flask_jsondash which might work for you.

Django function execution

In views, I have a function defined which is executed when the user submits the form online. After the form submission there are some database transactions that I perform and then based on the existing data in the database API's are triggered:
triggerapi():
execute API to send Email to the user and the administrator about
the submitted form
def databasetransactions():
check the data in the submitted form with the data in DB
if the last data submitted by the user is before 10 mins or more:
triggerapi()
def formsubmitted(request):
save the user input in variables
Databasetransactions()
save the data from the submitted form in the DB
In the above case, the user clicks on submit button 2 times in less than 5 milliseond duration. So 2 parallel data starts to process and both trigger Email which is not the desired behavior.
Is there a way to avoid this ? So that for a user session, the application should only accept the data once all the older data processing is completed ?
Since we are talking in pseudo-code, one way could be to use a singleton pattern for triggerapi() and return Not Allowed in case it is already istantiated.
There are multiple ways to solve this issue.
One of them would be to create a new session variable
request.session['activetransaction'] = True
This would however require you to pass request, unless it is already passed and we got a changed code portion. You can also add an instance/ class flag for it in the same way and check with it.
Another way, which might work if you need those submissions handled after the previous one, you can always add a while request.session['activetransaction']: and do the handling afterwards.
def formsubmitted(request):
if 'activetransaction' not in request.session or not request.session['activetransaction']:
request.session['activetransaction'] = True
# save the user input in variables
Databasetransactions()
# save the data from the submitted form in the DB
request.session['activetransaction'] = False
...

store a list in request.session in one view and retrieve it in another view django

I have a huge list that will be generated dynamically from a csv file in a django view, but i had a requirement to use that list in the next view, so i thought to give a try on django sessions
def import_products(request):
if request.method == 'POST':
if request.FILES:
csv_file_data = ...........
total_records = [row for row in csv_file_data]
request.session['list_data'] = total_records
# total_records is `list of lists` of length more than 150
# do some processing with the list and render the page
return render_to_response('product/import_products.html')
def do_something_with_csv_data_from_above_view(request):
data = request.session['list_data']
# do some operations with list and render the page
return render_to_response('website/product/success.html',
So as mentioned in the above, i need to use the total_records huge list in the do_something_with_csv_data_from_above_view view and delete the session by storing it in another variable
So actually how to implement/use exactly the sessions concept(i have read the django docs but could n't able to get the exact concept)
In my case,
When a user tries to upload the csv file each time, i am reading the data and storing
the data as list to session
==> Is this the right way to do so ? also i want to store the session variable in
database concept
Because the list was huge, i need to delete it for sure in the next view when i
copied it in to another variable
Am i missing anything, can anyone please implement exact code for my above scenario ?
You have two options:
Client side RESTful - This is a RESTful solution but may require a bit more work. You can retrieve the data in the first request to the client and after selecting you can send the selected rows back to the server for processing, CSV etc.
Caching: In the first request you can cache your data on the server using a django file system or memcached. In the second request use the cache key (which would be the user session key + some timestamp + whatever else) to fetch the data and store in the db.
If it's a lot of data option 2 may be better.

Huge remote source to jquery autocomplete without using database

I am working on a web app, in Django, which lets user tell their favourite movies. For the input I want to provide users a textbox with autocomplete enabled.
The list of all movies ever made is very big (18 MB) thus autocomplete has to be enabled using remote source.
To add to this, I have the constraint that I can not use a database. (Because my app is hosted on heroku and to store such data in database would cost a lot)
Right now, I have the list of all movies stored in a .py file, and I import it into my views.py. The view which handles the ajax request from autocomplete iterates over each movie in this list to filter based on the query term and returns the filtered list.
-movies.py
all_movies = [list of all movies' titles] # > 1M string elements
-views.py (handle_autocomplete() gets called whenever user changes the input in the textbox on web app)
import movies
def handle_autocomplete(request):
data = request.GET['term']
my_list = [title for title in movies.all_movies if data in title]
return HttpResponse(simplejson.dumps(my_list))
What are the disadvantages of this approach and how can I improve upon it?
Are there any libraries/ django apps which handle remote-source autocomplete ?