I have created a FLASK app which preforms CRUD operations on an SQL database. I had everything work a few days ago but now when using the web interface the HTML pages aren't working when clicked. For example after entering valid details and clicking login the URL now looks like:
incorrect url path
when it should redirect to
correct url path
showing in terminal
terminal
This is my folder layout
folder layout
My AJAX call to redirect to main.html
`
// Login a user
function userLogin() {
data = getLogin()
console.log(data)
$.ajax({
url:"http://127.0.0.1:5000/login",
data: JSON.stringify(data),
method:"POST",
dataType:"JSON",
contentType: "application/json; charset=utf-8",
success: function(result) {
if (result == 1) {
window.location.replace("main.html"); // Redirect to to main.html if successful
}
},
error: function(xhr, status, error){
window.alert("Invaild username and/or password");
console.log("error "+ error + " code "+ status)
}
})
}
`
Flask Server route:
`
# Homepage route
#app.route('/')
def index():
if not 'username' in session:
return app.send_static_file('index.html')
# Login
#app.route("/login", methods = ["POST"])
def login():
account = {
"username":request.json["username"],
"password":request.json["password"]
}
return jsonify(bookmarkDAO.login(account))
`
I've tried deleting the cache, changing my folder directories around and I even tried an older version which correctly worked from my github repository but now it is even throwing the same error. I am using VS Code, could it possibly be an issue with the terminal?
You are not trailing the main.html with /
Change this
window.location.replace("main.html")
to
window.location.replace("/main.html")
Related
I am trying to use react to get data from an API (Python, I'm hosting it on the same machine).
API Code:
from flask import Flask, jsonify, request
app = Flask(__name__)
#app.route('/')
def all_data():
all_data = "Hello"
return jsonify({
'data':all_data,
'message':"success"
}), 200
if __name__ == "__main__":
app.run(debug=True)
React code(Didn't include the render()):
export default class HomeScreen extends Component {
constructor(props){
super(props);
this.state = {
listData:[],
url:"http://localhost:5000"
}
}
getPlanets=()=>{
console.log("Axios called")
const url = this.state.url;
console.log(url)
axios.get(url).then((response)=>{
console.log(response.data)
return this.setState({listData:response.data})
}).catch((error)=>{
console.log(error.message)
Alert.alert(error.message);
})
}
componentDidMount(){
this.getPlanets();
}
}
I'm always getting Network Error for the console.log(error.message).
I'm also getting a larger Error: "Network Error" in Error: Network Error << at e.exports (axios.js:3:7286) << at d.onerror (axios.js:3:6270) for console.log(error).
Simultaneously, I got two weird error messages in my API:
code 400, message Bad request version ('localhost\x00\x17\x00\x00ÿ\x01\x00\x01\x00\x00')
"▬♥☺☻☺☺ü♥♥ÆuaTÁS¾eài ¸ ²`½‼/cùCf{&*½(¨qh↓(â®z↨Ó ×D ÚÚ‼☺‼☻‼♥À+À/À,À0̨̩À‼À¶úú♫♀ l
ocalhost↨ÿ☺☺" HTTPStatus.BAD_REQUEST -
Help?
I've tried looking through a lot of websites for the problem, but they all just suggested adding the http:// prefix to my url, which I had already done. I'm also using Python for the API and not NodeJS, so I don't need to use CORS. I just couldn't find a relevant fix anywhere.
I'm currently using Flasks's development server instead of using a separate one because I don't need the extra bulk. My server will not be processing many requests at once, so I feel the development server is fine enough.
What I'm Trying To Do
I have a python script that I'm trying to run with the click of a button on a web page. This web page is run on an Apache 2 web server on Ubuntu.
What I've Done
I've installed Flask and tried to post to my python script, but I always get this error:
* Serving Flask app "ResetPOE" (lazy loading)
* Environment: production WARNING: Do not use the development server in a production environment. Use a production WSGI server instead. * Debug mode: on
It always returns to my error block in my Ajax request and never to my success block. I do not get any return JSON from my Python script. I just want to know whether or not my script ran, I don't necessarily need any output from the script itself.
P.S. my Python may be incorrect, but I haven't even gotten it to recognize it yet, so that's been on the back burner for now. I'm just trying to get the post request to be successful.
ajax.js
function ajaxCall(input) {
var data = {"param" : input};
$.ajax({
url: "/cgi-bin/reset.py/request",
type: "POST",
contentType: "application/json",
data: JSON.stringify(data),
dataType: 'json',
success: function(response){
console.log("success");
console.log(response);
},
error: function(xhr, status, error) {
console.log("error");
var err = xhr.responseText;
console.log(err);
}
});
}
reset.py
#!/usr/bin/python3
print("Content-type: text/html")
print ("")
from flask import Flask, request, jsonify
import json
app = Flask(__name__)
#app.route('/')
def sendOK(environ, start_response):
status = '200 OK'
output = "Hello World!"
response_headers = [('Content-type', 'text/plain'),('Content-Length', str(len(output)))]
start_response(status, response_headers)
return [output]
#app.route('/request', methods=['POST'])
def processRequest():
data = request.form["param"]
# other code to do stuff with the data...
return Response(json.dumps({"status":"success"}), mimetype="application/json")
if __name__=="__main__":
app.run(debug=True, threaded=True, host="192.168.1.101")
It returns a 200 (OK) in my browser, but I'm not getting any return values, and I can tell my error block is executing and not my success block.
My Html page isn't rendered on ajax success when I use console.log() in the js file, the HTML page is printed out in the browser console but not in the browser itself.
kindly check my following code:
views.py:
def Filter_by_Products(request):
if request.is_ajax():
if request.method == 'GET':
print("filter by function!")
filter_brand = request.GET.get('filter_brand')
products_qs, qs_color, qs_size = product.objects.Filter_brand(filter_brand.rstrip(','))
context={
"object_list": products_qs,
'colors': qs_color,
'sizes':qs_size
}
# print(products_qs)
# print(qs_color)
# print(qs_size)
return render(request,"product/products.html",context)
ajax.js:
$.ajax({
url:'/cart/api/filterby/',
method:'get',
data:
{
'filter_brand':str,
},
success: function (data) {
console.log(data)
// location.reload()
},
error: function (error) {
console.log(error)
}
})
After googling on my question, I found that my problem is that I'm trying to mix the server side with the client side and the solution is to send my HTML template using HttpResponse not render function and then by using javascript, I select the HTML page and change content with the new html.
Actually, I didn't understand clearly the problem and why mixing server with client caused that problem and why my code wasn't working from the first time using render, so could you please explain more in details or refer links to me to understand.
also, I'm familiar with Django celery and Redis, if i can use those technologies in that situation, could you just refer to me how to use them.
When i'm working with Django and Ajax, i like to use JsonResponse, a library from django.http. This way, I can pass the status response (200, 500, ...), and the data that will be treated in front.
The problem in your case, is that after you received the response, you are reloading the page.
// location.reload()
As your responde data is an object, you have to define, using javascript, where it will be placed on the screen, for example:
success: function (data) {
console.log(data);
$("#div_object_list").html(data.object_list);
},
No problem in return render(request,"product/products.html",context), it will return a rendered html page's content.
The problem is in your ajax request calling: // location.reload(), referring to w3schools.com it reloads current page only without replacing page's content with returned response.
If you need to replace the entire page with returned response, so your ajax success function should like:
success: function (response) {
var newDoc = document.open("text/html", "replace");
newDoc.write(response);
newDoc.close();
}
If you just need to replace with specific html div, you can do:
success: function(response) {
$('#my-div').html(response);
}
Could you please help me with Python-Flask server misunderstanding. I have some project with flask, it perfectly works on local server 127.0.0.1, but when I moved it to the Web Server (blue host), some of my script give me these errors:
Here I have jQuery, Ajax response to show a table without reloading page:
<button class="myButton" id = "Lbutton">Load</button>
<script>
$("#Lbutton").click(function(){
$.ajax({
url: "/table,
type: "get",
data: {jsdata: $( "#select option:selected" ).text()},
success: function(response) {
$("#place_for_suggestions").html(response);
},
error: function(xhr) {
// handle error
}
});
});
</script>
url: "/table, is the link for Flask function:
#FlaskApp2.route('/table')
def table():
modid = request.args.get('jsdata')
return render_template('table.html')
But finally the Server gave me error:
File does not exist: /home1/user/public_html/table
Why direct link for action, server understand like a link for a file?
So, every action to Python-Flask
<form action="/sendemail" method="post">
the Server understand like a link and give an error message !
What I'm doing wrong ?
Solved, I need to put the full path in action and route() decorator #app.route "/.../templates/table.html"
Most likely you need to add the POST method to your route definition.
#FlaskApp2.route('/table')
becomes:
#FlaskApp2.route('/table', methods=['GET', 'POST'])
Check out the documentation here:
http://flask.pocoo.org/docs/0.12/quickstart/#http-methods
Which has an example of an endpoint that accepts both GET and POST HTTP methods.
Also check out a related question: Flask example with POST
I've got an app on Google App Engine for which I use the webapp2 authentication as described in this tutorial (thus Google Account API is not being used for user account management).
Therefore I'm using this Google tutorial to implement Google+ Sign-In. The front-end works fine, however I am having troubles with the callback. I would like to do this without Flask, since the only thing it seems to be used for is generating a response. The original code for the first part of the callback is:
if request.args.get('state', '') != session['state']:
response = make_response(json.dumps('Invalid state parameter.'), 401)
response.headers['Content-Type'] = 'application/json'
return response
To get rid of the Flask dependency, I rewrote this to:
if self.request.get('state') != self.session.get('state'):
msg = json.dumps('Invalid state parameter.')
self.response.headers["Content-Type"] = 'application/json'
self.response.set_status(401)
return self.response.out.write(msg)
The problem though, is that self.request.get('state') returns nothing. I'm guessing this is because I am not reading the response properly, however I don't know how to do it right.
The Javascript that launches the callback is:
function signInCallback(authResult) {
if (authResult['code']) {
// Send the code to the server
$.ajax({
type: 'POST',
url: '/signup/gauth',
contentType: 'application/octet-stream; charset=utf-8',
success: function(result) {
console.log(result),
processData: false,
data: authResult['code']
});
} else if (authResult['error']) {
// There was an error.
// Possible error codes:
// "access_denied" - User denied access to your app
// "immediate_failed" - Could not automatially log in the user
console.log('There was an error: ' + authResult['error']);
}
}