How to display an error message on invalid url? - python

#app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
session['link'] = request.form.get('link')
link = YouTube(session['link'])
return render_template('video.html', link=link)
return render_template('index.html')
#app.route('/download', methods=['GET', 'POST'])
def download():
if request.method == "POST":
link = YouTube(session['link'])
itag = request.form.get('itag')
video = link.streams.get_by_itag(itag)
filename = video.download()
return send_file(filename, as_attachment=True)
return redirect(url_for('index'))
if __name__ == '__main__':
app.run(debug=True)
I want my youtube downloader code to display an error message when the user enters an invalid URL or if the video is unavailable. It is showing an internal server error if the user enters an invalid URL.
After changes:
#app.route('/', methods=['GET', 'POST'])
def index():
try:
if request.method == 'POST':
session['link'] = request.form.get('link')
link = YouTube(session['link'])
return render_template('video.html', link=link)
return render_template('index.html')
except:
return redirect(url_for('index'))
Now if the user enters the invalid URL the user gets redirected to the homepage but I want to Flash error message once the user gets redirected to the homepage.

Instead of you current API call, you can use the catch method with the new Fetch method in Javascript:
fetch('https://example.com/profile', {
method: 'POST', // or 'PUT'
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});
The catch method triggers anytime when an error occurs. What you can do is specify different statements to output and check different crash criteria.
Sources:
Using Fetch

Related

Flasks logout_user() not working with React

I'm using Flask on backend and it works well when i making logout query via PostMan in browser. But the problem i met, when tried to connect it with React, which i'm using on frontend, is it returns Request failed with status code 401 ...
handleLogout.jsx
const handleLogout = async () => {
try {
let response = await PostService.userLogout()
setIsAuth(false);
sessionStorage.removeItem('access_token');
} catch (e) {
alert(e)
}
}
PostService.jsx
static async userLogout() {
const resp = await axios.get(lochost + "api/logout")
return resp.data
}
routes.py
#app.route("/api/logout", methods = ["GET"])
#login_required
def logout():
print(current_user)
logout_user()
return jsonify(msg = "Logged out successfully", status = 200)

Passing a variable with return redirect(url_for())

I have a login page that pulls the credentials from the form then uses those credentials in an API to get an authorization token. I am trying to pass that token to the /home URL to use it in other API calls but instead of passing the variable it adds it to the /home URL instead:
http://127.0.0.1:5000/home?headers=%7B%27Accept%27%3A+%27application%2Fjson%27,+%27X-AUTH-TOKEN%27%3A+%27VUw2U89iobifuyfaieubsifhoi%27%7D
#app.route('/', methods=['GET', 'POST'])
def login():
error = None
if request.method == 'POST':
query = {"username": request.form['username'], "password": request.form['password']}
response = requests.post("https://api.com/v2/authorize", json=query)
x = json.loads(response.text)
if response.status_code==201:
headers = {
'Accept': 'application/json',
'X-AUTH-TOKEN': x["authToken"]
}
return redirect(url_for('registered', headers=headers))
else:
error = 'Invalid Credentials. Please try again.'
return render_template('login.html', error=error)
#app.route("/home", methods=['GET','POST'])
def registered(headers):
return render_template('registered.html')
Is the syntax incorrect for passing this parameter or do I need to use a different method of passing it?

Flask and Ajax current_user.id returns error

Trying to make ajax POST request on Flask, everything works fine except for when anything related to current_user is involved in the ajax request.
For example:
python
#app.route("/example", methods=['POST', 'GET'])
def example():
if request.method == 'POST':
mynumber = request.form['number']
whatdoesntwork = mynumber + current_user.id
return whatdoesntwork
javascript
$(document).ready(function () {
$('.button').on('click', function () {
var myNumber = 100;
var toPost = {
number : myNumber
};
$.ajax({
type : 'POST',
url : '/example',
data : toPost,
success : function (returnValue) {
console.log(returnValue);
},
error : function() {
console.log("why doesnt it work?")
}
});
});
});
current_user.whatever does fine everywhere else in the code
for exampe:
#app.route("/example", methods=['POST', 'GET'])
def example():
flash(current_user.id, 'success)
return render_template('eg.html')
the above code will display the user id as a flash message in the webpage
However, whenever current_user.whatever is involved in the ajax request, it raises an error with error 500 displaying on the console.
First time posting on stackoverflow, sorry if the question isn't straightforward
Next time when you asking questions here, please provide your error output. But, I guess I know what's happening.
Flask-Login user ids have the type ObjectId. They look like this:
{{
$oid : 'xxxxxxxxxxxxxxxxxxxxxx'
}}
You can serialize them by simply calling str(current_user.id).
In your case:
#app.route("/example", methods=['POST', 'GET'])
def example():
if request.method == 'POST':
mynumber = request.form['number']
whatdoesntwork = mynumber + str(current_user.id)
return whatdoesntwork

Logging into an external website with flask

I'm currently having some trouble with my flask webapp, where I have written it as below, but when I try to run the flask app, I run into a Bad Request Error. (The browser (or proxy) sent a request that this server could not understand)
Essentially, I am trying to allow users to log in to an external website through the flask webapp
What is the cause of this error? Apologies if I am making a stupid mistake, I'm very new to flask.
from flask import Flask,render_template, request, redirect
import requests
from bs4 import BeautifulSoup as bs
app = Flask(__name__)
#app.route('/', methods = ["POST", "GET"])
def login():
username = request.form['username']
pin = request.form['password']
s = requests.Session()
r = s.get("https://www.example.com/User/Login")
soup = bs(r.text, 'html.parser')
loginToken = soup.findAll(attrs={"name" : "__RequestVerificationToken"})[0]['value']
#Create Login Payload
login_payload = {
"__RequestVerificationToken" : loginToken,
"UserName" : username,
"Password" : pin,
"returnUrl" : "https://example.com/user-action/?action=login&returnUrl=https://www.example.com/User/Information",
}
#Post Login Payload
r = s.post("https://www.example.com/Account/Login", data = login_payload)
if r.status_code == 200:
return render_template('home.html')
else:
return render_template('login.html')
return render_template('login.html')
#app.route('/home') #If login works, redirect to this page
def hello_world():
return 'Hello, World!'
if __name__ == "__main__":
app.run(debug = True)
In addition, if there are other resources that I could refer to with regards to allowing a user to log in to a external URL from the flask webapp as compared to the conventional tutorials that only show a user logging in to the flask webapp itself, do share it with me, thank you!
Your endpoint' s has two Http verbs ["POST", "GET"]. You should specify your methods as below.
#app.route('/', methods = ["POST", "GET"])
def login():
if request.method == "GET":
#something do stuff
return render_template("your_html_page")
if request.method == "POST":
#something do stuff
return your_response, 200
Edited Block
#app.route('/', methods = ["POST", "GET"])
def login():
if request.method == "GET":
return render_template('login.html')
if request.method == "POST":
#same logic here
if status_code == 200:
return redirect(url_for('home'))
return render_template('login.html')

How to accept FormData sent via ajax in Flask?

I'm trying to send an image file in a FormData using an Ajax POST request.
I am faced with 2 problems:
I do not know how to extract the FormData on the flask part
I 500 internal server error when making an ajax POST request (not sure if this is because of 1)
Thank you
Flask python code:
#app.route('/', methods=['GET','POST'])
def upload_file():
if request.method == 'POST':
file = request.files['file']
if file: # and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(os.getcwd()+"/static", "current_image.jpg"))
return jsonify({'tasks': tasks})
HTML and Javascript code:
<input id="pictureInput" type=file name=file>
<input type=submit value=Upload id="button">
<script type="text/javascript">
var pictureInput = document.getElementById("pictureInput");
var myFormData = new FormData();
myFormData.append('pictureFile', pictureInput.files[0]);
$("#button").click(function(){
console.log(pictureInput);
console.log(pictureInput.files[0]);
console.log(myFormData);
$.ajax({
url: "http://localhost:8000/",
type: 'POST',
processData: false, // important
contentType: false, // important
dataType : 'json',
data: myFormData,
success : function(data){
console.log(data);
},
});
});
</script>
Error:
The following code should work for you. You need to have the static folder in the same level as your app.py file
app.py
import os
from flask import Flask, request, jsonify
from werkzeug.utils import secure_filename
app = Flask(__name__)
#app.route('/', methods=['GET','POST'])
def upload_file():
if request.method == 'POST':
file = request.files['file']
if file:
filename = secure_filename(file.filename)
file.save(os.path.join(os.getcwd()+"/static", "current_image.jpg"))
tasks = []
return jsonify({'tasks': tasks})
if __name__ == "__main__":
app.run(host='0.0.0.0', debug=True)
tasks is not defined above in your code, so I just initialized it to an empty list. You need also to make sure that jQuery is loaded in your template.
1. I do not know how to extract the FormData on the flask part
In order to extract the fomrdata, you could write the following code
#app.route('/', methods=['GET','POST'])
def upload_file():
if request.method == 'POST':
file = request.files['pictureFile'] # according to the name you append to formdata
2. I 500 internal server error when making an ajax POST request (not sure if this is because of 1)
Actaully, if the file is not be found, there is no correct response, so it will not work correctly.
You could reference the following sample code
#app.route('/', methods=['GET','POST'])
def upload_file():
if request.method == 'POST':
isSuccess = False
if 'file' not in request.files:
return jsonify({"IsSuccess" : isSuccess, "Message": "No file part"})
file = request.files['pictureFile'] # according to the name you append to formdata
if file: # and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(os.getcwd(), "static", "current_image.jpg"))
isSuccess = True
tasks = []
return jsonify({"IsSuccess" : isSuccess, "tasks": tasks})
return jsonify({"IsSuccess" : isSuccess, "Message": "Error occurs"})

Categories

Resources