I'm setting a new server in Flask for an API. And a server to render the frontend in Flask also. Ok, so when i make a request to a determine API route i get this strange response 'This page was not found'. I it really seems to be every thing ok how can i debug this bug? Other Strange thing is that it allways give me status 200 OK. The error is in the route: #app.route('/v1.0/aluno/update/', methods=['POST'])
API SIDE
#app.route('/v1.0/aluno/<int:aluno_id>', methods=['GET'])
def aluno(aluno_id):
if request.method == 'GET':
cur = mysql.connection.cursor()
query = "SELECT NOME, NUMERO, PASSWORD FROM aluno WHERE NUMERO=%s"
cur.execute(query, (aluno_id,))
data = cur.fetchall()
if len(data) <= 0:
return Response(status=404)
else:
aluno = {
'nome': data[0][0],
'numero': data[0][1],
'password': data[0][2]
}
js = json.dumps(aluno)
resp = Response(js, status=200, mimetype='application/json')
resp.headers['Links'] = 'http://127.0.0.1/aluno'
return resp
#app.route('/v1.0/aluno/delete/<int:aluno_id>', methods=['POST'])
def aluno_delete(aluno_id):
if request.method == 'POST' and request.form['_method'] == 'delete':
query = "DELETE FROM aluno WHERE NUMERO = %s"
cur = mysql.connection.cursor()
cur.execute(query, (aluno_id,))
mysql.connection.commit()
cur.fetchall()
cur.close()
return Response(status=200)
#app.route('/v1.0/aluno/update/<int:aluno_id>', methods=['POST'])
def aluno_update(aluno_id):
form = AlunoForm(request.form)
if request.method == 'POST' and form.validate():
nome = request.form["nome"]
numero = request.form["numero"]
password = request.form["password"]
cur = mysql.connection.cursor()
query = "UPDATE aluno SET NOME=%s, NUMERO=%s, PASSWORD=%s WHERE NUMERO = %s"
cur.execute(query, (nome, numero, password, aluno_id))
mysql.connection.commit()
cur.execute(
"SELECT NOME, NUMERO FROM aluno WHERE NUMERO = %s", (aluno_id,))
data = cur.fetchall()
cur.close()
print(" * DATA ")
print(data)
aluno = {
'nome': data[0][0],
'numero': data[0][1]
}
js = json.dumps(aluno)
resp = Response(js, status=200, mimetype='application/json')
resp.headers['Links'] = 'http://127.0.0.1/aluno'
return resp
elif request.method == 'POST' and not form.validate():
resp = Response(status=400)
resp.headers['Links'] = 'http://127.0.0.1/aluno'
return resp
FRONT-END SIDE
{% endblock %}
<script type="text/javascript" src="{{url_for('static', filename='js/jquery-3.2.1.min.js') }}"></script>
<script type="text/javascript" src="{{url_for('static', filename = 'js/bootstrap.min.js')}}"></script>
<script>
function aluno_update(){
try{
let formElement = document.getElementById("aluno_update")
//let formData = formElement.
//console.log(formData)
$.ajax({
type: "POST",
url: "http://127.0.0.1:80/v1.0/aluno/update/{{aluno['numero']}}",
data: {'nome': 'João Luis','numero':'16172','password':'Password'},
//dataType: 'json',
success: function(data){
//location.href = "http://127.0.0.1:3000/v1.0/alunos/"
alert(data)
console.log(data)
},
error(jqXHR,JQueryXHR,errorThrown){
//console.log(formData)
alert(jqXHR)
alert(JQueryXHR)
alert(errorThrown)
console.log(jqXHR)
console.log(JQueryXHR)
console.log(errorThrown)
}
})
}catch(err){
alert(err)
}
}
</script>
I have tried using POSTMAN instead of the regular web browser. To make the request to the API. But i get the same response: 'This page was not found'
At least i was expecting some sort of 400 Bad Request or something like that.
https://github.com/joaogracio/SqlParser
Form validation fails and you get 400 according to the code below
elif request.method == 'POST' and not form.validate():
resp = Response(status=400)
resp.headers['Links'] = 'http://127.0.0.1/aluno'
return resp
Related
I am trying to send 2 params to the backend through a get request that returns some query based on the params I send to the backend. I am using React.js front end and flask python backend.
My get request looks like this:
async function getStatsData() {
const req = axios.get('http://127.0.0.1:5000/stat/', {
params: {
user: 0,
flashcard_id: 1
},
headers: {'Access-Control-Allow-Origin': '*', 'X-Requested-With': 'XMLHttpRequest'},
})
const res = await req;
return res.data.results.map((statsItem, index) => {
return {
stat1: statsItem.stat1,
stat2: statsItem.stat2,
stat3: statsItem.stat3,
stat4: statsItem.user,
key: statsItem.key
}
})
}
and then my route in the backend is this:
#app.route('/stat/<user>/<flashcard_id>', methods=['GET', 'POST', 'OPTIONS'])
def stats(user, flashcard_id):
def get_total_percent_correct(user):
correct = d.db_query('SELECT COUNT(*) FROM cards.responses WHERE guess = answer AND user_id = %s' % user)[0][0]
total = d.db_query('SELECT COUNT(*) FROM cards.responses WHERE user_id = %s' % user)[0][0]
try:
return round(float(correct)/float(total),3)*100
except:
print('0')
def get_percent_correct_for_flashcard(user,flashcard_id):
total = d.db_query('SELECT COUNT(*) FROM cards.responses WHERE user_id = %s AND flashcard_id = %s' % (user, flashcard_id))[0][0]
correct = d.db_query('SELECT COUNT(*) FROM cards.responses WHERE flashcard_id = %s AND guess = answer AND user_id = %s' % (flashcard_id, user))[0][0]
try:
return round(float(correct)/float(total),3)*100
except:
print('0')
def get_stats_for_flashcard(user_id, flashcard_id):
attempts = d.db_query('SELECT COUNT(*) FROM cards.responses WHERE user_id = %s AND flashcard_id = %s' % (user_id, flashcard_id))[0][0]
correct = d.db_query('SELECT COUNT(*) FROM cards.responses WHERE flashcard_id = %s AND guess = answer AND user_id = %s' % (flashcard_id, user_id))[0][0]
missed = attempts - correct
return attempts, correct, missed
data = [{
"stat1": get_total_percent_correct(user),
"stat2": get_percent_correct_for_flashcard(user, flashcard_id),
'stat3': get_stats_for_flashcard(user, flashcard_id),
'user': user,
'key':999
}]
return {"response_code" : 200, "results" : data}
When I go to http://127.0.0.1:5000/stat/0/1 in my browser, the stats are shown correctly but the get request is not working because it says xhr.js:210 GET http://127.0.0.1:5000/stat/?user=0&flashcard_id=1 404 (NOT FOUND) . So clearly I'm not sending or receiving the params correctly. Does anyone know how to solve this? Thank you for your time
In your backend route you are expecting the values in url as dynamic segment, but from axios you are sending it as query sring.
Solution:
You can modify the axios request like this to send the values as dynamic segment:
const user = 0;
const flashcard_id = 1;
const req = axios.get(`http://127.0.0.1:5000/stat/${user}/${flashcard_id}`,{
headers: {'Access-Control-Allow-Origin': '*', 'X-Requested-With': 'XMLHttpRequest'},
})
or you can modify flask route like this if you need to recieve values from query params:
from flask import request
#app.route('/stat/', methods=['GET', 'POST', 'OPTIONS'])
def stats():
user = request.args.get('user')
flashcard_id = request.args.get('flashcard_id')
Send the parameters like this:
const req = axios.get(`http://127.0.0.1:5000/stat/${user}/${flashcard_id}`)
and in Flask you receive the parameters like this:
#app.route('/stat/<user>/<flashcard_id>', methods=['GET', 'POST', 'OPTIONS'])
def stats(user, flashcard_id):
I have a profile method and a profile.html template.
profile.html has a drop-down list of user e-mails. When I select one of them, a modal window appears with this email, and I can send a message to it. I get it via AJAX.
The problem is that born_date and phone_number of this user, which I get from the database are not rendered into a template, and I can not see them in modal window, but I can get them in the console.
def str_value_to_list(text: str):
*_, email_json = re.findall(r'[^ \',()]+', text)
return email_json
#profile page method
#app.route('/profile', methods=['GET','POST'])
def profile():
if request.method == 'GET' and 'loggedin' in session:
cur = mysql.connection.cursor()
cur.execute("SELECT firstname, lastname, email FROM users.data WHERE description = 'doctor'")
account = cur.fetchall()
description = account
countries = ['USA','France','Italy','Spain','Australia','New Zealand']
cur = mysql.connection.cursor()
cur.execute("SELECT born_date, phone_number FROM users.data WHERE email = '%s'" % (dtx, ))
account = cur.fetchone()
born = account[0]
num = account[1]
print(born)
print(num)
return render_template(
'profile.html',
id = session['id'],
email = session['email'],
firstname = session['firstname'],
description = description,
countries = countries,
born=born,
num=num
)
#app.route('/api/get_data', methods=['POST'])
def get_data():
if request.method == 'POST':
print('Holy Shit!')
data = request.json
print(str_value_to_list(data['selectedItems'][0]))
cur = mysql.connection.cursor()
cur.execute("SELECT born_date, phone_number FROM users.data WHERE email = '%s'" % str_value_to_list(data['selectedItems'][0]))
account = cur.fetchone()
born = account[0]
num = account[1]
print(born)
print(num)
return jsonify({
'born': born,
'num': num,
})
html
<script type="text/javascript">
function printValue(selectedItem) {
$('#mySelectedValue').html(selectedItem.value);
}
</script>
<h2 class="white-text" style="font-size: 14px; color: #000;">born: {{ born }}</h2>
<h2 class="white-text" style="font-size: 14px; color: #000;">num: {{ num }}</h2>
<script type="text/javascript">
function printValue(selectedItem) {
$('#mySelectedValue').html(selectedItem.value.replace(/[{()}]/g, '').replace(/['"]+/g, '').replace(/[{,}]/g, ''));
console.log(selectedItem.value);
}
function process(selectedItem) {
$('#exampleModalCenter').modal('show')
document.getElementById('#exampleModalCenter')
const data = JSON.stringify({
"selectedItems": $('#sel').val()
});
$.ajax({
url: "/profile",
type: "POST",
contentType: "application/json",
data: data,
success: function (data) {
console.log(data);
},
});
}
function optionClick(selectedItem) {
printValue(selectedItem);
}
</script>
Per your code, you should use Javascript to update the born and num variable inside your Ajax success funtion:
$.ajax({
url: "/api/get_data",
type: "POST",
contentType: "application/json",
data: data,
success: function (data) {
h2 = document.querySelectorAll('.white-text')
h2[0].innerText = `born: ${data.born}`
h2[1].innerText = `num: ${data.num}`
},
});
You didn't put variable born, num in the render_template function, so you are not able to render it using {{ var }}
I suspect it has something got to do with refresh token. Could not understand how to use it by the docs. Can I know the exact code how to use it?
The access token is created during login:
#app.route('/login', methods=['POST','GET'])
def login():
username = request.form["email"]
password = request.form["password"]
my_token_expiry_time = datetime.timedelta(seconds=60)
segments = 0
access_token = None
if request.method == 'POST':
result_set = authenticate_user(username, password)
if result_set:
ss1 = select([nsettings]).\
where(nsettings.c.mattribute == 'my_jwt_expiry_time_min')
rss1 = g.conn.execute(ss1)
if rss1.rowcount > 0:
for r in rss1:
my_token_expiry_time = datetime.timedelta(seconds=
(int(r[nsettings.c.mvalue])* 60))
else:
my_token_expiry_time = datetime.timedelta(
seconds=(2 * 60 *60)) # 2 hours
#print result_set, 'result_set result_set'
session['email'] = result_set['email']
access_token = create_access_token(
identity=username, expires_delta=my_token_expiry_time)
user_dict = result_set
if user_dict:
session['email'] = user_dict['email']
session['id'] = result_set['id']
# users and related views
session['access_token'] = access_token
print access_token, 'aaaaaaaaaaa'
return jsonify({
'email': session['email'],
'user_id': result_set['id'],
'access_token': access_token,
'id': session['id'],
}), 200
else:
return jsonify({'message': "Invalid credentials, retry"}), 401
return "True"
The flask api call to upload:
#app.route('/rt/api/v1.0/issues/<int:issue_id>/documents', methods=['POST'])
#jwt_required
def rt_doc_upload(issue_id):
'''
Upload documents for a rt ticket.
'''
# Iterate through the list of files, we don't care about the
# attribute name. We consider only the first file and ignore the
# rest.
if 'id' in session:
uploader = "3"
minternal_only = True
bool_internal_update = False
msg_str = None
for attr, document in request.files.iteritems():
trans = g.conn.begin()
try:
orig_filename = document.filename
filename, upload_folder = check_or_insert_document(
orig_filename, uploader)
new_doc = add_doc(orig_filename, filename)
print orig_filename, 'origooooo'
ins = archival_docs.insert().values(new_doc)
rs = g.conn.execute(ins)
doc_id = rs.inserted_primary_key[0]
filename = (str(doc_id) + '_' + orig_filename)
stmt = archival_docs.update().values(stored_name=filename).\
where(archival_docs.c.id == doc_id)
g.conn.execute(stmt)
document.save(os.path.join(upload_folder, filename))
mattach_doc_id = genUrl(doc_id)
trans.commit()
return jsonify(
{'issue_doc_id': rs.inserted_primary_key[0]}), 201
except Exception, e:
print e
trans.rollback()
return jsonify({'message': "Did not find any file"}), 400
return jsonify({'message': "UNAUTHORIZED"}), 401
When used with runserver and on commenting the jwt_required decorator I am able to upload and download files
Using sqlalchemy core, python and flask. The api call to upload worked for more than a month, but suddenly stopped working now
I'm attempting to submit my form, but it continually fails as there's something wrong with the POST. I'm unsure where/what exactly is causing the server to not process the request whether it's related to syntax, request routing, etc. I've also commented out every line related to file uploads, as well as comment out the if (validated) statement. There are no errors in the console as a result of this, but the form submission still fails. I'd appreciate any help/direction thanks.
I get this error message when I submit the form:
POST http://127.0.0.1:5051/register/ 400 (BAD REQUEST)
views.py
#blueprint.route("register/", methods=['GET', 'POST'])
def register():
"""Renders register page."""
form = RegisterForm()
if request.method == 'POST':
if not form.validate_on_submit():
return render_template('main/register.html', page_title="Service Registration",
form=form, form_success=False, media_types=current_app.config["ACCEPTED_"
"MEDIA_TYPE"])
ticket, err = create_ticket2(customer_id, organization + "\n" + venue_name + "\n" + street + "\n" + country + "\n" + teamviewquestion + "\n" + teamviewerid + "\n" + deviations + "\n" + deviationsnotes + "\n" + displaydirector + "\n" + composer + "\n" + decryptor + "\n" + motionrocket + "\n" + othersoftware,
location=location)
if err:
return render_template('main/register.html', page_title="Service Registration",
form=form, form_success=False, message=err, media_types=current_app.config["ACCEPTED_"
"MEDIA_TYPE"])
else:
success_msg = "Error"
.format(ticket.get('id'))
return render_template('main/register.html', page_title="Service Registration",
form=form, form_success=True, message=success_msg, media_types=current_app.config["ACCEPTED_"
"MEDIA_TYPE"])
return render_template('main/register.html', page_title="Service Registration",
form=form, media_types=current_app.config["ACCEPTED_"
"MEDIA_TYPE"])
"""Handles file upload POSTs."""
first_name = request.form.get("first_name")
last_name = request.form.get("last_name")
name = request.form.get("first_name") + " " + request.form.get("last_name")
email = request.form.get("email")
filename = request.form.get("filename")
file_type = request.form.get("file_type")
if filename == '':
response = make_response("No selected file")
return response, 400
if check_file_type(file_type):
filename = clean_filename(filename)
filename = secure_filename(filename)
filename = unique_filename(filename)
response = generate_presigned_post(filename, file_type)
# CREATE DB REFERENCE
url = "http://nevcodocs.s3.amazonaws.com/Uploads/{}".format(filename)
instance = CustomerFileUpload.query.filter_by(url=url).first()
if not instance:
instance = CustomerFileUpload(url=url, email=email, name=name)
db.session.add(instance)
db.session.commit()
else:
instance.update(created_at=datetime.utcnow())
return response, 200
js (ticket submission function)
$('#ticket-form').submit(function(event) {
if (validated) {
$('#filename').val($('#upload').val());
$.ajax({
type: 'POST',
url: '/register/',
data: $('#ticket-form').serialize()
}).done(function(data) {
var formData = new FormData();
for (var key in data.data) {
formData.append(key, data.data[key]);
}
formData.append('file', $('#upload').prop('files')[0]);
formData.append('csrf_token', '{{ csrf_token }}');
var req = new XMLHttpRequest();
req.onload = function() {
showSpinner(false);
$('#ticket-form').removeClass("support-form-show");
$('#ticket-form').addClass("support-form-hide");
};
req.onerror = function() {
showSpinner(false);
$('#ticket-form-failed').removeClass("support-form-hide");
$('#ticket-form-failed').addClass("support-form-show");
};
req.open('POST', '/register/');
req.send(formData);
}).fail(function(err) {
showSpinner(false);
$('#ticket-form-failed').removeClass("support-form-hide");
$('#ticket-form-failed').addClass("support-form-show");
});
} else {
showSpinner(false);
enableSubmit(true);
}
});
Usually, bad request means that you're trying to fetch data from request object using invalid keys. So you need to make sure that your POST request body (that was sent by javascript) contains all keys which you're using as arguments of request.form.get() method: first_name, last_name, etc...
When I request something to python by AJAX, everything runs OK in python, but, when the route return my informations for AJAX, simply he create another blank page with the text that I returned, and not did what I want in the page who needs to be.
Here the response image
image2
Here is the code:
#app.route('/', methods=['POST', 'GET'])
def bot():
texto = request.form['text']
print(texto)
conversation = ConversationV1(
username='a33eb2c9-d218-4e05-a8ff-a46b59c5c3b1',
password='VATP3XEHsrPL',
version='2017-05-26'
)
context = {}
workspace_id = '96cbce3b-2fd3-49b0-ad57-da62c33547ee'
user = texto
response = conversation.message(
workspace_id=workspace_id,
message_input={'text': user},
context=context
)
context = response['context']
#se há intenções e dialogo
if response['intents'] or response['entities']:
if response['intents']:
intent = (json.dumps(response['intents'][0]['intent'],indent = 2))
intent = intent[1:-1]
dialog = (json.dumps(response['output']['nodes_visited'][0],indent = 2))
dialog = dialog[1:-1]
#se há resesposta à intenção
if response['output']['text']:
resposta = json.dumps(response['output']['text'][0],sort_keys=True, indent=4)
resposta = resposta[1:-1]
resposta = resposta.encode('utf-8')
resp = (resposta.decode('unicode-escape'))
#se entrou no nó x,y,z
if dialog == "perfil_e_id":
ID = (json.dumps(response['entities'][0]['value'],indent = 2))
ID = ID[1:-1]
print (ID)
resp = perfill(ID)
elif dialog == "perfil":
return resp
ID = texto
print ("Ikrl : " + ID)
resp = perfil()
elif dialog == "heroi":
ID = (json.dumps(response['entities'][0]['value']))
ID = ID[1:-1]
resp = herostats(int(ID))
return resp
elif dialog == "counterheroi":
ID = (json.dumps(response['entities'][0]['value']))
ID = ID[1:-1]
resp = herostats(int(ID))
return resp
else:
resposta = json.dumps(response['output']['text'][0],sort_keys=True, indent=4)
resposta = resposta[1:-1]
resposta = resposta.encode('utf-8')
resp = (resposta.decode('unicode-escape'))
print (resp)
return resp
And my ajax code:
$(function(){
$(".mytext").on("keyup", function(e){
if (e.which == 13){
var text = $(this).val();
if (text !== ""){
insertChat("me", text);
document.getElementById("nome").innerHTML = text;
$(this).val('');
}
$.ajax({
url: '/',
data: $(text),
type: 'POST',
success: function(response){
console.log(response);
insertChat("you", response)
},
error: function(error){
console.log(error)
}
})
}
});
});
if you need test in your pc, I upload a .rar file
https://drive.google.com/open?id=0B9TVHd_5neJ1amdqZWVrbm9mX2c
You haven't cancelled the default submit action.
if (e.which == 13){
e.preventDefault();
...