#app.route('/predict', methods=['GET', 'POST'])
def predict1():
# radio = 0
if request.method == 'POST':
value = request.get_json()
if(value['radioValue'] == 'word'):
radio = 0
return "ok"
elif(value['radioValue'] == 'sentence'):
radio = 1
return "ok"
else:
if(radio==0):
lists = ["my","word"]
elif(radio==1):
lists = ["my","sentence"]
return jsonify({'prediction': lists})
Hello, I am new to Flask and web development. So, here is my question, I am getting two radio button value named word and sentence. I want to pass lists = ["my","word"] if value is word else lists = ["my","sentence"].
But here jsonify() is not returning anything. So what am I doing wrong here?
Though it return lists if I declare radio variable outside if-else block as you can see I commented them out.
Also if I don't return anything inside post what I did as return "ok" it doesn't return anything even if I declare radio = 0 or 1 outside if-else block.
A short explanation will be really helpful.
If you check your debug log, you will probably see a NameError where radio is not defined. This is due to radio being a local variable, and not a session variable as you probably intended.
To store variables for further usage in Flask, you need to use sessions.
from flask import session
#app.route('/predict', methods=['GET', 'POST'])
def predict1():
if request.method == 'POST':
value = request.get_json()
if(value['radioValue'] == 'word'):
session["radio"] = 0
return "ok"
elif(value['radioValue'] == 'sentence'):
session["radio"] = 1
return "ok"
else:
if(session["radio"]==0):
lists = ["my","word"]
elif(session["radio"]==1):
lists = ["my","sentence"]
return jsonify({'prediction': lists})
Related
I have problem in try-except
The file is views.py
function 'noun_check' return nouns of the sentence that I received from contenct.para(=input)
If there is no noun in the sentence than function 'noun_check' return error
If the error occur, go to except and return(request, 'main/desktop.html'), and receive another sentence.
And If I got nouns, I return render(request, 'main/introduction.html', context). This is the way I thought.
But error occured in function 'noun_check', logic doesnt' go to except, and return render(request, 'main/introduction.html', context)
Could you explain why try-except doesn't work?
def submit(request):
if request.method == 'POST' and request.POST['input'] != '':
try:
content = Diary_content()
content.para = request.POST['diary_input']
tokenized_nouns = noun_check(content.para)
context = {'para' : content.para, 'emotions':tokenized_nouns}
return render(request, 'main/introduction.html', context)
except:
return render(request, 'main/desktop.html')
I seperate the function, and made function if error occur return False
And use temp = function(sentence) \n if temp == 0: ...
Althogh 'temp == 0' is True, logic doesn't go under 'if function'
I am running my script in Flask and to catch and print the errors on the server I have made functions that either return None if succeeded else return an error message.
The problem is I have many functions which runs one after another and uses global variable from earlier function, this makes the code unorganized. What can I do?
App.py
from flask import Flask
from main import *
app = Flask(__name__)
#app.route('/')
def main():
input = request.args.get('input')
first_response = function1(input)
if first_response is None:
second_response = function2() # no input from hereon
if second_response is None:
third_response = function3() # functions are imported from main.py
if third_response is None:
...
if ...
else ...
else:
return third_response
else:
return second_response
else:
return first_response
main.py
def function1(input):
global new_variable1
if input is valid:
new_variable1 = round(input,2)
else:
return "the value is not integer"
def function2():
global new_variable2
if new_variable1 > 8:
new_variable2 = new_variable1 / 8
else:
return "the division is not working, value is 0"
def function3():
...
This is just a demo of what's going on. The last function will return a value either side. So if everything goes right I would be able to see the right output as well as I will see error on any given function.
The code works fine, but I need better alternative to do this.
Thanks!
Ah...you have (correctly) determined that you have two things to do:
Process your data, and
Deal with errors.
So let's process the data replacing global with parameteters (and come back to the error handling in a bit). You want to do something like this.
main.py
def function1(some_number):
if some_number is valid:
return round(some_number, 2)
def function2(a_rounded_number):
if a_rounded_number > 8:
return a_rounded_number / 8
So each function should return the results of its work. Then the calling routine can just send the results of each function to the next function, like this:
app.py
# [code snipped]
result1 = function1(the_input_value)
result2 = function2(result1)
result3 = function3(result2)
But...how do we deal with unexpected or error conditions? We use exceptions, like this:
main.py
def function1(some_number):
if some_number is valid:
return round(some_number, 2)
else:
raise ValueError("some_number was not valid")
and then in the calling routine
app.py
try:
result1 = function1(some_input_value)
except (ValueError as some_exception):
return str(some_exception)
I have this Flask View which takes a POST and GET requests
Goal is to do something with the Data from the POST request
and use it for the GET request
for example this AJAX GET Request
$.getJSON({url: '/uploadajax'}).done(result =>console.log(result));
which waits to return the processed data from the POST request
I was able to pass the data to the AJAX call by
declaring the global variable result and changed it in the function
and use it as a return value for the GET Request
Question here: is there a cleaner way to perform this task ?
result = 0
# ------------upload-file-----------------------------------------#
#flask_class.route('/uploadajax', methods=['POST', 'GET'])
def receave_file():
if request.method == 'POST':
uploaded_file = request.files['file']
# filename = secure_filename(uploaded_file.filename)
if uploaded_file.filename != "":
filename = secure_filename(uploaded_file.filename)
file_ext = os.path.splitext(filename)[1] # was macht das ?
if file_ext not in Config.ALLOWED_EXTENSIONS:
abort(400)
# file kann auch net gespeichert werden
uploaded_file.save(os.path.join(flask_class.instance_path, 'uploads', filename))
# ------------------------------------- #
df = pd.read_excel(uploaded_file)
columns = df.columns.to_list()
global result
result = json.dumps(columns)
# return result
print("shoud return somehting")
# ---------------------------------------- #
return '', 204
# ---------------------------------------- #
else:
return "false"
else:
# GET REQUEST
if len(result) > 1:
return result
else:
return '', 404
# return render_template('index.html')
Yes, there is :)
Have a look at the following code:
class LocalStore:
def __call__(self, f: callable):
f.__globals__[self.__class__.__name__] = self
return f
# ------------upload-file-----------------------------------------#
#flask_class.route('/uploadajax', methods=['POST', 'GET'])
#LocalStore() # creates store for this unique method only
def receave_file():
if request.method == 'POST':
LocalStore.post_headers= request.headers
LocalStore.post_body = request.body
LocalStore.post_json = request.get_json()
LocalStore.post_params = request.params
LocalStore.answer_to_everything = 42
print("POST request stored.")
return jsonify({"response": "Thanks for your POST!"})
else:
try:
print("This is a GET request.")
print("POST headers were:", LocalStore.post_headers)
print("POST params were :", LocalStore.post_params)
print("POST body was :", LocalStore.post_body)
print("The answer is :", LocalStore.answer_to_everything)
return jsonify({"postHeadersWere": LocalStore.post_headers})
except AttributeError:
return jsonify({"response":"You have to make a POST first!"})
I created a special class which "injects" its reference into the __globals__ dictionary of the method. If you type the class name in the method, it will be the object reference, not the class reference. Be aware of that!
You then just need to add #LocalStore underneath the #app.route(...) of your application because the store needs to be routed with the method...
I think it's a quite elegant way that saves you the definition of 5 global variables for 5 different methods
I have a function ('postcode') that takes input from user and generates two variables that I want to pass to another function ('constituency').
How can I pass two arguments between function such that only one is passed to the url?
app("/postcode", methods=["GET", "POST"])
def postcode():
form = PostcodeForm()
if form.validate_on_submit():
pc = form.postcode.data.replace(" ", "").strip()
if validate(pc) == True:
code, const = dosomething(pc)
return redirect(url_for('app.constituency', const_id=const)), code
return render_template("template1.html", form=form)
#app.route("/constituency/<string:const_id>")
def constituency(const_id):
const = const_id
people = People.query.filter_by(code=code) # I want the value of "code" here to come from the function 'postcode' above
return render_template("template2.html", people=people, const=const)
You either need to pass code as a query parameter, or make a new url route that takes a code parameter, url_for doesn't calls consitutency directly, it just generates a url that the browser then requests.
I'm working on a PUT request to be able to modify data in my JSON file, using Flask and Python. The problem is it won't save the changes made.
Below is my code:
#app.route('/updated', methods = ['POST', 'PUT' 'GET'])
def update():
try:
title = request.form['title']
print title
if request.method == 'POST':
with open("articles.json", 'r+') as json_File:
articles = json.load(json_File)
for article in articles['article']:
if title == article['title']:
print article['title']
print article['author']
print article['article_id']
article['title'] = title
article['author'] = request.form['author']
article['text'] = request.form['text']
article['article_id'] = request.form['article_id']
print article
save_article = json.dumps(article, json_File)
else:
print "article could not be added"
#json_File.close()
return render_template('updated.html', save_article = save_article, article = article)
except:
print "This didn't work."
return render_template('errorHandler.html'), 404
Example from (http://blog.luisrei.com/articles/flaskrest.html)
#app.route('/echo', methods = ['GET', 'POST', 'PATCH', 'PUT', 'DELETE'])
def api_echo():
if request.method == 'GET':
return "ECHO: GET\n"
elif request.method == 'POST':
return "ECHO: POST\n"
elif request.method == 'PATCH':
return "ECHO: PACTH\n"
elif request.method == 'PUT':
return "ECHO: PUT\n"
elif request.method == 'DELETE':
return "ECHO: DELETE"
Probably best to have a if/elif/else for each method in the decorator, prevents weird bug and edge cases.
I think you should change this part:
if request.method == 'POST' or request.method == 'PUT':
For better practices, i think you should do:
if request.method == 'POST' or request.method == 'PUT':
# do your code here, which edit into your database
if request.method == 'GET':
# do GET code here, which return data from your database
Or separate your https methods into different functions
First of all, json.dumps() "dumps" to a string, not a file. So
save_article = json.dumps(article, json_File)
will return a string which is then bound to the save_article variable, but the file is not actually modified. You probably meant to use json.dump(article, json_File) which does accept a file as the second argument.
Note: The file argument is silently ignored in Python 2, which I assume that you are using because it would show up as an error in Python 3.
There might be other problems. One is that articles will be appended to the file, but it would seem that the intention of the code is to update an existing article. It's generally impractical to update text files in place. A better method would be to iterate over the articles, updating those that match the title. Then rewrite the whole file once at the end. Here's an example:
with open("articles.json", 'r') as json_File:
articles = json.load(json_File)
# update any matching articles
for article in articles['article']:
if title == article['title']:
article['author'] = request.form['author']
article['text'] = request.form['text']
article['article_id'] = request.form['article_id']
# rewrite the whole JSON file with updated dictionary
with open("articles.json", 'w') as json_File:
json.dump(articles, json_File)
As you are updating the article data you might want to consider using a simple database to manage it. You could take a look at Flask SQLAlchemy.